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;
24 import java.io.ByteArrayOutputStream;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.PrintStream;
30 import java.io.PrintWriter;
31 import java.io.StringBufferInputStream;
32 import java.io.StringWriter;
33 import java.text.DateFormat;
34 import java.text.SimpleDateFormat;
35 import java.util.ArrayList;
36 import java.util.Date;
37 import java.util.List;
38 import java.util.Map.Entry;
39 import java.util.Properties;
41 import org.onap.aaf.cadi.config.Config;
42 import org.onap.aaf.cadi.config.SecurityInfo;
43 import org.onap.aaf.cadi.util.Split;
45 public class PropAccess implements Access {
46 // Sonar says cannot be static... it's ok. not too many PropAccesses created.
47 private final SimpleDateFormat iso8601 = newISO8601();
49 public static SimpleDateFormat newISO8601() {
50 return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
53 public static final Level DEFAULT = Level.AUDIT;
57 private Properties props;
58 private List<String> recursionProtection = null;
63 logIt = new StreamLogIt(System.out);
68 * This Constructor soly exists to instantiate Servlet Context Based Logging that will call "init" later.
71 protected PropAccess(Object o) {
72 logIt = new StreamLogIt(System.out);
73 props = new Properties();
76 public PropAccess(String ... args) {
77 this(System.out,args);
80 public PropAccess(PrintStream ps, String[] args) {
81 logIt = new StreamLogIt(ps==null?System.out:ps);
85 public PropAccess(LogIt logit, String[] args) {
89 public PropAccess(Properties p) {
93 public PropAccess(PrintStream ps, Properties p) {
94 logIt = new StreamLogIt(ps==null?System.out:ps);
98 protected void init(final LogIt logIt, final String[] args) {
100 Properties nprops=new Properties();
102 for (String arg : args) {
103 if ((eq=arg.indexOf('='))>0) {
104 nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1));
110 protected synchronized void init(Properties p) {
111 // Make sure these two are set before any changes in Logging
114 props = new Properties();
115 // First, load related System Properties
116 for (Entry<Object,Object> es : System.getProperties().entrySet()) {
117 String key = es.getKey().toString();
118 for (String start : new String[] {"cadi_","aaf_","cm_"}) {
119 if (key.startsWith(start)) {
120 props.put(key, es.getValue());
124 // Second, overlay or fill in with Passed in Props
130 String sLevel = props.getProperty(Config.CADI_LOGLEVEL);
131 // Third, load any Chained Property Files
132 load(props.getProperty(Config.CADI_PROP_FILES));
134 if(sLevel==null) { // if LogLev wasn't set before, check again after Chained Load
135 sLevel = props.getProperty(Config.CADI_LOGLEVEL);
137 level=DEFAULT.maskOf();
139 level=Level.valueOf(sLevel).maskOf();
142 // Setup local Symmetrical key encryption
145 symm = Symm.obtain(this);
146 } catch (CadiException e) {
147 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
148 e.printStackTrace(System.err);
153 name = props.getProperty(Config.CADI_LOGNAME, name);
155 SecurityInfo.setHTTPProtocols(this);
160 private void load(String cadi_prop_files) {
161 if (cadi_prop_files==null) {
164 String prevKeyFile = props.getProperty(Config.CADI_KEYFILE);
167 for(String filename : Split.splitTrim(File.pathSeparatorChar, cadi_prop_files)) {
168 Properties fileProps = new Properties();
169 File file = new File(filename);
171 printf(Level.INIT,"Loading CADI Properties from %s",file.getAbsolutePath());
173 FileInputStream fis = new FileInputStream(file);
176 // Only load props from recursion which are not already in props
177 // meaning top Property file takes precedence
178 for(Entry<Object, Object> es : fileProps.entrySet()) {
179 if(props.get(es.getKey())==null) {
180 String key = es.getKey().toString();
181 String value = es.getValue().toString();
182 props.put(key, value);
183 if(key.contains("pass")) {
186 printf(Level.DEBUG," %s=%s",key,value);
190 String chainProp = fileProps.getProperty(Config.CADI_PROP_FILES);
191 if (chainProp!=null) {
192 if (recursionProtection==null) {
193 recursionProtection = new ArrayList<>();
194 recursionProtection.add(cadi_prop_files);
196 if (!recursionProtection.contains(chainProp)) {
197 recursionProtection.add(chainProp);
198 load(chainProp); // recurse
204 } catch (Exception e) {
205 log(e,filename,"cannot be opened");
208 printf(Level.WARN,"Warning: recursive CADI Property %s does not exist",file.getAbsolutePath());
213 for (Entry<Object, Object> es : props.entrySet()) {
214 Object value = es.getValue();
215 if (value instanceof String) {
216 String trim = ((String)value).trim();
217 // Remove Beginning/End Quotes, which might be there if mixed with Bash Props
218 int s = 0, e=trim.length()-1;
219 if (s<e && trim.charAt(s)=='"' && trim.charAt(e)=='"') {
220 trim=trim.substring(s+1,e);
222 if (trim!=value) { // Yes, I want OBJECT equals
223 props.setProperty((String)es.getKey(), trim);
227 // Reset Symm if Keyfile Changes:
228 String newKeyFile = props.getProperty(Config.CADI_KEYFILE);
229 if ((prevKeyFile!=null && newKeyFile!=null) || (newKeyFile!=null && !newKeyFile.equals(prevKeyFile))) {
231 symm = Symm.obtain(this);
232 } catch (CadiException e) {
233 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
234 e.printStackTrace(System.err);
238 prevKeyFile=newKeyFile;
241 String loglevel = props.getProperty(Config.CADI_LOGLEVEL);
242 if (loglevel!=null) {
244 level=Level.valueOf(loglevel).maskOf();
245 } catch (IllegalArgumentException e) {
246 printf(Level.ERROR,"%s=%s is an Invalid Log Level",Config.CADI_LOGLEVEL,loglevel);
252 public void load(InputStream is) throws IOException {
254 load(props.getProperty(Config.CADI_PROP_FILES));
258 public void log(Level level, Object ... elements) {
259 if (willLog(level)) {
260 logIt.push(level,elements);
264 public StringBuilder buildMsg(Level level, Object[] elements) {
265 return buildMsg(name,iso8601,level,elements);
269 * Need to pass in DateFormat per thread, because not marked as thread safe
271 public static StringBuilder buildMsg(final String name, final DateFormat sdf, Level level, Object[] elements) {
272 final StringBuilder sb;
273 int end = elements.length;
275 sb = new StringBuilder();
276 write(true,sb,elements);
278 sb = new StringBuilder(
279 sdf.format(new Date())
282 sb.append(level.name());
289 if(elements[idx]!=null &&
290 elements[idx] instanceof Integer) {
292 sb.append(elements[idx]);
296 write(true,sb,elements);
302 private static boolean write(boolean first, StringBuilder sb, Object[] elements) {
304 for (Object o : elements) {
306 if(o.getClass().isArray()) {
307 first = write(first,sb,(Object[])o);
308 } else if(o instanceof Throwable) {
309 ByteArrayOutputStream baos = new ByteArrayOutputStream();
310 PrintStream ps = new PrintStream(baos);
311 ((Throwable)o).printStackTrace(ps);
312 sb.append(baos.toString());
320 switch(s.charAt(l-1)) {
336 public void log(Exception e, Object... elements) {
337 StringWriter sw = new StringWriter();
338 PrintWriter pw = new PrintWriter(sw);
340 e.printStackTrace(pw);
341 log(Level.ERROR,elements,sw.toString());
345 public void printf(Level level, String fmt, Object... elements) {
346 if (willLog(level)) {
347 log(level,String.format(fmt, elements));
352 public void setLogLevel(Level level) {
353 this.level = level.maskOf();
357 public boolean willLog(Level level) {
358 return level.inMask(this.level);
362 public ClassLoader classLoader() {
363 return ClassLoader.getSystemClassLoader();
367 public String getProperty(String tag, String def) {
368 return props.getProperty(tag,def);
372 public String decrypt(String encrypted, boolean anytext) throws IOException {
373 return (encrypted!=null && (anytext==true || encrypted.startsWith(Symm.ENC)))
374 ? symm.depass(encrypted)
378 public String encrypt(String unencrypted) throws IOException {
379 return Symm.ENC+symm.enpass(unencrypted);
385 public String getProperty(String tag) {
386 return props.getProperty(tag);
390 public Properties getProperties() {
394 public void setProperty(String tag, String value) {
396 props.put(tag, value);
397 if (Config.CADI_KEYFILE.equals(tag)) {
398 // reset decryption too
400 symm = Symm.obtain(this);
401 } catch (CadiException e) {
402 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
403 e.printStackTrace(System.err);
410 public interface LogIt {
411 public void push(Level level, Object ... elements) ;
414 private class StreamLogIt implements LogIt {
415 private PrintStream ps;
417 public StreamLogIt(PrintStream ps) {
421 public void push(Level level, Object ... elements) {
422 ps.println(buildMsg(level,elements));
427 public void set(LogIt logit) {
431 public void setStreamLogIt(PrintStream ps) {
432 logIt = new StreamLogIt(ps);
435 public String toString() {
436 return props.toString();