2 * Copyright © 2016-2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.config.impl;
19 import static org.onap.config.ConfigurationUtils.isBlank;
22 import java.lang.reflect.Constructor;
23 import java.lang.reflect.Field;
24 import java.lang.reflect.Modifier;
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;
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;
41 public class ConfigurationImpl implements org.onap.config.api.Configuration {
43 private static final String KEY_CANNOT_BE_NULL = "Key can't be null.";
45 private static final Object LOCK = new Object();
47 private static boolean instantiated = false;
49 public ConfigurationImpl() throws Exception {
56 private void init() throws Exception {
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);
73 moduleConfig.addConfig(url);
75 NonConfigResource.add(url);
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);
91 moduleConfig.addConfig(file);
93 NonConfigResource.add(file);
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));
113 AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
114 if (moduleConfig == null) {
115 moduleConfig = new AggregateConfiguration();
116 moduleConfigStore.put(moduleName, moduleConfig);
118 moduleConfig.addConfig(file);
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)),
142 private void populateFinalConfigurationIncrementally(Map<String, AggregateConfiguration> configs) {
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());
151 Set<String> modules = configs.keySet();
152 for (String module : modules) {
153 ConfigurationRepository.lookup().populateConfiguration(module, configs.get(module).getFinalConfiguration());
158 public <T> T get(String tenant, String namespace, String key, Class<T> clazz, Hint... hints) {
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];
169 tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
170 : Constants.DEFAULT_TENANT;
171 namespace = ConfigurationRepository.lookup().isValidNamespace(namespace) ? namespace.toUpperCase()
172 : Constants.DEFAULT_NAMESPACE;
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);
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);
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);
194 if (returnValue == null && clazz.isPrimitive()) {
195 return (T) ConfigurationUtils.getDefaultFor(clazz);
202 public <T> Map<String, T> populateMap(String tenantId, String namespace, String key, Class<T> clazz) {
204 tenantId = calculateTenant(tenantId);
205 namespace = calculateNamespace(namespace);
206 Map<String, T> map = new HashMap<>();
207 Iterator<String> keys;
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));
220 } catch (Exception e) {
227 public Map generateMap(String tenantId, String namespace, String key) {
229 tenantId = calculateTenant(tenantId);
230 namespace = calculateNamespace(namespace);
233 Map parentMap = new HashMap<>();
234 Iterator<String> keys;
237 keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys();
239 keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys(key);
241 while (keys.hasNext()) {
243 String k = keys.next();
245 if (!isBlank(key) && !k.startsWith(key + ".")) {
248 String value = getAsString(tenantId, namespace, k);
249 if (!isBlank(key) && k.startsWith(key + ".")) {
250 k = k.substring(key.trim().length() + 1);
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<>());
260 map = (Map) map.get(subkey);
266 } catch (Exception e) {
272 protected <T> T getInternal(String tenant, String namespace, String key, Class<T> clazz, Hint... hints) {
273 int processingHints = Hint.DEFAULT.value();
275 for (Hint hint : hints) {
276 processingHints = processingHints | hint.value();
280 tenant = calculateTenant(tenant);
281 namespace = calculateNamespace(namespace);
283 if (isBlank(key) && !clazz.isAnnotationPresent(Config.class)) {
284 throw new IllegalArgumentException(KEY_CANNOT_BE_NULL);
288 throw new IllegalArgumentException("clazz is null.");
291 if (clazz.isPrimitive()) {
292 clazz = getWrapperClass(clazz);
295 if (ConfigurationUtils.isWrapperClass(clazz) || clazz.isPrimitive()) {
296 Object obj = ConfigurationUtils.getProperty(
297 ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key, processingHints);
299 if (ConfigurationUtils.isCollection(obj.toString())) {
300 obj = ConfigurationUtils.getCollectionString(obj.toString());
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);
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);
313 Class componentClass = clazz.getComponentType();
314 if (clazz.getComponentType().isPrimitive()) {
315 componentClass = getWrapperClass(clazz.getComponentType());
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));
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());
328 return (T) collection.toArray(getZeroLengthArrayFor(getWrapperClass(clazz.getComponentType())));
333 } else if (clazz.isAnnotationPresent(Config.class)) {
334 return read(tenant, namespace, clazz, isBlank(key) ? "" : (key + "."), hints);
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.");
340 } catch (Exception exception) {
341 exception.printStackTrace();
346 private static String calculateNamespace(String namespace) {
348 if (isBlank(namespace)) {
349 return Constants.DEFAULT_NAMESPACE;
352 return namespace.toUpperCase();
355 private static String calculateTenant(String tenant) {
357 if (isBlank(tenant)) {
358 return Constants.DEFAULT_TENANT;
361 return tenant.toUpperCase();
364 private <T> T read(String tenant, String namespace, Class<T> clazz, String keyPrefix, Hint... hints)
366 Config confAnnotation = clazz.getAnnotation(Config.class);
367 if (confAnnotation != null && confAnnotation.key().length() > 0 && !keyPrefix.endsWith(".")) {
368 keyPrefix += (confAnnotation.key() + ".");
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)),
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())) {
395 ConfigurationUtils.getCompatibleCollectionForAbstractDef(field.getType())
398 clazzToInstantiate = field.getType();
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));
410 } else if (Map.class.isAssignableFrom(field.getType())) {
411 field.set(objToReturn, generateMap(tenant, namespace, keyPrefix + fieldConfAnnotation.key()));
418 private Constructor getConstructorWithArguments(Class clazz, Class... classes) {
420 return clazz.getDeclaredConstructor(classes);
421 } catch (Exception exception) {
426 private Class getWrapperClass(Class clazz) {
427 if (byte.class == clazz) {
429 } else if (short.class == clazz) {
431 } else if (int.class == clazz) {
432 return Integer.class;
433 } else if (long.class == clazz) {
435 } else if (float.class == clazz) {
437 } else if (double.class == clazz) {
439 } else if (char.class == clazz) {
440 return Character.class;
441 } else if (boolean.class == clazz) {
442 return Boolean.class;
447 private <T> T getValue(Object obj, Class<T> clazz, int processingHint) {
449 if (obj == null || obj.toString().trim().length() == 0) {
452 obj = obj.toString().trim();
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());
462 if (contents != null) {
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();
473 case "java.lang.Short":
474 Short shortVal = doubleValue.shortValue();
476 case "java.lang.Integer":
477 Integer intVal = doubleValue.intValue();
479 case "java.lang.Long":
480 Long longVal = doubleValue.longValue();
482 case "java.lang.Float":
483 Float floatVal = doubleValue.floatValue();
485 case "java.lang.Double":
486 return (T) doubleValue;
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));
497 private <T> T[] getZeroLengthArrayFor(Class<T> clazz) {
499 if (clazz == int.class) {
501 } else if (clazz == byte.class) {
503 } else if (clazz == short.class) {
504 obj = new short[] {};
505 } else if (clazz == long.class) {
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) {
515 } else if (clazz == Byte.class) {
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) {
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[] {};
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(",")) {
541 T type1 = getValue(value, clazz, processingHints);
543 collection.add(type1);
545 } catch (RuntimeException re) {