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.SimpleDateFormat;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Properties;
38 import org.onap.aaf.cadi.config.Config;
39 import org.onap.aaf.cadi.config.SecurityInfo;
40 import org.onap.aaf.cadi.util.Split;
42 public class PropAccess implements Access {
43 // Sonar says cannot be static... it's ok. not too many PropAccesses created.
44 private final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
46 public static final Level DEFAULT = Level.AUDIT;
50 private Properties props;
51 private List<String> recursionProtection = null;
56 logIt = new StreamLogIt(System.out);
61 * This Constructor soly exists to instantiate Servlet Context Based Logging that will call "init" later.
64 protected PropAccess(Object o) {
65 logIt = new StreamLogIt(System.out);
66 props = new Properties();
69 public PropAccess(String ... args) {
70 this(System.out,args);
73 public PropAccess(PrintStream ps, String[] args) {
74 logIt = new StreamLogIt(ps==null?System.out:ps);
78 public PropAccess(LogIt logit, String[] args) {
82 public PropAccess(Properties p) {
86 public PropAccess(PrintStream ps, Properties p) {
87 logIt = new StreamLogIt(ps==null?System.out:ps);
91 protected void init(final LogIt logIt, final String[] args) {
93 Properties nprops=new Properties();
95 for (String arg : args) {
96 if ((eq=arg.indexOf('='))>0) {
97 nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1));
103 protected void init(Properties p) {
104 // Make sure these two are set before any changes in Logging
106 level=DEFAULT.maskOf();
108 props = new Properties();
109 // First, load related System Properties
110 for (Entry<Object,Object> es : System.getProperties().entrySet()) {
111 String key = es.getKey().toString();
112 for (String start : new String[] {"cadi_","aaf_","cm_"}) {
113 if (key.startsWith(start)) {
114 props.put(key, es.getValue());
118 // Second, overlay or fill in with Passed in Props
124 String sLevel = props.getProperty(Config.CADI_LOGLEVEL);
126 level=Level.valueOf(sLevel).maskOf();
129 // Third, load any Chained Property Files
130 load(props.getProperty(Config.CADI_PROP_FILES));
132 if(sLevel==null) { // if LogLev wasn't set before, check again after Chained Load
133 sLevel = props.getProperty(Config.CADI_LOGLEVEL);
135 level=Level.valueOf(sLevel).maskOf();
138 // Setup local Symmetrical key encryption
141 symm = Symm.obtain(this);
142 } catch (CadiException e) {
143 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
144 e.printStackTrace(System.err);
149 name = props.getProperty(Config.CADI_LOGNAME, name);
151 SecurityInfo.setHTTPProtocols(this);
155 private void load(String cadi_prop_files) {
156 if (cadi_prop_files==null) {
159 String prevKeyFile = props.getProperty(Config.CADI_KEYFILE);
162 for(String filename : Split.splitTrim(File.pathSeparatorChar, cadi_prop_files)) {
163 Properties fileProps = new Properties();
164 File file = new File(filename);
166 printf(Level.INIT,"Loading CADI Properties from %s",file.getAbsolutePath());
168 FileInputStream fis = new FileInputStream(file);
171 // Only load props from recursion which are not already in props
172 // meaning top Property file takes precedence
173 for(Entry<Object, Object> es : fileProps.entrySet()) {
174 if(props.get(es.getKey())==null) {
175 String key = es.getKey().toString();
176 String value = es.getValue().toString();
177 props.put(key, value);
178 if(key.contains("pass")) {
181 printf(Level.DEBUG," %s=%s",key,value);
185 String chainProp = fileProps.getProperty(Config.CADI_PROP_FILES);
186 if (chainProp!=null) {
187 if (recursionProtection==null) {
188 recursionProtection = new ArrayList<>();
189 recursionProtection.add(cadi_prop_files);
191 if (!recursionProtection.contains(chainProp)) {
192 recursionProtection.add(chainProp);
193 load(chainProp); // recurse
199 } catch (Exception e) {
200 log(e,filename,"cannot be opened");
203 printf(Level.WARN,"Warning: recursive CADI Property %s does not exist",file.getAbsolutePath());
208 for (Entry<Object, Object> es : props.entrySet()) {
209 Object value = es.getValue();
210 if (value instanceof String) {
211 String trim = ((String)value).trim();
212 // Remove Beginning/End Quotes, which might be there if mixed with Bash Props
213 int s = 0, e=trim.length()-1;
214 if (s<e && trim.charAt(s)=='"' && trim.charAt(e)=='"') {
215 trim=trim.substring(s+1,e);
217 if (trim!=value) { // Yes, I want OBJECT equals
218 props.setProperty((String)es.getKey(), trim);
222 // Reset Symm if Keyfile Changes:
223 String newKeyFile = props.getProperty(Config.CADI_KEYFILE);
224 if ((prevKeyFile!=null && newKeyFile!=null) || (newKeyFile!=null && !newKeyFile.equals(prevKeyFile))) {
226 symm = Symm.obtain(this);
227 } catch (CadiException e) {
228 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
229 e.printStackTrace(System.err);
233 prevKeyFile=newKeyFile;
236 String loglevel = props.getProperty(Config.CADI_LOGLEVEL);
237 if (loglevel!=null) {
239 level=Level.valueOf(loglevel).maskOf();
240 } catch (IllegalArgumentException e) {
241 printf(Level.ERROR,"%s=%s is an Invalid Log Level",Config.CADI_LOGLEVEL,loglevel);
247 public void load(InputStream is) throws IOException {
249 load(props.getProperty(Config.CADI_PROP_FILES));
253 public void log(Level level, Object ... elements) {
254 if (willLog(level)) {
255 logIt.push(level,elements);
259 protected StringBuilder buildMsg(Level level, Object[] elements) {
260 return buildMsg(name,iso8601,level,elements);
263 public static StringBuilder buildMsg(final String name, final SimpleDateFormat sdf, Level level, Object[] elements) {
264 StringBuilder sb = new StringBuilder(sdf.format(new Date()));
266 sb.append(level.name());
270 int end = elements.length;
275 if(elements[idx]!=null &&
276 elements[idx] instanceof Integer) {
278 sb.append(elements[idx]);
282 write(true,sb,elements);
287 private static boolean write(boolean first, StringBuilder sb, Object[] elements) {
289 for (Object o : elements) {
291 if(o.getClass().isArray()) {
292 first = write(first,sb,(Object[])o);
300 switch(s.charAt(l-1)) {
316 public void log(Exception e, Object... elements) {
317 StringWriter sw = new StringWriter();
318 PrintWriter pw = new PrintWriter(sw);
320 e.printStackTrace(pw);
321 log(Level.ERROR,elements,sw.toString());
325 public void printf(Level level, String fmt, Object... elements) {
326 if (willLog(level)) {
327 log(level,String.format(fmt, elements));
332 public void setLogLevel(Level level) {
333 this.level = level.maskOf();
337 public boolean willLog(Level level) {
338 return level.inMask(this.level);
342 public ClassLoader classLoader() {
343 return ClassLoader.getSystemClassLoader();
347 public String getProperty(String tag, String def) {
348 return props.getProperty(tag,def);
352 public String decrypt(String encrypted, boolean anytext) throws IOException {
353 return (encrypted!=null && (anytext==true || encrypted.startsWith(Symm.ENC)))
354 ? symm.depass(encrypted)
358 public String encrypt(String unencrypted) throws IOException {
359 return Symm.ENC+symm.enpass(unencrypted);
365 public String getProperty(String tag) {
366 return props.getProperty(tag);
370 public Properties getProperties() {
374 public void setProperty(String tag, String value) {
376 props.put(tag, value);
377 if (Config.CADI_KEYFILE.equals(tag)) {
378 // reset decryption too
380 symm = Symm.obtain(this);
381 } catch (CadiException e) {
382 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
383 e.printStackTrace(System.err);
390 public interface LogIt {
391 public void push(Level level, Object ... elements) ;
394 private class StreamLogIt implements LogIt {
395 private PrintStream ps;
397 public StreamLogIt(PrintStream ps) {
401 public void push(Level level, Object ... elements) {
402 ps.println(buildMsg(level,elements));
407 public void set(LogIt logit) {
411 public void setStreamLogIt(PrintStream ps) {
412 logIt = new StreamLogIt(ps);
415 public String toString() {
416 return props.toString();