Enhancements for the aai-common library
[aai/aai-common.git] / aai-els-onap-logging / src / main / java / org / onap / aai / util / AAIApplicationConfig.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-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
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.aai.util;
22
23 import org.apache.commons.io.IOUtils;
24 import org.eclipse.jetty.util.security.Password;
25 import org.onap.aai.exceptions.AAIException;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.charset.Charset;
34 import java.util.Properties;
35 import java.util.UUID;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38
39 public class AAIApplicationConfig {
40
41     private static final Logger LOGGER = LoggerFactory.getLogger(AAIApplicationConfig.class);
42     private static String GLOBAL_PROP_FILE_NAME = "application.properties";
43     private static final String SERVER_CERTS_LOCATION_PROP_NAME = "server.certs.location";
44     private static final String PASSPHRASSES_FILENAME = ".passphrases";
45     private static final String PASSWORD_FILENAME = ".password";
46     private static final String TRUSTSTORE_PASSWORD_PROP_NAME = "cadi_truststore_password";
47     private static final String SERVER_SSL_KEYSTORE_PROP_NAME = "server.ssl.key-store";
48     private static final String SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME = "server.ssl.key-store.pkcs12";
49     private static final String SERVER_SSL_TRUSTSTORE_PROP_NAME = "server.ssl.trust-store";
50     private static Properties serverProps;
51     private static boolean propsInitialized = false;
52     private static String TRUSTSTORE_PASSWORD = null;
53     private static String KEYSTORE_PASSWORD = null;
54     private static final String PROPERTY_REGEX = "\\$\\{([^\\$\\{\\}]+)\\}";
55
56     /**
57      * Instantiates a new AAI config.
58      */
59     // Don't instantiate
60     private AAIApplicationConfig() {
61     }
62
63     /**
64      * Inits the.
65      *
66      * @throws AAIException the AAI exception
67      */
68     public synchronized static void init() {
69         /*LoggingContext.save();
70         LoggingContext.component("config");
71         LoggingContext.partnerName("NA");
72         LoggingContext.targetEntity("AAI");
73         LoggingContext.requestId(UUID.randomUUID().toString());
74         LoggingContext.serviceName("AAI");
75         LoggingContext.targetServiceName("init");
76         LoggingContext.statusCode(StatusCode.COMPLETE);*/
77
78         LOGGER.info("Initializing AAIApplicationConfig");
79
80         AAIApplicationConfig.reloadConfig();
81
82         //LoggingContext.restore();
83     }
84
85     /**
86      * Reload config.
87      */
88     public synchronized static void reloadConfig() {
89
90         Properties newServerProps = new Properties();
91         LOGGER.debug("Reloading config from " + GLOBAL_PROP_FILE_NAME);
92
93         try {
94             InputStream is = AAIApplicationConfig.class.getClassLoader().getResourceAsStream(GLOBAL_PROP_FILE_NAME);
95             newServerProps.load(is);
96             propsInitialized = true;
97             serverProps = newServerProps;
98             TRUSTSTORE_PASSWORD = retrieveTruststorePassword();
99             KEYSTORE_PASSWORD = retrieveKeystorePassword();
100         } catch (Exception fnfe) {
101             final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
102             LOGGER.info("Unable to find the application.properties from filesystem so using file in jar");
103             if (is != null) {
104                 try {
105                     newServerProps.load(is);
106                     serverProps = newServerProps;
107                     TRUSTSTORE_PASSWORD = retrieveTruststorePassword();
108                     KEYSTORE_PASSWORD = retrieveKeystorePassword();
109                 } catch (IOException e) {
110                     LOGGER.warn("Encountered IO Exception during loading of props from inputstream", e);
111                 }
112             } else {
113                 LOGGER.error("Expected to find the properties file in the jar but unable to find it");
114             }
115         }
116     }
117
118     /**
119      * Gets the key value
120      *
121      * @param key          the key
122      * @param defaultValue the default value
123      * @return the string
124      */
125     public static String get(String key, String defaultValue) {
126         String result = defaultValue;
127         try {
128             result = get(key);
129         } catch (AAIException a) {
130         }
131         if (result == null || result.isEmpty()) {
132             result = defaultValue;
133         }
134         return (result);
135     }
136
137     /**
138      * Gets the key value
139      *
140      * @param key the key
141      * @return the string
142      * @throws AAIException the AAI exception
143      */
144     public static String get(String key) throws AAIException {
145         String response = null;
146
147         if (!propsInitialized || (serverProps == null)) {
148             reloadConfig();
149         }
150
151         if ((key.endsWith("password") || key.endsWith("passwd") || key.endsWith("apisecret"))
152                 && serverProps.containsKey(key + ".x")) {
153             String valx = serverProps.getProperty(key + ".x");
154             return Password.deobfuscate(valx);
155         }
156
157         if (!serverProps.containsKey(key)) {
158             throw new AAIException("AAI_4005", "Property key " + key + " cannot be found");
159         } else {
160             response = serverProps.getProperty(key);
161             if (response == null || response.isEmpty()) {
162                 throw new AAIException("AAI_4005", "Property key " + key + " is null or empty");
163             }
164             response = replaceProperties(response);
165         }
166         return response;
167     }
168
169     /**
170      * Gets the keystore path
171      *
172      * @return the string
173      * @throws AAIException the AAI exception
174      */
175     public static String getKeystore() throws AAIException {
176         return (get(SERVER_SSL_KEYSTORE_PROP_NAME));
177     }
178     /**
179      * Gets the PKCS12 keystore path
180      *
181      * @return the string
182      * @throws AAIException the AAI exception
183      */
184     public static String getKeystorePkcs12() throws AAIException {
185         return (get(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME));
186     }
187     /**
188      * Gets the keystore path
189      *
190      * @return the string
191      * @throws AAIException the AAI exception
192      */
193     public static String getTruststore() throws AAIException {
194         return (get(SERVER_SSL_TRUSTSTORE_PROP_NAME));
195     }
196
197     /**
198      * Retrieve the keystore password
199      *
200      * @return the password
201      */
202     private static String retrieveKeystorePassword() {
203         String certPath = serverProps.getProperty(SERVER_CERTS_LOCATION_PROP_NAME);
204         if (certPath == null) {
205             return null;
206         }
207         try {
208             certPath = replaceProperties(certPath);
209         }
210         catch (AAIException e) {
211             return null;
212         }
213
214         File passwordFile = null;
215         InputStream passwordStream = null;
216         String keystorePassword = null;
217
218         // Override the passwords from application.properties if we find AAF certman files
219         try {
220             passwordFile = new File(certPath + PASSWORD_FILENAME);
221             passwordStream = new FileInputStream(passwordFile);
222             keystorePassword = IOUtils.toString(passwordStream, Charset.defaultCharset());
223             if (keystorePassword != null) {
224                 keystorePassword = keystorePassword.trim();
225             }
226
227         } catch (IOException e) {
228             LOGGER.warn("Not using AAF Certman password file, e=" + e.getMessage());
229         } catch (NullPointerException n) {
230             LOGGER.warn("Not using AAF Certman passphrases file, e=" + n.getMessage());
231         } finally {
232             if (passwordStream != null) {
233                 try {
234                     passwordStream.close();
235                 } catch (Exception e) {
236                 }
237             }
238         }
239         return keystorePassword;
240     }
241
242     /**
243      * Get the keystore password
244      *
245      * @return the password
246      */
247     public static String getKeystorePassword() {
248         return (KEYSTORE_PASSWORD);
249     }
250
251     /**
252      * Gets the truststore password
253      *
254      * @return the password
255      */
256     private static String retrieveTruststorePassword() {
257         String certPath = serverProps.getProperty(SERVER_CERTS_LOCATION_PROP_NAME);
258         if (certPath == null) {
259             return null;
260         }
261         try {
262             certPath = replaceProperties(certPath);
263         }
264         catch (AAIException e) {
265             return null;
266         }
267         File passphrasesFile = null;
268         InputStream passphrasesStream = null;
269         String truststorePassword = null;
270         try {
271             passphrasesFile = new File(certPath + PASSPHRASSES_FILENAME);
272             passphrasesStream = new FileInputStream(passphrasesFile);
273
274
275             Properties passphrasesProps = new Properties();
276             passphrasesProps.load(passphrasesStream);
277             truststorePassword = passphrasesProps.getProperty(TRUSTSTORE_PASSWORD_PROP_NAME);
278             if (truststorePassword != null) {
279                 truststorePassword = truststorePassword.trim();
280             }
281
282         } catch (IOException e) {
283             LOGGER.warn("Not using AAF Certman passphrases file, e=" + e.getMessage());
284         } catch (NullPointerException n) {
285             LOGGER.warn("Not using AAF Certman passphrases file, e=" + n.getMessage());
286         } finally {
287             if (passphrasesStream != null) {
288                 try {
289                     passphrasesStream.close();
290                 } catch (Exception e) {
291                 }
292             }
293         }
294
295         return truststorePassword;
296     }
297
298     /**
299      * Get the trustore password
300      *
301      * @return the password
302      */
303     public static String getTruststorePassword() {
304         return (TRUSTSTORE_PASSWORD);
305     }
306
307     /**
308      * Gets the int value for the key.
309      *
310      * @param key the key
311      * @return the int
312      * @throws AAIException the AAI exception
313      */
314     public static int getInt(String key) throws AAIException {
315         return Integer.parseInt(AAIApplicationConfig.get(key));
316     }
317
318     /**
319      * Gets the int.
320      *
321      * @param key the key
322      * @return the int
323      */
324     public static int getInt(String key, String value) {
325         return Integer.parseInt(AAIApplicationConfig.get(key, value));
326     }
327
328     /**
329      * Gets the server props.
330      *
331      * @return the server props
332      */
333     public static Properties getServerProps() {
334         return serverProps;
335     }
336
337     /**
338      * Check if a null or an Empty string is passed in.
339      *
340      * @param s the s
341      * @return boolean
342      */
343     public static boolean isEmpty(String s) {
344         return (s == null || s.length() == 0);
345     }
346
347     private static String replaceProperties(String originalValue) throws AAIException {
348         final Pattern p = Pattern.compile(PROPERTY_REGEX);
349         Matcher m = p.matcher(originalValue);
350         /*if (!m.matches()) {
351             return originalValue;
352         }*/
353         StringBuffer sb = new StringBuffer();
354         while(m.find()) {
355             String text = m.group(1);
356             String replacement = get(text);
357             m.appendReplacement(sb, replacement);
358         }
359         m.appendTail(sb);
360         return(sb.toString());
361     }
362 }