Remove Tabs, per Jococo
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / PropAccess.java
index a35777f..1bf0230 100644 (file)
@@ -3,6 +3,8 @@
  * org.onap.aaf
  * ===========================================================================
  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * 
+ * Modifications Copyright (C) 2018 IBM.
  * ===========================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.aaf.cadi;
 
+import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.StringBufferInputStream;
+import java.io.StringWriter;
+import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
@@ -35,14 +42,20 @@ import java.util.Properties;
 
 import org.onap.aaf.cadi.config.Config;
 import org.onap.aaf.cadi.config.SecurityInfo;
+import org.onap.aaf.cadi.util.Split;
 
 public class PropAccess implements Access {
     // Sonar says cannot be static... it's ok.  not too many PropAccesses created.
-    private final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
+    private final SimpleDateFormat iso8601 = newISO8601();
+    private Symm symm;
+            
+    public static SimpleDateFormat newISO8601() {
+        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
+    }
 
     public static final Level DEFAULT = Level.AUDIT;
     
-    private Symm symm;
+    
     private int level;
     private Properties props;
     private List<String> recursionProtection = null;
@@ -89,43 +102,48 @@ public class PropAccess implements Access {
         this.logIt = logIt;
         Properties nprops=new Properties();
         int eq;
-        for(String arg : args) {
-            if((eq=arg.indexOf('='))>0) {
+        for (String arg : args) {
+            if ((eq=arg.indexOf('='))>0) {
                 nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1));
             }
         }
         init(nprops);
     }
     
-    protected void init(Properties p) {
+    protected synchronized void init(Properties p) {
         // Make sure these two are set before any changes in Logging
         name = "cadi";
-        level=DEFAULT.maskOf();
         
         props = new Properties();
         // First, load related System Properties
-        for(Entry<Object,Object> es : System.getProperties().entrySet()) {
+        for (Entry<Object,Object> es : System.getProperties().entrySet()) {
             String key = es.getKey().toString();
-            for(String start : new String[] {"cadi_","aaf_","cm_"}) {
-                if(key.startsWith(start)) {
+            for (String start : new String[] {"cadi_","aaf_","cm_"}) {
+                if (key.startsWith(start)) {
                     props.put(key, es.getValue());
                 }
             }            
         }
         // Second, overlay or fill in with Passed in Props
-        if(p!=null) {
+        if (p!=null) {
             props.putAll(p);
         }
         
+        // Preset LogLevel
+        String sLevel = props.getProperty(Config.CADI_LOGLEVEL); 
         // Third, load any Chained Property Files
         load(props.getProperty(Config.CADI_PROP_FILES));
         
-        String sLevel = props.getProperty(Config.CADI_LOGLEVEL); 
-        if(sLevel!=null) {
-            level=Level.valueOf(sLevel).maskOf(); 
+        if(sLevel==null) { // if LogLev wasn't set before, check again after Chained Load
+            sLevel = props.getProperty(Config.CADI_LOGLEVEL); 
+            if (sLevel==null) {
+                level=DEFAULT.maskOf();
+            } else {
+                level=Level.valueOf(sLevel).maskOf(); 
+            }
         }
         // Setup local Symmetrical key encryption
-        if(symm==null) {
+        if (symm==null) {
             try {
                 symm = Symm.obtain(this);
             } catch (CadiException e) {
@@ -137,57 +155,48 @@ public class PropAccess implements Access {
         
         name = props.getProperty(Config.CADI_LOGNAME, name);
         
-        specialConversions();
-    }
-
-    private void specialConversions() {
-        // Critical - if no Security Protocols set, then set it.  We'll just get messed up if not
-        if(props.get(Config.CADI_PROTOCOLS)==null) {
-            props.setProperty(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT);
-        }
-        
-        Object temp;
-        temp=props.get(Config.CADI_PROTOCOLS);
-        if(props.get(Config.HTTPS_PROTOCOLS)==null && temp!=null) {
-            props.put(Config.HTTPS_PROTOCOLS, temp);
-        }
+        SecurityInfo.setHTTPProtocols(this);
         
-        if(temp!=null) {
-            if("1.7".equals(System.getProperty("java.specification.version")) 
-                    && (temp==null || (temp instanceof String && ((String)temp).contains("TLSv1.2")))) {
-                System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT);
-            }
-        }
     }
-
+    
+   
     private void load(String cadi_prop_files) {
-        if(cadi_prop_files==null) {
+        if (cadi_prop_files==null) {
             return;
         }
         String prevKeyFile = props.getProperty(Config.CADI_KEYFILE);
-        int prev = 0, end = cadi_prop_files.length();
-        int idx;
-        String filename;
-        while(prev<end) {
-            idx = cadi_prop_files.indexOf(File.pathSeparatorChar,prev);
-            if(idx<0) {
-                idx = end;
-            }
-            File file = new File(filename=cadi_prop_files.substring(prev,idx));
-            if(file.exists()) {
+
+        
+        for(String filename : Split.splitTrim(File.pathSeparatorChar, cadi_prop_files)) {
+            Properties fileProps = new Properties();
+            File file = new File(filename);
+            if (file.exists()) {
                 printf(Level.INIT,"Loading CADI Properties from %s",file.getAbsolutePath());
                 try {
                     FileInputStream fis = new FileInputStream(file);
                     try {
-                        props.load(fis);
+                        fileProps.load(fis);
+                        // Only load props from recursion which are not already in props
+                        // meaning top Property file takes precedence
+                        for(Entry<Object, Object> es : fileProps.entrySet()) {
+                            if(props.get(es.getKey())==null) {
+                                String key = es.getKey().toString();
+                                String value = es.getValue().toString();
+                                props.put(key, value);
+                                if(key.contains("pass")) {
+                                    value = "XXXXXXX";
+                                }
+                                printf(Level.DEBUG,"  %s=%s",key,value);
+                            }
+                        }
                         // Recursively Load
-                        String chainProp = props.getProperty(Config.CADI_PROP_FILES);
-                        if(chainProp!=null) {
-                            if(recursionProtection==null) {
+                        String chainProp = fileProps.getProperty(Config.CADI_PROP_FILES);
+                        if (chainProp!=null) {
+                            if (recursionProtection==null) {
                                 recursionProtection = new ArrayList<>();
                                 recursionProtection.add(cadi_prop_files);
                             }
-                            if(!recursionProtection.contains(chainProp)) {
+                            if (!recursionProtection.contains(chainProp)) {
                                 recursionProtection.add(chainProp);
                                 load(chainProp); // recurse
                             }
@@ -201,27 +210,26 @@ public class PropAccess implements Access {
             } else {
                 printf(Level.WARN,"Warning: recursive CADI Property %s does not exist",file.getAbsolutePath());
             }
-            prev = idx+1;
         }
         
         // Trim 
-        for(Entry<Object, Object> es : props.entrySet()) {
+        for (Entry<Object, Object> es : props.entrySet()) {
             Object value = es.getValue();
-            if(value instanceof String) {
+            if (value instanceof String) {
                 String trim = ((String)value).trim();
                 // Remove Beginning/End Quotes, which might be there if mixed with Bash Props
                 int s = 0, e=trim.length()-1;
-                if(s<e && trim.charAt(s)=='"' && trim.charAt(e)=='"') {
+                if (s<e && trim.charAt(s)=='"' && trim.charAt(e)=='"') {
                     trim=trim.substring(s+1,e);
                 }
-                if(trim!=value) { // Yes, I want OBJECT equals
+                if (trim!=value) { // Yes, I want OBJECT equals
                     props.setProperty((String)es.getKey(), trim);
                 }
             }
         }
         // Reset Symm if Keyfile Changes:
         String newKeyFile = props.getProperty(Config.CADI_KEYFILE);
-        if((prevKeyFile!=null && newKeyFile!=null) || (newKeyFile!=null && !newKeyFile.equals(prevKeyFile))) {
+        if ((prevKeyFile!=null && newKeyFile!=null) || (newKeyFile!=null && !newKeyFile.equals(prevKeyFile))) {
             try {
                 symm = Symm.obtain(this);
             } catch (CadiException e) {
@@ -234,15 +242,13 @@ public class PropAccess implements Access {
         }
         
         String loglevel = props.getProperty(Config.CADI_LOGLEVEL);
-        if(loglevel!=null) {
+        if (loglevel!=null) {
             try {
                 level=Level.valueOf(loglevel).maskOf();
             } catch (IllegalArgumentException e) {
                 printf(Level.ERROR,"%s=%s is an Invalid Log Level",Config.CADI_LOGLEVEL,loglevel);
             }
         }
-        
-        specialConversions();
     }
     
     @Override
@@ -253,43 +259,67 @@ public class PropAccess implements Access {
 
     @Override
     public void log(Level level, Object ... elements) {
-        if(willLog(level)) {
+        if (willLog(level)) {
             logIt.push(level,elements);
         }
     }
 
-    protected StringBuilder buildMsg(Level level, Object[] elements) {
+    public StringBuilder buildMsg(Level level, Object[] elements) {
         return buildMsg(name,iso8601,level,elements);
     }
-
-    public static StringBuilder buildMsg(final String name, final SimpleDateFormat sdf, Level level, Object[] elements) { 
-        StringBuilder sb = new StringBuilder(sdf.format(new Date()));
-        sb.append(' ');
-        sb.append(level.name());
-        sb.append(" [");
-        sb.append(name);
-        
+    
+    /*
+     * Need to pass in DateFormat per thread, because not marked as thread safe
+     */
+    public static StringBuilder buildMsg(final String name, final DateFormat sdf, Level level, Object[] elements) {
+        final StringBuilder sb;
         int end = elements.length;
-        if(end<=0) {
-            sb.append("] ");
+        if(sdf==null) {
+            sb = new StringBuilder();
+            write(true,sb,elements);
         } else {
-            int idx = 0;
-            if(elements[idx] instanceof Integer) {
-                sb.append('-');
-                sb.append(elements[idx]);
-                ++idx;
+            sb = new StringBuilder(
+                    sdf.format(new Date())
+                    );
+            sb.append(' ');
+            sb.append(level.name());
+            sb.append(" [");
+            sb.append(name);
+            if (end<=0) {
+                sb.append("] ");
+            } else {
+                int idx = 0;
+                if(elements[idx]!=null  && 
+                    elements[idx] instanceof Integer) {
+                    sb.append('-');
+                    sb.append(elements[idx]);
+                    ++idx;
+                }
+                sb.append("] ");
+                write(true,sb,elements);
             }
-            sb.append("] ");
-            String s;
-            boolean first = true;
-            for(Object o : elements) {
-                if(o!=null) {
+        }
+        return sb;
+    }
+    
+    private static boolean write(boolean first, StringBuilder sb, Object[] elements) {
+        String s;
+        for (Object o : elements) {
+            if (o!=null) {
+                if(o.getClass().isArray()) {
+                    first = write(first,sb,(Object[])o);
+                } else if(o instanceof Throwable) {
+                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                    PrintStream ps = new PrintStream(baos);
+                    ((Throwable)o).printStackTrace(ps);
+                    sb.append(baos.toString());
+                } else {
                     s=o.toString();
-                    if(first) {
+                    if (first) {
                         first = false;
                     } else {
                         int l = s.length();
-                        if(l>0)    {
+                        if (l>0)    {
                             switch(s.charAt(l-1)) {
                                 case ' ':
                                     break;
@@ -302,18 +332,21 @@ public class PropAccess implements Access {
                 }
             }
         }
-        return sb;
+        return first;
     }
 
     @Override
     public void log(Exception e, Object... elements) {
-        log(Level.ERROR,e.getMessage(),elements);
-        e.printStackTrace(System.err);
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        pw.println();
+        e.printStackTrace(pw);
+        log(Level.ERROR,elements,sw.toString());
     }
 
     @Override
     public void printf(Level level, String fmt, Object... elements) {
-        if(willLog(level)) {
+        if (willLog(level)) {
             log(level,String.format(fmt, elements));
         }
     }
@@ -362,9 +395,9 @@ public class PropAccess implements Access {
     }
 
     public void setProperty(String tag, String value) {
-        if(value!=null) {
+        if (value!=null) {
             props.put(tag, value);
-            if(Config.CADI_KEYFILE.equals(tag)) {
+            if (Config.CADI_KEYFILE.equals(tag)) {
                 // reset decryption too
                 try {
                     symm = Symm.obtain(this);
@@ -392,10 +425,17 @@ public class PropAccess implements Access {
             ps.println(buildMsg(level,elements));
             ps.flush();
         }
-        
     }
 
     public void set(LogIt logit) {
         logIt = logit;
     }
+
+    public void setStreamLogIt(PrintStream ps) {
+        logIt = new StreamLogIt(ps);
+    }
+
+    public String toString() {
+        return props.toString();
+    }
 }