2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.cadi;
25 import java.io.FileInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.PrintStream;
29 import java.io.PrintWriter;
30 import java.io.StringWriter;
31 import java.text.DateFormat;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Date;
35 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Properties;
39 import org.onap.aaf.cadi.config.Config;
40 import org.onap.aaf.cadi.config.SecurityInfo;
41 import org.onap.aaf.cadi.util.Split;
43 public class PropAccess implements Access {
44 // Sonar says cannot be static... it's ok. not too many PropAccesses created.
45 private final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
47 public static final Level DEFAULT = Level.AUDIT;
51 private Properties props;
52 private List<String> recursionProtection = null;
57 logIt = new StreamLogIt(System.out);
62 * This Constructor soly exists to instantiate Servlet Context Based Logging that will call "init" later.
65 protected PropAccess(Object o) {
66 logIt = new StreamLogIt(System.out);
67 props = new Properties();
70 public PropAccess(String ... args) {
71 this(System.out,args);
74 public PropAccess(PrintStream ps, String[] args) {
75 logIt = new StreamLogIt(ps==null?System.out:ps);
79 public PropAccess(LogIt logit, String[] args) {
83 public PropAccess(Properties p) {
87 public PropAccess(PrintStream ps, Properties p) {
88 logIt = new StreamLogIt(ps==null?System.out:ps);
92 protected void init(final LogIt logIt, final String[] args) {
94 Properties nprops=new Properties();
96 for (String arg : args) {
97 if ((eq=arg.indexOf('='))>0) {
98 nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1));
104 protected void init(Properties p) {
105 // Make sure these two are set before any changes in Logging
107 level=DEFAULT.maskOf();
109 props = new Properties();
110 // First, load related System Properties
111 for (Entry<Object,Object> es : System.getProperties().entrySet()) {
112 String key = es.getKey().toString();
113 for (String start : new String[] {"cadi_","aaf_","cm_"}) {
114 if (key.startsWith(start)) {
115 props.put(key, es.getValue());
119 // Second, overlay or fill in with Passed in Props
125 String sLevel = props.getProperty(Config.CADI_LOGLEVEL);
127 level=Level.valueOf(sLevel).maskOf();
130 // Third, load any Chained Property Files
131 load(props.getProperty(Config.CADI_PROP_FILES));
133 if(sLevel==null) { // if LogLev wasn't set before, check again after Chained Load
134 sLevel = props.getProperty(Config.CADI_LOGLEVEL);
136 level=Level.valueOf(sLevel).maskOf();
139 // Setup local Symmetrical key encryption
142 symm = Symm.obtain(this);
143 } catch (CadiException e) {
144 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
145 e.printStackTrace(System.err);
150 name = props.getProperty(Config.CADI_LOGNAME, name);
152 SecurityInfo.setHTTPProtocols(this);
157 private void load(String cadi_prop_files) {
158 if (cadi_prop_files==null) {
161 String prevKeyFile = props.getProperty(Config.CADI_KEYFILE);
164 for(String filename : Split.splitTrim(File.pathSeparatorChar, cadi_prop_files)) {
165 Properties fileProps = new Properties();
166 File file = new File(filename);
168 printf(Level.INIT,"Loading CADI Properties from %s",file.getAbsolutePath());
170 FileInputStream fis = new FileInputStream(file);
173 // Only load props from recursion which are not already in props
174 // meaning top Property file takes precedence
175 for(Entry<Object, Object> es : fileProps.entrySet()) {
176 if(props.get(es.getKey())==null) {
177 String key = es.getKey().toString();
178 String value = es.getValue().toString();
179 props.put(key, value);
180 if(key.contains("pass")) {
183 printf(Level.DEBUG," %s=%s",key,value);
187 String chainProp = fileProps.getProperty(Config.CADI_PROP_FILES);
188 if (chainProp!=null) {
189 if (recursionProtection==null) {
190 recursionProtection = new ArrayList<>();
191 recursionProtection.add(cadi_prop_files);
193 if (!recursionProtection.contains(chainProp)) {
194 recursionProtection.add(chainProp);
195 load(chainProp); // recurse
201 } catch (Exception e) {
202 log(e,filename,"cannot be opened");
205 printf(Level.WARN,"Warning: recursive CADI Property %s does not exist",file.getAbsolutePath());
210 for (Entry<Object, Object> es : props.entrySet()) {
211 Object value = es.getValue();
212 if (value instanceof String) {
213 String trim = ((String)value).trim();
214 // Remove Beginning/End Quotes, which might be there if mixed with Bash Props
215 int s = 0, e=trim.length()-1;
216 if (s<e && trim.charAt(s)=='"' && trim.charAt(e)=='"') {
217 trim=trim.substring(s+1,e);
219 if (trim!=value) { // Yes, I want OBJECT equals
220 props.setProperty((String)es.getKey(), trim);
224 // Reset Symm if Keyfile Changes:
225 String newKeyFile = props.getProperty(Config.CADI_KEYFILE);
226 if ((prevKeyFile!=null && newKeyFile!=null) || (newKeyFile!=null && !newKeyFile.equals(prevKeyFile))) {
228 symm = Symm.obtain(this);
229 } catch (CadiException e) {
230 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
231 e.printStackTrace(System.err);
235 prevKeyFile=newKeyFile;
238 String loglevel = props.getProperty(Config.CADI_LOGLEVEL);
239 if (loglevel!=null) {
241 level=Level.valueOf(loglevel).maskOf();
242 } catch (IllegalArgumentException e) {
243 printf(Level.ERROR,"%s=%s is an Invalid Log Level",Config.CADI_LOGLEVEL,loglevel);
249 public void load(InputStream is) throws IOException {
251 load(props.getProperty(Config.CADI_PROP_FILES));
255 public void log(Level level, Object ... elements) {
256 if (willLog(level)) {
257 logIt.push(level,elements);
261 protected StringBuilder buildMsg(Level level, Object[] elements) {
262 return buildMsg(name,iso8601,level,elements);
265 public static StringBuilder buildMsg(final String name, final DateFormat sdf, Level level, Object[] elements) {
266 final StringBuilder sb;
267 int end = elements.length;
269 sb = new StringBuilder();
270 write(true,sb,elements);
272 sb = new StringBuilder(
273 sdf.format(new Date())
276 sb.append(level.name());
283 if(elements[idx]!=null &&
284 elements[idx] instanceof Integer) {
286 sb.append(elements[idx]);
290 write(true,sb,elements);
296 private static boolean write(boolean first, StringBuilder sb, Object[] elements) {
298 for (Object o : elements) {
300 if(o.getClass().isArray()) {
301 first = write(first,sb,(Object[])o);
309 switch(s.charAt(l-1)) {
325 public void log(Exception e, Object... elements) {
326 StringWriter sw = new StringWriter();
327 PrintWriter pw = new PrintWriter(sw);
329 e.printStackTrace(pw);
330 log(Level.ERROR,elements,sw.toString());
334 public void printf(Level level, String fmt, Object... elements) {
335 if (willLog(level)) {
336 log(level,String.format(fmt, elements));
341 public void setLogLevel(Level level) {
342 this.level = level.maskOf();
346 public boolean willLog(Level level) {
347 return level.inMask(this.level);
351 public ClassLoader classLoader() {
352 return ClassLoader.getSystemClassLoader();
356 public String getProperty(String tag, String def) {
357 return props.getProperty(tag,def);
361 public String decrypt(String encrypted, boolean anytext) throws IOException {
362 return (encrypted!=null && (anytext==true || encrypted.startsWith(Symm.ENC)))
363 ? symm.depass(encrypted)
367 public String encrypt(String unencrypted) throws IOException {
368 return Symm.ENC+symm.enpass(unencrypted);
374 public String getProperty(String tag) {
375 return props.getProperty(tag);
379 public Properties getProperties() {
383 public void setProperty(String tag, String value) {
385 props.put(tag, value);
386 if (Config.CADI_KEYFILE.equals(tag)) {
387 // reset decryption too
389 symm = Symm.obtain(this);
390 } catch (CadiException e) {
391 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
392 e.printStackTrace(System.err);
399 public interface LogIt {
400 public void push(Level level, Object ... elements) ;
403 private class StreamLogIt implements LogIt {
404 private PrintStream ps;
406 public StreamLogIt(PrintStream ps) {
410 public void push(Level level, Object ... elements) {
411 ps.println(buildMsg(level,elements));
416 public void set(LogIt logit) {
420 public void setStreamLogIt(PrintStream ps) {
421 logIt = new StreamLogIt(ps);
424 public String toString() {
425 return props.toString();