Removed JMX, other unused code from configuration
[sdc.git] / common / onap-common-configuration-management / onap-configuration-management-core / src / main / java / org / onap / config / impl / ConfigurationImpl.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.config.impl;
18
19 import static org.onap.config.ConfigurationUtils.isBlank;
20
21 import java.io.File;
22 import java.lang.reflect.Constructor;
23 import java.lang.reflect.Field;
24 import java.lang.reflect.Modifier;
25 import java.net.URL;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.function.Predicate;
35 import org.onap.config.ConfigurationUtils;
36 import org.onap.config.Constants;
37 import org.onap.config.NonConfigResource;
38 import org.onap.config.api.Config;
39 import org.onap.config.api.Hint;
40
41 public class ConfigurationImpl implements org.onap.config.api.Configuration {
42
43     private static final String KEY_CANNOT_BE_NULL = "Key can't be null.";
44
45     private static final Object LOCK = new Object();
46
47     private static boolean instantiated = false;
48
49     public ConfigurationImpl() throws Exception {
50
51         synchronized (LOCK) {
52             init();
53         }
54     }
55
56     private void init() throws Exception {
57
58         if (instantiated) {
59             return;
60         }
61
62         Map<String, AggregateConfiguration> moduleConfigStore = new HashMap<>();
63         List<URL> classpathResources = ConfigurationUtils.getAllClassPathResources();
64         Predicate<URL> predicate = ConfigurationUtils::isConfig;
65         for (URL url : classpathResources) {
66             if (predicate.test(url)) {
67                 String moduleName = ConfigurationUtils.getConfigurationRepositoryKey(url);
68                 AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
69                 if (moduleConfig == null) {
70                     moduleConfig = new AggregateConfiguration();
71                     moduleConfigStore.put(moduleName, moduleConfig);
72                 }
73                 moduleConfig.addConfig(url);
74             } else {
75                 NonConfigResource.add(url);
76             }
77         }
78         String configLocation = System.getProperty("config.location");
79         if (!isBlank(configLocation)) {
80             File root = new File(configLocation);
81             Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
82             Predicate<File> filePredicate = ConfigurationUtils::isConfig;
83             for (File file : filesystemResources) {
84                 if (filePredicate.test(file)) {
85                     String moduleName = ConfigurationUtils.getConfigurationRepositoryKey(file);
86                     AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
87                     if (moduleConfig == null) {
88                         moduleConfig = new AggregateConfiguration();
89                         moduleConfigStore.put(moduleName, moduleConfig);
90                     }
91                     moduleConfig.addConfig(file);
92                 } else {
93                     NonConfigResource.add(file);
94                 }
95             }
96         }
97         String tenantConfigLocation = System.getProperty("tenant.config.location");
98         if (!isBlank(tenantConfigLocation)) {
99             File root = new File(tenantConfigLocation);
100             Collection<File> tenantsRoot = ConfigurationUtils.getAllFiles(root, false, true);
101             Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
102             Predicate<File> filePredicate = ConfigurationUtils::isConfig;
103             for (File file : filesystemResources) {
104                 if (filePredicate.test(file)) {
105                     String moduleName = ConfigurationUtils.getNamespace(file);
106                     for (File tenantFileRoot : tenantsRoot) {
107                         if (file.getAbsolutePath().startsWith(tenantFileRoot.getAbsolutePath())) {
108                             moduleName = ConfigurationUtils.getConfigurationRepositoryKey(
109                                     (tenantFileRoot.getName().toUpperCase() + Constants.TENANT_NAMESPACE_SEPARATOR
110                                              + moduleName).split(Constants.TENANT_NAMESPACE_SEPARATOR));
111                         }
112                     }
113                     AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
114                     if (moduleConfig == null) {
115                         moduleConfig = new AggregateConfiguration();
116                         moduleConfigStore.put(moduleName, moduleConfig);
117                     }
118                     moduleConfig.addConfig(file);
119                 }
120             }
121         }
122
123         populateFinalConfigurationIncrementally(moduleConfigStore);
124         String nodeConfigLocation = System.getProperty("node.config.location");
125         if (!isBlank(nodeConfigLocation)) {
126             File root = new File(nodeConfigLocation);
127             Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
128             Predicate<File> filePredicate = ConfigurationUtils::isConfig;
129             for (File file : filesystemResources) {
130                 if (filePredicate.test(file)) {
131                     ConfigurationRepository.lookup().populateOverrideConfiguration(
132                             ConfigurationUtils.getConfigurationRepositoryKey(
133                                     ConfigurationUtils.getNamespace(file).split(Constants.TENANT_NAMESPACE_SEPARATOR)),
134                             file);
135                 }
136             }
137         }
138
139         instantiated = true;
140     }
141
142     private void populateFinalConfigurationIncrementally(Map<String, AggregateConfiguration> configs) {
143
144         if (configs.get(Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELIMITER + Constants.DB_NAMESPACE) != null) {
145             ConfigurationRepository.lookup().populateConfiguration(
146                     Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELIMITER + Constants.DB_NAMESPACE,
147                     configs.remove(Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELIMITER + Constants.DB_NAMESPACE)
148                             .getFinalConfiguration());
149         }
150
151         Set<String> modules = configs.keySet();
152         for (String module : modules) {
153             ConfigurationRepository.lookup().populateConfiguration(module, configs.get(module).getFinalConfiguration());
154         }
155     }
156
157     @Override
158     public <T> T get(String tenant, String namespace, String key, Class<T> clazz, Hint... hints) {
159
160         String[] tenantNamespaceArray;
161         if (tenant == null && namespace != null) {
162             tenantNamespaceArray = namespace.split(Constants.TENANT_NAMESPACE_SEPARATOR);
163             if (tenantNamespaceArray.length > 1) {
164                 tenant = tenantNamespaceArray[0];
165                 namespace = tenantNamespaceArray[1];
166             }
167         }
168
169         tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
170                          : Constants.DEFAULT_TENANT;
171         namespace = ConfigurationRepository.lookup().isValidNamespace(namespace) ? namespace.toUpperCase()
172                             : Constants.DEFAULT_NAMESPACE;
173         T returnValue;
174         returnValue = (T) getInternal(tenant, namespace, key, clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
175                 hints == null || hints.length == 0 ? new Hint[] {Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC} : hints);
176         if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
177                     && !Constants.DEFAULT_TENANT.equals(tenant)) {
178             returnValue = (T) getInternal(Constants.DEFAULT_TENANT, namespace, key,
179                     clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
180                     hints == null || hints.length == 0 ? new Hint[] {Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC} : hints);
181         }
182         if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
183                     && !Constants.DEFAULT_NAMESPACE.equals(namespace)) {
184             returnValue = (T) getInternal(tenant, Constants.DEFAULT_NAMESPACE, key,
185                     clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
186                     hints == null || hints.length == 0 ? new Hint[] {Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC} : hints);
187         }
188         if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
189                     && !Constants.DEFAULT_NAMESPACE.equals(namespace) && !Constants.DEFAULT_TENANT.equals(tenant)) {
190             returnValue = (T) getInternal(Constants.DEFAULT_TENANT, Constants.DEFAULT_NAMESPACE, key,
191                     clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
192                     hints == null || hints.length == 0 ? new Hint[] {Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC} : hints);
193         }
194         if (returnValue == null && clazz.isPrimitive()) {
195             return (T) ConfigurationUtils.getDefaultFor(clazz);
196         } else {
197             return returnValue;
198         }
199     }
200
201     @Override
202     public <T> Map<String, T> populateMap(String tenantId, String namespace, String key, Class<T> clazz) {
203
204         tenantId = calculateTenant(tenantId);
205         namespace = calculateNamespace(namespace);
206         Map<String, T> map = new HashMap<>();
207         Iterator<String> keys;
208         try {
209             keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys(key);
210             while (keys.hasNext()) {
211                 String k = keys.next();
212                 if (k.startsWith(key + ".")) {
213                     k = k.substring(key.length() + 1);
214                     String subkey = k.substring(0, k.indexOf("."));
215                     if (!map.containsKey(subkey)) {
216                         map.put(subkey, get(tenantId, namespace, key + "." + subkey, clazz));
217                     }
218                 }
219             }
220         } catch (Exception e) {
221             e.printStackTrace();
222         }
223         return map;
224     }
225
226     @Override
227     public Map generateMap(String tenantId, String namespace, String key) {
228
229         tenantId = calculateTenant(tenantId);
230         namespace = calculateNamespace(namespace);
231
232         Map map;
233         Map parentMap = new HashMap<>();
234         Iterator<String> keys;
235         try {
236             if (isBlank(key)) {
237                 keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys();
238             } else {
239                 keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys(key);
240             }
241             while (keys.hasNext()) {
242                 map = parentMap;
243                 String k = keys.next();
244
245                 if (!isBlank(key) && !k.startsWith(key + ".")) {
246                     continue;
247                 }
248                 String value = getAsString(tenantId, namespace, k);
249                 if (!isBlank(key) && k.startsWith(key + ".")) {
250                     k = k.substring(key.trim().length() + 1);
251                 }
252
253                 while (k.contains(".")) {
254                     if (k.contains(".")) {
255                         String subkey = k.substring(0, k.indexOf("."));
256                         k = k.substring(k.indexOf(".") + 1);
257                         if (!map.containsKey(subkey)) {
258                             map.put(subkey, map = new HashMap<>());
259                         } else {
260                             map = (Map) map.get(subkey);
261                         }
262                     }
263                 }
264                 map.put(k, value);
265             }
266         } catch (Exception e) {
267             e.printStackTrace();
268         }
269         return parentMap;
270     }
271
272     protected <T> T getInternal(String tenant, String namespace, String key, Class<T> clazz, Hint... hints) {
273         int processingHints = Hint.DEFAULT.value();
274         if (hints != null) {
275             for (Hint hint : hints) {
276                 processingHints = processingHints | hint.value();
277             }
278         }
279
280         tenant = calculateTenant(tenant);
281         namespace = calculateNamespace(namespace);
282
283         if (isBlank(key) && !clazz.isAnnotationPresent(Config.class)) {
284             throw new IllegalArgumentException(KEY_CANNOT_BE_NULL);
285         }
286
287         if (clazz == null) {
288             throw new IllegalArgumentException("clazz is null.");
289         }
290
291         if (clazz.isPrimitive()) {
292             clazz = getWrapperClass(clazz);
293         }
294         try {
295             if (ConfigurationUtils.isWrapperClass(clazz) || clazz.isPrimitive()) {
296                 Object obj = ConfigurationUtils.getProperty(
297                         ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key, processingHints);
298                 if (obj != null) {
299                     if (ConfigurationUtils.isCollection(obj.toString())) {
300                         obj = ConfigurationUtils.getCollectionString(obj.toString());
301                     }
302                     String value = obj.toString().split(",")[0];
303                     value = ConfigurationUtils.processVariablesIfPresent(tenant, namespace, value);
304                     return (T) getValue(value, clazz.isPrimitive() ? getWrapperClass(clazz) : clazz, processingHints);
305                 } else {
306                     return null;
307                 }
308             } else if (clazz.isArray() && (clazz.getComponentType().isPrimitive() || ConfigurationUtils.isWrapperClass(
309                     clazz.getComponentType()))) {
310                 Object obj = ConfigurationUtils.getProperty(
311                         ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key, processingHints);
312                 if (obj != null) {
313                     Class componentClass = clazz.getComponentType();
314                     if (clazz.getComponentType().isPrimitive()) {
315                         componentClass = getWrapperClass(clazz.getComponentType());
316                     }
317                     String collString = ConfigurationUtils.getCollectionString(obj.toString());
318                     ArrayList<String> tempCollection = new ArrayList<>();
319                     for (String itemValue : collString.split(",")) {
320                         tempCollection.add(ConfigurationUtils.processVariablesIfPresent(tenant, namespace, itemValue));
321                     }
322                     Collection<T> collection =
323                             convert(ConfigurationUtils.getCollectionString(Arrays.toString(tempCollection.toArray())),
324                                     componentClass, processingHints);
325                     if (clazz.getComponentType().isPrimitive()) {
326                         return (T) ConfigurationUtils.getPrimitiveArray(collection, clazz.getComponentType());
327                     } else {
328                         return (T) collection.toArray(getZeroLengthArrayFor(getWrapperClass(clazz.getComponentType())));
329                     }
330                 } else {
331                     return null;
332                 }
333             } else if (clazz.isAnnotationPresent(Config.class)) {
334                 return read(tenant, namespace, clazz, isBlank(key) ? "" : (key + "."), hints);
335             } else {
336                 throw new IllegalArgumentException(
337                         "Only primitive classes, wrapper classes, corresponding array classes and any "
338                                 + "class decorated with @org.openecomp.config.api.Config are allowed as argument.");
339             }
340         } catch (Exception exception) {
341             exception.printStackTrace();
342         }
343         return null;
344     }
345
346     private static String calculateNamespace(String namespace) {
347
348         if (isBlank(namespace)) {
349             return Constants.DEFAULT_NAMESPACE;
350         }
351
352         return namespace.toUpperCase();
353     }
354
355     private static String calculateTenant(String tenant) {
356
357         if (isBlank(tenant)) {
358             return Constants.DEFAULT_TENANT;
359         }
360
361         return tenant.toUpperCase();
362     }
363
364     private <T> T read(String tenant, String namespace, Class<T> clazz, String keyPrefix, Hint... hints)
365             throws Exception {
366         Config confAnnotation = clazz.getAnnotation(Config.class);
367         if (confAnnotation != null && confAnnotation.key().length() > 0 && !keyPrefix.endsWith(".")) {
368             keyPrefix += (confAnnotation.key() + ".");
369         }
370         Constructor<T> constructor = clazz.getDeclaredConstructor();
371         constructor.setAccessible(true);
372         T objToReturn = constructor.newInstance();
373         for (Field field : clazz.getDeclaredFields()) {
374             field.setAccessible(true);
375             Config fieldConfAnnotation = field.getAnnotation(Config.class);
376             if (fieldConfAnnotation != null) {
377                 if (field.getType().isPrimitive() || ConfigurationUtils.isWrapperClass(field.getType()) || (
378                         field.getType().isArray() && (field.getType().getComponentType().isPrimitive()
379                                                               || ConfigurationUtils.isWrapperClass(
380                                 field.getType().getComponentType())))
381                             || field.getType().getAnnotation(Config.class) != null) {
382                     field.set(objToReturn,
383                             get(tenant, namespace, keyPrefix + fieldConfAnnotation.key(), field.getType(), hints));
384                 } else if (Collection.class.isAssignableFrom(field.getType())) {
385                     Object obj = get(tenant, namespace, keyPrefix + fieldConfAnnotation.key(),
386                             ConfigurationUtils.getArrayClass(ConfigurationUtils.getCollectionGenericType(field)),
387                             hints);
388                     if (obj != null) {
389                         List list = Arrays.asList((Object[]) obj);
390                         Class clazzToInstantiate;
391                         if (field.getType().isInterface()) {
392                             clazzToInstantiate = ConfigurationUtils.getConcreteCollection(field.getType()).getClass();
393                         } else if (Modifier.isAbstract(field.getType().getModifiers())) {
394                             clazzToInstantiate =
395                                     ConfigurationUtils.getCompatibleCollectionForAbstractDef(field.getType())
396                                             .getClass();
397                         } else {
398                             clazzToInstantiate = field.getType();
399                         }
400                         Constructor construct = getConstructorWithArguments(clazzToInstantiate, Collection.class);
401                         if (construct != null) {
402                             construct.setAccessible(true);
403                             field.set(objToReturn, construct.newInstance(list));
404                         } else if ((construct = getConstructorWithArguments(clazzToInstantiate, Integer.class,
405                                 Boolean.class, Collection.class)) != null) {
406                             construct.setAccessible(true);
407                             field.set(objToReturn, construct.newInstance(list.size(), true, list));
408                         }
409                     }
410                 } else if (Map.class.isAssignableFrom(field.getType())) {
411                     field.set(objToReturn, generateMap(tenant, namespace, keyPrefix + fieldConfAnnotation.key()));
412                 }
413             }
414         }
415         return objToReturn;
416     }
417
418     private Constructor getConstructorWithArguments(Class clazz, Class... classes) {
419         try {
420             return clazz.getDeclaredConstructor(classes);
421         } catch (Exception exception) {
422             return null;
423         }
424     }
425
426     private Class getWrapperClass(Class clazz) {
427         if (byte.class == clazz) {
428             return Byte.class;
429         } else if (short.class == clazz) {
430             return Short.class;
431         } else if (int.class == clazz) {
432             return Integer.class;
433         } else if (long.class == clazz) {
434             return Long.class;
435         } else if (float.class == clazz) {
436             return Float.class;
437         } else if (double.class == clazz) {
438             return Double.class;
439         } else if (char.class == clazz) {
440             return Character.class;
441         } else if (boolean.class == clazz) {
442             return Boolean.class;
443         }
444         return clazz;
445     }
446
447     private <T> T getValue(Object obj, Class<T> clazz, int processingHint) {
448
449         if (obj == null || obj.toString().trim().length() == 0) {
450             return null;
451         } else {
452             obj = obj.toString().trim();
453         }
454
455         if (String.class.equals(clazz)) {
456             if (obj.toString().startsWith("@") && ConfigurationUtils.isExternalLookup(processingHint)) {
457                 String contents = ConfigurationUtils.getFileContents(
458                         NonConfigResource.locate(obj.toString().substring(1).trim()));
459                 if (contents == null) {
460                     contents = ConfigurationUtils.getFileContents(obj.toString().substring(1).trim());
461                 }
462                 if (contents != null) {
463                     obj = contents;
464                 }
465             }
466             return (T) obj.toString();
467         } else if (Number.class.isAssignableFrom(clazz)) {
468             Double doubleValue = Double.valueOf(obj.toString());
469             switch (clazz.getName()) {
470                 case "java.lang.Byte":
471                     Byte byteVal = doubleValue.byteValue();
472                     return (T) byteVal;
473                 case "java.lang.Short":
474                     Short shortVal = doubleValue.shortValue();
475                     return (T) shortVal;
476                 case "java.lang.Integer":
477                     Integer intVal = doubleValue.intValue();
478                     return (T) intVal;
479                 case "java.lang.Long":
480                     Long longVal = doubleValue.longValue();
481                     return (T) longVal;
482                 case "java.lang.Float":
483                     Float floatVal = doubleValue.floatValue();
484                     return (T) floatVal;
485                 case "java.lang.Double":
486                     return (T) doubleValue;
487                 default:
488             }
489         } else if (Boolean.class.equals(clazz)) {
490             return (T) Boolean.valueOf(obj.toString());
491         } else if (Character.class.equals(clazz)) {
492             return (T) Character.valueOf(obj.toString().charAt(0));
493         }
494         return null;
495     }
496
497     private <T> T[] getZeroLengthArrayFor(Class<T> clazz) {
498         Object obj = null;
499         if (clazz == int.class) {
500             obj = new int[] {};
501         } else if (clazz == byte.class) {
502             obj = new byte[] {};
503         } else if (clazz == short.class) {
504             obj = new short[] {};
505         } else if (clazz == long.class) {
506             obj = new long[] {};
507         } else if (clazz == float.class) {
508             obj = new float[] {};
509         } else if (clazz == double.class) {
510             obj = new double[] {};
511         } else if (clazz == boolean.class) {
512             obj = new boolean[] {};
513         } else if (clazz == char.class) {
514             obj = new char[] {};
515         } else if (clazz == Byte.class) {
516             obj = new Byte[] {};
517         } else if (clazz == Short.class) {
518             obj = new Short[] {};
519         } else if (clazz == Integer.class) {
520             obj = new Integer[] {};
521         } else if (clazz == Long.class) {
522             obj = new Long[] {};
523         } else if (clazz == Float.class) {
524             obj = new Float[] {};
525         } else if (clazz == Double.class) {
526             obj = new Double[] {};
527         } else if (clazz == Boolean.class) {
528             obj = new Boolean[] {};
529         } else if (clazz == Character.class) {
530             obj = new Character[] {};
531         } else if (clazz == String.class) {
532             obj = new String[] {};
533         }
534         return (T[]) obj;
535     }
536
537     private <T> Collection<T> convert(String commaSeparatedValues, Class<T> clazz, int processingHints) {
538         ArrayList<T> collection = new ArrayList<>();
539         for (String value : commaSeparatedValues.split(",")) {
540             try {
541                 T type1 = getValue(value, clazz, processingHints);
542                 if (type1 != null) {
543                     collection.add(type1);
544                 }
545             } catch (RuntimeException re) {
546                 // do nothing
547             }
548         }
549         return collection;
550     }
551 }