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