Code formatting of configuration framework 57/71257/2
authorvempo <vitaliy.emporopulo@amdocs.com>
Thu, 25 Oct 2018 16:27:22 +0000 (19:27 +0300)
committerAvi Gaffa <avi.gaffa@amdocs.com>
Sun, 28 Oct 2018 06:58:23 +0000 (06:58 +0000)
Fixed code formatting, removed meaningless Javadoc comments,
added copyright headers, minor (and safe) static analysis fixes.

Change-Id: I3eda1f242905da5b80e024cf30a69ff59381fc43
Issue-ID: SDC-1867
Signed-off-by: vempo <vitaliy.emporopulo@amdocs.com>
52 files changed:
common/onap-common-configuration-management/onap-configuration-management-api/pom.xml
common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/Config.java
common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/Configuration.java
common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/ConfigurationChangeListener.java
common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/ConfigurationManager.java
common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/DynamicConfiguration.java
common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/Hint.java
common/onap-common-configuration-management/onap-configuration-management-core/pom.xml
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/ConfigurationUtils.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/Constants.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/NonConfigResource.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/AgglomerateConfiguration.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/AggregateConfiguration.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/CliConfigurationImpl.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/ConfigurationChangeNotifier.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/ConfigurationFilter.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/ConfigurationImpl.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/ConfigurationRepository.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/ContextListener.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/YamlConfiguration.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/type/ConfigurationMode.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/type/ConfigurationQuery.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/type/ConfigurationType.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/type/ConfigurationUpdate.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/resources/config-system.properties
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/ConfigurationUtilsTest.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/TestCMSuite.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/CliFallbackAndLookupTest.java [moved from common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/CLIFallbackAndLookupTest.java with 65% similarity]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/ConfigSourceLocationTest.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/FallbackConfigTest.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/FallbackToGlobalNSTest.java [deleted file]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/FallbackToGlobalNamespaceTest.java [new file with mode: 0644]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/GlobalAndNSConfigTest.java [deleted file]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/GlobalAndNamespaceConfigTest.java [new file with mode: 0644]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JAVAPropertiesConfigTest.java [deleted file]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JSONConfigTest.java [deleted file]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JavaPropertiesConfigTest.java [new file with mode: 0644]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JsonConfigTest.java [new file with mode: 0644]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/LoadOrderMergeAndOverrideTest.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/ModeAsConfigPropTest.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/MultiTenancyConfigTest.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/ValidateDefaultModeTest.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/XMLConfigTest.java [deleted file]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/XmlConfigTest.java [new file with mode: 0644]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/YAMLConfigTest.java [deleted file]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/YamlConfigTest.java [new file with mode: 0644]
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/util/ConfigTestConstant.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/util/TestUtil.java
common/onap-common-configuration-management/onap-configuration-management-core/src/test/resources/GlobalAndNSConfig/config.properties
common/onap-common-configuration-management/onap-configuration-management-core/src/test/resources/SourceLocation/appjarconfig.properties
common/onap-common-configuration-management/onap-configuration-management-core/src/test/resources/config-system.properties
common/onap-common-configuration-management/pom.xml

index 376ff9a..08be65a 100644 (file)
@@ -1,5 +1,5 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xmlns="http://maven.apache.org/POM/4.0.0"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 
     <modelVersion>4.0.0</modelVersion>
index 406f45a..73ddc5d 100644 (file)
@@ -1,3 +1,19 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.api;
 
 import java.lang.annotation.ElementType;
@@ -5,17 +21,9 @@ import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
-/**
- * The interface Config.
- */
 @Target({ElementType.TYPE, ElementType.FIELD})
 @Retention(RetentionPolicy.RUNTIME)
 public @interface Config {
 
-    /**
-     * Key string.
-     *
-     * @return the string
-     */
     String key();
 }
index 58eedd7..3232d49 100644 (file)
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.api;
 
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 
-/**
- * The interface Configuration.
- */
 public interface Configuration {
-  /**
-   * The constant tenant.
-   */
-  public static ThreadLocal<String> tenant = new ThreadLocal<>();
-
-  /**
-   * Sets tenant id.
-   *
-   * @param id the id
-   */
-  public static void setTenantId(String id) {
-    if (id != null && id.trim().length() > 0) {
-      tenant.set(id);
-    }
-  }
-
-  /**
-   * Gets as string.
-   *
-   * @param key the key
-   * @return the as string
-   */
-  public default String getAsString(String key) {
-    return getAsString(null, key);
-  }
-
-  /**
-   * Gets as string.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as string
-   */
-  public default String getAsString(String namespace, String key) {
-    return getAsString(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as string.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as string
-   */
-  public default String getAsString(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, String.class);
-  }
-
-  /**
-   * Gets as byte value.
-   *
-   * @param key the key
-   * @return the as byte value
-   */
-  public default Byte getAsByteValue(String key) {
-    return getAsByteValue(null, key);
-  }
-
-  /**
-   * Gets as byte value.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as byte value
-   */
-  public default Byte getAsByteValue(String namespace, String key) {
-    return getAsByteValue(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as byte value.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as byte value
-   */
-  public default Byte getAsByteValue(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, Byte.class);
-  }
-
-  /**
-   * Gets as short value.
-   *
-   * @param key the key
-   * @return the as short value
-   */
-  public default Short getAsShortValue(String key) {
-    return getAsShortValue(null, key);
-  }
-
-  /**
-   * Gets as short value.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as short value
-   */
-  public default Short getAsShortValue(String namespace, String key) {
-    return getAsShortValue(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as short value.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as short value
-   */
-  public default Short getAsShortValue(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, Short.class);
-  }
-
-  /**
-   * Gets as integer value.
-   *
-   * @param key the key
-   * @return the as integer value
-   */
-  public default Integer getAsIntegerValue(String key) {
-    return getAsIntegerValue(null, key);
-  }
-
-  /**
-   * Gets as integer value.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as integer value
-   */
-  public default Integer getAsIntegerValue(String namespace, String key) {
-    return getAsIntegerValue(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as integer value.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as integer value
-   */
-  public default Integer getAsIntegerValue(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, Integer.class);
-  }
-
-  /**
-   * Gets as long value.
-   *
-   * @param key the key
-   * @return the as long value
-   */
-  public default Long getAsLongValue(String key) {
-    return getAsLongValue(null, key);
-  }
-
-  /**
-   * Gets as long value.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as long value
-   */
-  public default Long getAsLongValue(String namespace, String key) {
-    return getAsLongValue(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as long value.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as long value
-   */
-  public default Long getAsLongValue(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, Long.class);
-  }
-
-  /**
-   * Gets as float value.
-   *
-   * @param key the key
-   * @return the as float value
-   */
-  public default Float getAsFloatValue(String key) {
-    return getAsFloatValue(null, key);
-  }
-
-  /**
-   * Gets as float value.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as float value
-   */
-  public default Float getAsFloatValue(String namespace, String key) {
-    return getAsFloatValue(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as float value.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as float value
-   */
-  public default Float getAsFloatValue(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, Float.class);
-  }
-
-  /**
-   * Gets as double value.
-   *
-   * @param key the key
-   * @return the as double value
-   */
-  public default Double getAsDoubleValue(String key) {
-    return getAsDoubleValue(null, key);
-  }
-
-  /**
-   * Gets as double value.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as double value
-   */
-  public default Double getAsDoubleValue(String namespace, String key) {
-    return getAsDoubleValue(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as double value.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as double value
-   */
-  public default Double getAsDoubleValue(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, Double.class);
-  }
-
-  /**
-   * Gets as boolean value.
-   *
-   * @param key the key
-   * @return the as boolean value
-   */
-  public default Boolean getAsBooleanValue(String key) {
-    return getAsBooleanValue(null, key);
-  }
-
-  /**
-   * Gets as boolean value.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as boolean value
-   */
-  public default Boolean getAsBooleanValue(String namespace, String key) {
-    return getAsBooleanValue(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as boolean value.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as boolean value
-   */
-  public default Boolean getAsBooleanValue(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, Boolean.class);
-  }
-
-  /**
-   * Gets as char value.
-   *
-   * @param key the key
-   * @return the as char value
-   */
-  public default Character getAsCharValue(String key) {
-    return getAsCharValue(null, key);
-  }
-
-  /**
-   * Gets as char value.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as char value
-   */
-  public default Character getAsCharValue(String namespace, String key) {
-    return getAsCharValue(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as char value.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as char value
-   */
-  public default Character getAsCharValue(String tenantId, String namespace, String key) {
-    return get(tenantId, namespace, key, Character.class);
-  }
-
-  /**
-   * Populate configuration t.
-   *
-   * @param <T>   the type parameter
-   * @param clazz the clazz
-   * @return the t
-   */
-  public default <T> T populateConfiguration(Class<T> clazz) {
-    return populateConfiguration(null, clazz);
-  }
-
-  /**
-   * Populate configuration t.
-   *
-   * @param <T>       the type parameter
-   * @param namespace the namespace
-   * @param clazz     the clazz
-   * @return the t
-   */
-  public default <T> T populateConfiguration(String namespace, Class<T> clazz) {
-    return populateConfiguration(tenant.get(), namespace, clazz);
-  }
-
-  /**
-   * Populate configuration t.
-   *
-   * @param <T>       the type parameter
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param clazz     the clazz
-   * @return the t
-   */
-  public default <T> T populateConfiguration(String tenantId, String namespace, Class<T> clazz) {
-    return get(tenantId, namespace, null, clazz, Hint.EXTERNAL_LOOKUP);
-  }
-
-  /**
-   * Gets dynamic configuration.
-   *
-   * @param <T>          the type parameter
-   * @param key          the key
-   * @param clazz        the clazz
-   * @param defaultValue the default value
-   * @return the dynamic configuration
-   */
-  public default <T> DynamicConfiguration<T> getDynamicConfiguration(String key, Class<T> clazz,
-                                                                     T defaultValue) {
-    return getDynamicConfiguration(null, key, clazz, defaultValue);
-  }
-
-  /**
-   * Gets dynamic configuration.
-   *
-   * @param <T>          the type parameter
-   * @param namespace    the namespace
-   * @param key          the key
-   * @param clazz        the clazz
-   * @param defaultValue the default value
-   * @return the dynamic configuration
-   */
-  public default <T> DynamicConfiguration<T> getDynamicConfiguration(String namespace, String key,
-                                                                     Class<T> clazz,
-                                                                     T defaultValue) {
-    return getDynamicConfiguration(tenant.get(), namespace, key, clazz, defaultValue);
-  }
-
-  /**
-   * Gets dynamic configuration.
-   *
-   * @param <T>          the type parameter
-   * @param tenant       the tenant
-   * @param namespace    the namespace
-   * @param key          the key
-   * @param clazz        the clazz
-   * @param defaultValue the default value
-   * @return the dynamic configuration
-   */
-  public default <T> DynamicConfiguration<T> getDynamicConfiguration(String tenant,
-                                                                     String namespace, String key,
-                                                                     Class<T> clazz,
-                                                                     T defaultValue) {
-    return DynamicConfiguration
-        .getDynamicConfiguration(tenant, namespace, key, clazz, defaultValue, this);
-  }
-
-  /**
-   * Gets dynamic configuration values.
-   *
-   * @param <T>          the type parameter
-   * @param key          the key
-   * @param clazz        the clazz
-   * @param defaultValue the default value
-   * @return the dynamic configuration values
-   */
-  public default <T> DynamicConfiguration<List<T>> getDynamicConfigurationValues(String key,
-                                                                                 Class<T> clazz,
-                                                                                 T defaultValue) {
-    return getDynamicConfigurationValues(null, key, clazz, defaultValue);
-  }
-
-  /**
-   * Gets dynamic configuration values.
-   *
-   * @param <T>          the type parameter
-   * @param namespace    the namespace
-   * @param key          the key
-   * @param clazz        the clazz
-   * @param defaultValue the default value
-   * @return the dynamic configuration values
-   */
-  public default <T> DynamicConfiguration<List<T>> getDynamicConfigurationValues(String namespace,
-                                                                                 String key,
-                                                                                 Class<T> clazz,
-                                                                                 T defaultValue) {
-    return getDynamicConfigurationValues(tenant.get(), namespace, key, clazz, defaultValue);
-  }
-
-  /**
-   * Gets dynamic configuration values.
-   *
-   * @param <T>          the type parameter
-   * @param tenant       the tenant
-   * @param namespace    the namespace
-   * @param key          the key
-   * @param clazz        the clazz
-   * @param defaultValue the default value
-   * @return the dynamic configuration values
-   */
-  public default <T> DynamicConfiguration<List<T>> getDynamicConfigurationValues(String tenant,
-                                                                                 String namespace,
-                                                                                 String key,
-                                                                                 Class<T> clazz,
-                                                                                 T defaultValue) {
-    return DynamicConfiguration
-        .getDynConfiguration(tenant, namespace, key, clazz, defaultValue, this);
-  }
-
-  /**
-   * Gets as string values.
-   *
-   * @param key the key
-   * @return the as string values
-   */
-  public default List<String> getAsStringValues(String key) {
-    return getAsStringValues(null, key);
-  }
-
-  /**
-   * Gets as string values.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as string values
-   */
-  public default List<String> getAsStringValues(String namespace, String key) {
-    return getAsStringValues(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as string values.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as string values
-   */
-  public default List<String> getAsStringValues(String tenantId, String namespace, String key) {
-    String[] tempArray = get(tenantId, namespace, key, String[].class);
-    return tempArray == null ? Arrays.asList() : Arrays.asList(tempArray);
-  }
-
-  /**
-   * Gets as byte values.
-   *
-   * @param key the key
-   * @return the as byte values
-   */
-  public default List<Byte> getAsByteValues(String key) {
-    return getAsByteValues(null, key);
-  }
-
-  /**
-   * Gets as byte values.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as byte values
-   */
-  public default List<Byte> getAsByteValues(String namespace, String key) {
-    return getAsByteValues(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as byte values.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as byte values
-   */
-  public default List<Byte> getAsByteValues(String tenantId, String namespace, String key) {
-    Byte[] tempArray = get(tenantId, namespace, key, Byte[].class);
-    return tempArray == null ? Arrays.asList() : Arrays.asList(tempArray);
-  }
-
-  /**
-   * Gets as short values.
-   *
-   * @param key the key
-   * @return the as short values
-   */
-  public default List<Short> getAsShortValues(String key) {
-    return getAsShortValues(null, key);
-  }
-
-  /**
-   * Gets as short values.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as short values
-   */
-  public default List<Short> getAsShortValues(String namespace, String key) {
-    return getAsShortValues(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as short values.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as short values
-   */
-  public default List<Short> getAsShortValues(String tenantId, String namespace, String key) {
-    Short[] tempArray = get(tenantId, namespace, key, Short[].class);
-    return tempArray == null ? Arrays.asList() : Arrays.asList(tempArray);
-  }
-
-  /**
-   * Gets as integer values.
-   *
-   * @param key the key
-   * @return the as integer values
-   */
-  public default List<Integer> getAsIntegerValues(String key) {
-    return getAsIntegerValues(null, key);
-  }
-
-  /**
-   * Gets as integer values.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as integer values
-   */
-  public default List<Integer> getAsIntegerValues(String namespace, String key) {
-    return getAsIntegerValues(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as integer values.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as integer values
-   */
-  public default List<Integer> getAsIntegerValues(String tenantId, String namespace, String key) {
-    Integer[] tempArray = get(tenantId, namespace, key, Integer[].class);
-    return tempArray == null ? Arrays.asList() : Arrays.asList(tempArray);
-  }
-
-  /**
-   * Gets as double values.
-   *
-   * @param key the key
-   * @return the as double values
-   */
-  public default List<Double> getAsDoubleValues(String key) {
-    return getAsDoubleValues(null, key);
-  }
-
-  /**
-   * Gets as double values.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as double values
-   */
-  public default List<Double> getAsDoubleValues(String namespace, String key) {
-    return getAsDoubleValues(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as double values.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as double values
-   */
-  public default List<Double> getAsDoubleValues(String tenantId, String namespace, String key) {
-    Double[] tempArray = get(tenantId, namespace, key, Double[].class);
-    return tempArray == null ? Arrays.asList() : Arrays.asList(tempArray);
-  }
-
-  /**
-   * Gets as float values.
-   *
-   * @param key the key
-   * @return the as float values
-   */
-  public default List<Float> getAsFloatValues(String key) {
-    return getAsFloatValues(null, key);
-  }
-
-  /**
-   * Gets as float values.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as float values
-   */
-  public default List<Float> getAsFloatValues(String namespace, String key) {
-    return getAsFloatValues(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as float values.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as float values
-   */
-  public default List<Float> getAsFloatValues(String tenantId, String namespace, String key) {
-    Float[] tempArray = get(tenantId, namespace, key, Float[].class);
-    return tempArray == null ? Arrays.asList() : Arrays.asList(tempArray);
-  }
-
-  /**
-   * Gets as boolean values.
-   *
-   * @param key the key
-   * @return the as boolean values
-   */
-  public default List<Boolean> getAsBooleanValues(String key) {
-    return getAsBooleanValues(null, key);
-  }
-
-  /**
-   * Gets as boolean values.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as boolean values
-   */
-  public default List<Boolean> getAsBooleanValues(String namespace, String key) {
-    return getAsBooleanValues(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as boolean values.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as boolean values
-   */
-  public default List<Boolean> getAsBooleanValues(String tenantId, String namespace, String key) {
-    Boolean[] tempArray = get(tenantId, namespace, key, Boolean[].class);
-    return tempArray == null ? Arrays.asList() : Arrays.asList(tempArray);
-  }
-
-  /**
-   * Gets as character values.
-   *
-   * @param key the key
-   * @return the as character values
-   */
-  public default List<Character> getAsCharacterValues(String key) {
-    return getAsCharacterValues(null, key);
-  }
-
-  /**
-   * Gets as character values.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as character values
-   */
-  public default List<Character> getAsCharacterValues(String namespace, String key) {
-    return getAsCharacterValues(tenant.get(), namespace, key);
-  }
-
-  /**
-   * Gets as character values.
-   *
-   * @param tenantId  the tenant id
-   * @param namespace the namespace
-   * @param key       the key
-   * @return the as character values
-   */
-  public default List<Character> getAsCharacterValues(String tenantId, String namespace,
-                                                      String key) {
-    Character[] tempArray = get(tenantId, namespace, key, Character[].class);
-    return tempArray == null ? Arrays.asList() : Arrays.asList(tempArray);
-  }
-
-  /**
-   * Get t.
-   *
-   * @param <T>       the type parameter
-   * @param tenant    the tenant
-   * @param namespace the namespace
-   * @param key       the key
-   * @param clazz     the clazz
-   * @param hints     the hints
-   * @return the t
-   */
-  public <T> T get(String tenant, String namespace, String key, Class<T> clazz, Hint... hints);
-
-  /**
-   * Add configuration change listener.
-   *
-   * @param key    the key
-   * @param myself the myself
-   */
-  public default void addConfigurationChangeListener(String key,
-                                                     ConfigurationChangeListener myself) {
-    addConfigurationChangeListener(null, key, myself);
-  }
-
-  /**
-   * Add configuration change listener.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @param myself    the myself
-   */
-  public default void addConfigurationChangeListener(String namespace, String key,
-                                                     ConfigurationChangeListener myself) {
-    addConfigurationChangeListener(tenant.get(), namespace, key, myself);
-  }
-
-  /**
-   * Add configuration change listener.
-   *
-   * @param tenant    the tenant
-   * @param namespace the namespace
-   * @param key       the key
-   * @param myself    the myself
-   */
-  public void addConfigurationChangeListener(String tenant, String namespace, String key,
-                                             ConfigurationChangeListener myself);
-
-  /**
-   * Remove configuration change listener.
-   *
-   * @param key    the key
-   * @param myself the myself
-   */
-  public default void removeConfigurationChangeListener(String key,
-                                                        ConfigurationChangeListener myself) {
-    removeConfigurationChangeListener(null, key, myself);
-  }
-
-  /**
-   * Remove configuration change listener.
-   *
-   * @param namespace the namespace
-   * @param key       the key
-   * @param myself    the myself
-   */
-  public default void removeConfigurationChangeListener(String namespace, String key,
-                                                        ConfigurationChangeListener myself) {
-    removeConfigurationChangeListener(tenant.get(), namespace, key, myself);
-  }
-
-  /**
-   * Remove configuration change listener.
-   *
-   * @param tenant    the tenant
-   * @param namespace the namespace
-   * @param key       the key
-   * @param myself    the myself
-   */
-  public void removeConfigurationChangeListener(String tenant, String namespace, String key,
-                                                ConfigurationChangeListener myself);
-
-  public default <T> Map<String, T> populateMap(String key, Class<T> clazz){
-    return populateMap(null, key, clazz);
-  }
-  public default <T> Map<String, T> populateMap(String namespace, String key, Class<T> clazz){
-    return populateMap(tenant.get(), namespace, key, clazz);
-  }
-  public <T> Map<String, T> populateMap(String tenantId, String namespace, String key, Class<T> clazz);
-
-  public default Map generateMap(String key){
-    return generateMap(null, key);
-  }
-  public default Map generateMap(String namespace, String key){
-    return generateMap(tenant.get(), namespace, key);
-  }
-  public Map generateMap(String tenantId, String namespace, String key);
 
+    ThreadLocal<String> TENANT = new ThreadLocal<>();
+
+    /**
+     * Sets tenant for current thread.
+     *
+     * @param id tenant id; may be <code>null</code> in which case a default will be used.
+     */
+    static void setTenantId(String id) {
+
+        if (id != null && id.trim().length() > 0) {
+            TENANT.set(id);
+        } else {
+            TENANT.remove();
+        }
+    }
+
+    default String getAsString(String key) {
+        return getAsString(null, key);
+    }
+
+    default String getAsString(String namespace, String key) {
+        return getAsString(TENANT.get(), namespace, key);
+    }
+
+    default String getAsString(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, String.class);
+    }
+
+    <T> T get(String tenant, String namespace, String key, Class<T> clazz, Hint... hints);
+
+    default Byte getAsByteValue(String key) {
+        return getAsByteValue(null, key);
+    }
+
+    default Byte getAsByteValue(String namespace, String key) {
+        return getAsByteValue(TENANT.get(), namespace, key);
+    }
+
+    default Byte getAsByteValue(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, Byte.class);
+    }
+
+    default Short getAsShortValue(String key) {
+        return getAsShortValue(null, key);
+    }
+
+    default Short getAsShortValue(String namespace, String key) {
+        return getAsShortValue(TENANT.get(), namespace, key);
+    }
+
+    default Short getAsShortValue(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, Short.class);
+    }
+
+    default Integer getAsIntegerValue(String key) {
+        return getAsIntegerValue(null, key);
+    }
+
+    default Integer getAsIntegerValue(String namespace, String key) {
+        return getAsIntegerValue(TENANT.get(), namespace, key);
+    }
+
+    default Integer getAsIntegerValue(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, Integer.class);
+    }
+
+    default Long getAsLongValue(String key) {
+        return getAsLongValue(null, key);
+    }
+
+    default Long getAsLongValue(String namespace, String key) {
+        return getAsLongValue(TENANT.get(), namespace, key);
+    }
+
+    default Long getAsLongValue(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, Long.class);
+    }
+
+    default Float getAsFloatValue(String key) {
+        return getAsFloatValue(null, key);
+    }
+
+    default Float getAsFloatValue(String namespace, String key) {
+        return getAsFloatValue(TENANT.get(), namespace, key);
+    }
+
+    default Float getAsFloatValue(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, Float.class);
+    }
+
+    default Double getAsDoubleValue(String key) {
+        return getAsDoubleValue(null, key);
+    }
+
+    default Double getAsDoubleValue(String namespace, String key) {
+        return getAsDoubleValue(TENANT.get(), namespace, key);
+    }
+
+    default Double getAsDoubleValue(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, Double.class);
+    }
+
+    default Boolean getAsBooleanValue(String key) {
+        return getAsBooleanValue(null, key);
+    }
+
+    default Boolean getAsBooleanValue(String namespace, String key) {
+        return getAsBooleanValue(TENANT.get(), namespace, key);
+    }
+
+    default Boolean getAsBooleanValue(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, Boolean.class);
+    }
+
+    default Character getAsCharValue(String key) {
+        return getAsCharValue(null, key);
+    }
+
+    default Character getAsCharValue(String namespace, String key) {
+        return getAsCharValue(TENANT.get(), namespace, key);
+    }
+
+    default Character getAsCharValue(String tenantId, String namespace, String key) {
+        return get(tenantId, namespace, key, Character.class);
+    }
+
+    default <T> T populateConfiguration(Class<T> clazz) {
+        return populateConfiguration(null, clazz);
+    }
+
+    default <T> T populateConfiguration(String namespace, Class<T> clazz) {
+        return populateConfiguration(TENANT.get(), namespace, clazz);
+    }
+
+    default <T> T populateConfiguration(String tenantId, String namespace, Class<T> clazz) {
+        return get(tenantId, namespace, null, clazz, Hint.EXTERNAL_LOOKUP);
+    }
+
+    default <T> DynamicConfiguration<T> getDynamicConfiguration(String key, Class<T> clazz, T defaultValue) {
+        return getDynamicConfiguration(null, key, clazz, defaultValue);
+    }
+
+    default <T> DynamicConfiguration<T> getDynamicConfiguration(String namespace, String key, Class<T> clazz,
+            T defaultValue) {
+        return getDynamicConfiguration(TENANT.get(), namespace, key, clazz, defaultValue);
+    }
+
+    default <T> DynamicConfiguration<T> getDynamicConfiguration(String tenant, String namespace, String key,
+            Class<T> clazz, T defaultValue) {
+        return DynamicConfiguration.getDynamicConfiguration(tenant, namespace, key, clazz, defaultValue, this);
+    }
+
+    default <T> DynamicConfiguration<List<T>> getDynamicConfigurationValues(String key, Class<T> clazz,
+            T defaultValue) {
+        return getDynamicConfigurationValues(null, key, clazz, defaultValue);
+    }
+
+    default <T> DynamicConfiguration<List<T>> getDynamicConfigurationValues(String namespace, String key,
+            Class<T> clazz, T defaultValue) {
+        return getDynamicConfigurationValues(TENANT.get(), namespace, key, clazz, defaultValue);
+    }
+
+    default <T> DynamicConfiguration<List<T>> getDynamicConfigurationValues(String tenant, String namespace, String key,
+            Class<T> clazz, T defaultValue) {
+        return DynamicConfiguration.getDynConfiguration(tenant, namespace, key, clazz, defaultValue, this);
+    }
+
+    default List<String> getAsStringValues(String key) {
+        return getAsStringValues(null, key);
+    }
+
+    default List<String> getAsStringValues(String namespace, String key) {
+        return getAsStringValues(TENANT.get(), namespace, key);
+    }
+
+    default List<String> getAsStringValues(String tenantId, String namespace, String key) {
+        String[] tempArray = get(tenantId, namespace, key, String[].class);
+        return tempArray == null ? Collections.emptyList() : Arrays.asList(tempArray);
+    }
+
+    default List<Byte> getAsByteValues(String key) {
+        return getAsByteValues(null, key);
+    }
+
+    default List<Byte> getAsByteValues(String namespace, String key) {
+        return getAsByteValues(TENANT.get(), namespace, key);
+    }
+
+    default List<Byte> getAsByteValues(String tenantId, String namespace, String key) {
+        Byte[] tempArray = get(tenantId, namespace, key, Byte[].class);
+        return tempArray == null ? Collections.emptyList() : Arrays.asList(tempArray);
+    }
+
+    default List<Short> getAsShortValues(String key) {
+        return getAsShortValues(null, key);
+    }
+
+    default List<Short> getAsShortValues(String namespace, String key) {
+        return getAsShortValues(TENANT.get(), namespace, key);
+    }
+
+    default List<Short> getAsShortValues(String tenantId, String namespace, String key) {
+        Short[] tempArray = get(tenantId, namespace, key, Short[].class);
+        return tempArray == null ? Collections.emptyList() : Arrays.asList(tempArray);
+    }
+
+    default List<Integer> getAsIntegerValues(String key) {
+        return getAsIntegerValues(null, key);
+    }
+
+    default List<Integer> getAsIntegerValues(String namespace, String key) {
+        return getAsIntegerValues(TENANT.get(), namespace, key);
+    }
+
+    default List<Integer> getAsIntegerValues(String tenantId, String namespace, String key) {
+        Integer[] tempArray = get(tenantId, namespace, key, Integer[].class);
+        return tempArray == null ? Collections.emptyList() : Arrays.asList(tempArray);
+    }
+
+    default List<Double> getAsDoubleValues(String key) {
+        return getAsDoubleValues(null, key);
+    }
+
+    default List<Double> getAsDoubleValues(String namespace, String key) {
+        return getAsDoubleValues(TENANT.get(), namespace, key);
+    }
+
+    default List<Double> getAsDoubleValues(String tenantId, String namespace, String key) {
+        Double[] tempArray = get(tenantId, namespace, key, Double[].class);
+        return tempArray == null ? Collections.emptyList() : Arrays.asList(tempArray);
+    }
+
+    default List<Float> getAsFloatValues(String key) {
+        return getAsFloatValues(null, key);
+    }
+
+    default List<Float> getAsFloatValues(String namespace, String key) {
+        return getAsFloatValues(TENANT.get(), namespace, key);
+    }
+
+    default List<Float> getAsFloatValues(String tenantId, String namespace, String key) {
+        Float[] tempArray = get(tenantId, namespace, key, Float[].class);
+        return tempArray == null ? Collections.emptyList() : Arrays.asList(tempArray);
+    }
+
+    default List<Boolean> getAsBooleanValues(String key) {
+        return getAsBooleanValues(null, key);
+    }
+
+    default List<Boolean> getAsBooleanValues(String namespace, String key) {
+        return getAsBooleanValues(TENANT.get(), namespace, key);
+    }
+
+    default List<Boolean> getAsBooleanValues(String tenantId, String namespace, String key) {
+        Boolean[] tempArray = get(tenantId, namespace, key, Boolean[].class);
+        return tempArray == null ? Collections.emptyList() : Arrays.asList(tempArray);
+    }
+
+    default List<Character> getAsCharacterValues(String key) {
+        return getAsCharacterValues(null, key);
+    }
+
+    default List<Character> getAsCharacterValues(String namespace, String key) {
+        return getAsCharacterValues(TENANT.get(), namespace, key);
+    }
+
+    default List<Character> getAsCharacterValues(String tenantId, String namespace, String key) {
+        Character[] tempArray = get(tenantId, namespace, key, Character[].class);
+        return tempArray == null ? Collections.emptyList() : Arrays.asList(tempArray);
+    }
+
+    default void addConfigurationChangeListener(String key, ConfigurationChangeListener myself) {
+        addConfigurationChangeListener(null, key, myself);
+    }
+
+    default void addConfigurationChangeListener(String namespace, String key, ConfigurationChangeListener myself) {
+        addConfigurationChangeListener(TENANT.get(), namespace, key, myself);
+    }
+
+    void addConfigurationChangeListener(String tenant, String namespace, String key,
+            ConfigurationChangeListener myself);
+
+    default void removeConfigurationChangeListener(String key, ConfigurationChangeListener myself) {
+        removeConfigurationChangeListener(null, key, myself);
+    }
+
+    default void removeConfigurationChangeListener(String namespace, String key, ConfigurationChangeListener myself) {
+        removeConfigurationChangeListener(TENANT.get(), namespace, key, myself);
+    }
+
+    void removeConfigurationChangeListener(String tenant, String namespace, String key,
+            ConfigurationChangeListener myself);
+
+    default <T> Map<String, T> populateMap(String key, Class<T> clazz) {
+        return populateMap(null, key, clazz);
+    }
+
+    default <T> Map<String, T> populateMap(String namespace, String key, Class<T> clazz) {
+        return populateMap(TENANT.get(), namespace, key, clazz);
+    }
+
+    <T> Map<String, T> populateMap(String tenantId, String namespace, String key, Class<T> clazz);
+
+    default Map generateMap(String key) {
+        return generateMap(null, key);
+    }
+
+    default Map generateMap(String namespace, String key) {
+        return generateMap(TENANT.get(), namespace, key);
+    }
+
+    Map generateMap(String tenantId, String namespace, String key);
 }
index 451a75f..dddd751 100644 (file)
@@ -1,14 +1,29 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.api;
 
 public interface ConfigurationChangeListener {
 
-  public default void notify(String tenantId, String component, String key, Object oldValue,
-                             Object newValue) {
-  }
+    default void notify(String tenantId, String component, String key, Object oldValue, Object newValue) {
+    }
 
-  public default void notify(String component, String key, Object oldValue, Object newValue) {
-  }
+    default void notify(String component, String key, Object oldValue, Object newValue) {
+    }
 
-  public default void notify(String key, Object oldValue, Object newValue) {
-  }
+    default void notify(String key, Object oldValue, Object newValue) {
+    }
 }
index 0e8f140..d91fdb1 100644 (file)
@@ -1,98 +1,52 @@
-package org.onap.config.api;
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 
+package org.onap.config.api;
 
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Proxy;
 import java.util.Collection;
+import java.util.Iterator;
 import java.util.Map;
 import java.util.ServiceLoader;
 
-/**
- * The interface Configuration manager.
- */
 public interface ConfigurationManager extends Configuration {
 
-  /**
-   * The constant config.
-   */
-  public static final Configuration config = lookup();
+    Configuration CONFIG = lookup();
+
+    static Configuration lookup() {
+
+        if (CONFIG == null) {
+            ServiceLoader<ConfigurationManager> loader = ServiceLoader.load(ConfigurationManager.class);
+            Iterator<ConfigurationManager> configManagers = loader.iterator();
+            return configManagers.hasNext() ? configManagers.next() : null;
+        }
 
-  /**
-   * Lookup configuration.
-   *
-   * @return the configuration
-   */
-  public static Configuration lookup() {
-    if (config == null) {
-      ServiceLoader<ConfigurationManager> loader = ServiceLoader.load(ConfigurationManager.class);
-      for (ConfigurationManager configuration : loader) {
-        return (Configuration) Proxy.newProxyInstance(ConfigurationManager.class.getClassLoader(),
-            new Class[]{Configuration.class}, (object, method, args) -> {
-              try {
-                return method.invoke(configuration, args);
-              } catch (InvocationTargetException ite) {
-                throw ite.getTargetException();
-              }
-            });
-      }
+        return CONFIG;
     }
-    return config;
-  }
 
-  /**
-   * Gets configuration value.
-   *
-   * @param queryData the query data
-   * @return the configuration value
-   */
-  public String getConfigurationValue(Map<String, Object> queryData);
+    String getConfigurationValue(Map<String, Object> queryData);
 
-  /**
-   * Update configuration value.
-   *
-   * @param updateData the update data
-   */
-  public void updateConfigurationValue(Map<String, Object> updateData);
+    void updateConfigurationValue(Map<String, Object> updateData);
 
-  /**
-   * List configuration map.
-   *
-   * @param query the query
-   * @return the map
-   */
-  public Map<String, String> listConfiguration(Map<String, Object> query);
+    Map<String, String> listConfiguration(Map<String, Object> query);
 
-  /**
-   * Update configuration values boolean.
-   *
-   * @param tenant              the tenant
-   * @param namespace           the namespace
-   * @param configKeyValueStore the config key value store
-   * @return the boolean
-   */
-  public boolean updateConfigurationValues(String tenant, String namespace,
-                                           Map configKeyValueStore);
+    boolean updateConfigurationValues(String tenant, String namespace, Map configKeyValueStore);
 
-  /**
-   * Gets tenants.
-   *
-   * @return the tenants
-   */
-  public Collection<String> getTenants();
+    Collection<String> getTenants();
 
-  /**
-   * Gets namespaces.
-   *
-   * @return the namespaces
-   */
-  public Collection<String> getNamespaces();
+    Collection<String> getNamespaces();
 
-  /**
-   * Gets keys.
-   *
-   * @param tenant    the tenant
-   * @param namespace the namespace
-   * @return the keys
-   */
-  public Collection<String> getKeys(String tenant, String namespace);
+    Collection<String> getKeys(String tenant, String namespace);
 }
index 969749b..c2973a4 100644 (file)
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.api;
 
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 
-/**
- * The type Dynamic configuration.
- *
- * @param <T> the type parameter
- */
+
 public class DynamicConfiguration<T> {
 
-  /**
-   * The Tenant.
-   */
-  String tenant;
-  /**
-   * The Namespace.
-   */
-  String namespace;
-  /**
-   * The Key.
-   */
-  String key;
-  /**
-   * The Configuration.
-   */
-  Configuration configuration;
-  /**
-   * The Clazz.
-   */
-  Class clazz;
-  /**
-   * The Default value.
-   */
-  T defaultValue;
+    private String tenant;
+
+    private String namespace;
+
+    private String key;
+
+    private Configuration configuration;
 
-  /**
-   * Gets dynamic configuration.
-   *
-   * @param <T>           the type parameter
-   * @param tenant        the tenant
-   * @param namespace     the namespace
-   * @param key           the key
-   * @param clazz         the clazz
-   * @param defaultValue  the default value
-   * @param configuration the configuration
-   * @return the dynamic configuration
-   */
-  public static <T> DynamicConfiguration<T> getDynamicConfiguration(String tenant, String namespace,
-                                                                    String key, Class<T> clazz,
-                                                                    T defaultValue,
-                                                                    Configuration configuration) {
-    DynamicConfiguration<T> dynamicConfiguration = new DynamicConfiguration<>();
-    dynamicConfiguration.tenant = tenant;
-    dynamicConfiguration.namespace = namespace;
-    dynamicConfiguration.key = key;
-    dynamicConfiguration.clazz = clazz;
-    dynamicConfiguration.defaultValue = defaultValue;
-    dynamicConfiguration.configuration = configuration;
-    return dynamicConfiguration;
-  }
+    private Class clazz;
+
+    private T defaultValue;
+
+    public static <K> DynamicConfiguration<List<K>> getDynConfiguration(String tenant, String namespace, String key,
+            Class<K> clazz, K defaultValue, Configuration configuration) {
+        if (clazz.isPrimitive()) {
+            throw new RuntimeException("Only Wrapper classes like Integer, Long, Double, "
+                                               + "Boolean etc including String are supported.");
+        }
+        return getDynamicConfiguration(tenant, namespace, key, getArrayClass(clazz),
+                Collections.singletonList(defaultValue), configuration);
+    }
 
-  /**
-   * Gets dyn configuration.
-   *
-   * @param <K>           the type parameter
-   * @param tenant        the tenant
-   * @param namespace     the namespace
-   * @param key           the key
-   * @param clazz         the clazz
-   * @param defaultValue  the default value
-   * @param configuration the configuration
-   * @return the dyn configuration
-   */
-  public static <K> DynamicConfiguration<List<K>> getDynConfiguration(String tenant,
-                                                                      String namespace, String key,
-                                                                      Class<K> clazz,
-                                                                      K defaultValue,
-                                                                      Configuration configuration) {
-    if (clazz.isPrimitive()) {
-      throw new RuntimeException(
-          "Only Wrapper classes like Integer, Long, Double, "
-              + "Boolean etc including String are supported.");
+    public static <T> DynamicConfiguration<T> getDynamicConfiguration(String tenant, String namespace, String key,
+            Class<T> clazz, T defaultValue, Configuration configuration) {
+        DynamicConfiguration<T> dynamicConfiguration = new DynamicConfiguration<>();
+        dynamicConfiguration.tenant = tenant;
+        dynamicConfiguration.namespace = namespace;
+        dynamicConfiguration.key = key;
+        dynamicConfiguration.clazz = clazz;
+        dynamicConfiguration.defaultValue = defaultValue;
+        dynamicConfiguration.configuration = configuration;
+        return dynamicConfiguration;
     }
-    return getDynamicConfiguration(tenant, namespace, key, getArrayClass(clazz),
-        Arrays.asList(defaultValue), configuration);
-  }
 
-  /**
-   * Gets array class.
-   *
-   * @param clazz the clazz
-   * @return the array class
-   */
-  public static Class getArrayClass(Class clazz) {
-    Class arrayClass = null;
-    switch (clazz.getName()) {
-      case "java.lang.Byte":
-        arrayClass = Byte[].class;
-        break;
-      case "java.lang.Short":
-        arrayClass = Short[].class;
-        break;
-      case "java.lang.Integer":
-        arrayClass = Integer[].class;
-        break;
-      case "java.lang.Long":
-        arrayClass = Long[].class;
-        break;
-      case "java.lang.Float":
-        arrayClass = Float[].class;
-        break;
-      case "java.lang.Double":
-        arrayClass = Double[].class;
-        break;
-      case "java.lang.Boolean":
-        arrayClass = Boolean[].class;
-        break;
-      case "java.lang.Character":
-        arrayClass = Character[].class;
-        break;
-      case "java.lang.String":
-        arrayClass = String[].class;
-        break;
-      default:
+    public static Class getArrayClass(Class clazz) {
+        Class arrayClass = null;
+        switch (clazz.getName()) {
+            case "java.lang.Byte":
+                arrayClass = Byte[].class;
+                break;
+            case "java.lang.Short":
+                arrayClass = Short[].class;
+                break;
+            case "java.lang.Integer":
+                arrayClass = Integer[].class;
+                break;
+            case "java.lang.Long":
+                arrayClass = Long[].class;
+                break;
+            case "java.lang.Float":
+                arrayClass = Float[].class;
+                break;
+            case "java.lang.Double":
+                arrayClass = Double[].class;
+                break;
+            case "java.lang.Boolean":
+                arrayClass = Boolean[].class;
+                break;
+            case "java.lang.Character":
+                arrayClass = Character[].class;
+                break;
+            case "java.lang.String":
+                arrayClass = String[].class;
+                break;
+            default:
+        }
+        return arrayClass;
     }
-    return arrayClass;
-  }
 
-  /**
-   * Get t.
-   *
-   * @return the t
-   */
-  public T get() {
-    Object toReturn = configuration
-        .get(tenant, namespace, key, clazz, Hint.LATEST_LOOKUP, Hint.EXTERNAL_LOOKUP,
-            Hint.NODE_SPECIFIC);
-    if (toReturn != null && toReturn.getClass().isArray()) {
-      toReturn = Arrays.asList((Object[]) toReturn);
+    public T get() {
+        Object toReturn = configuration.get(tenant, namespace, key, clazz, Hint.LATEST_LOOKUP, Hint.EXTERNAL_LOOKUP,
+                Hint.NODE_SPECIFIC);
+        if (toReturn != null && toReturn.getClass().isArray()) {
+            toReturn = Arrays.asList((Object[]) toReturn);
+        }
+        return toReturn == null ? defaultValue : (T) toReturn;
     }
-    return toReturn == null ? defaultValue : (T) toReturn;
-  }
 
 }
index 17b58f6..373b643 100644 (file)
@@ -1,18 +1,34 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.api;
 
 public enum Hint {
 
-  DEFAULT(0b0), LATEST_LOOKUP(0b1), EXTERNAL_LOOKUP(0b10), NODE_SPECIFIC(0b100);
+    DEFAULT(0b0), LATEST_LOOKUP(0b1), EXTERNAL_LOOKUP(0b10), NODE_SPECIFIC(0b100);
 
-  private final int lookupHint;
+    private final int lookupHint;
 
-  private Hint(int hnt) {
-    lookupHint = hnt;
-  }
+    Hint(int hint) {
+        lookupHint = hint;
+    }
 
-  public int value() {
-    return lookupHint;
-  }
+    public int value() {
+        return lookupHint;
+    }
 
 
 }
index f5b3400..7c5573c 100755 (executable)
@@ -14,8 +14,8 @@
   ~ limitations under the License.
   -->
 
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xmlns="http://maven.apache.org/POM/4.0.0"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 
     <modelVersion>4.0.0</modelVersion>
index 953ee15..528941b 100644 (file)
@@ -81,16 +81,10 @@ import org.onap.config.type.ConfigurationType;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-/**
- * The type Configuration utils.
- */
 public class ConfigurationUtils {
+
     private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationUtils.class);
     private static final String CONFIGURATION_TYPE_NOT_SUPPORTED = "Configuration type not supported:";
-
-    private ConfigurationUtils() {
-    }
-
     private static final Map<Class, Class> ARRAY_CLASS_MAP;
 
     static {
@@ -107,11 +101,9 @@ public class ConfigurationUtils {
         ARRAY_CLASS_MAP = Collections.unmodifiableMap(arrayTypes);
     }
 
-    /**
-     * Gets thread factory.
-     *
-     * @return the thread factory
-     */
+    private ConfigurationUtils() {
+    }
+
     public static ThreadFactory getThreadFactory() {
         return r1 -> {
             Thread thread = Executors.privilegedThreadFactory().newThread(r1);
@@ -120,14 +112,6 @@ public class ConfigurationUtils {
         };
     }
 
-    /**
-     * Gets all files.
-     *
-     * @param file          the file
-     * @param recursive     the recursive
-     * @param onlyDirectory the only directory
-     * @return the all files
-     */
     public static Collection<File> getAllFiles(File file, boolean recursive, boolean onlyDirectory) {
         ArrayList<File> collection = new ArrayList<>();
         if (file.isDirectory() && file.exists()) {
@@ -146,206 +130,81 @@ public class ConfigurationUtils {
         return collection;
     }
 
-    /**
-     * Gets comma saperated list.
-     *
-     * @param list the list
-     * @return the comma separated list
-     */
-    public static String getCommaSeparatedList(List list) {
-        return ((Stream<String>) list.stream().filter(o -> o != null && !o.toString().trim().isEmpty()).map(o -> o.toString().trim())).collect(Collectors.joining(","));
-    }
-
-    /**
-     * Gets comma saperated list.
-     *
-     * @param list the list
-     * @return the comma saperated list
-     */
     public static String getCommaSeparatedList(String[] list) {
-        return getCommaSeparatedList(list == null ? Arrays.asList() : Arrays.asList(list));
+        return getCommaSeparatedList(list == null ? Collections.emptyList() : Arrays.asList(list));
     }
 
-    /**
-     * Gets config type.
-     *
-     * @param url the url
-     * @return the config type
-     */
-    public static ConfigurationType getConfigType(URL url) {
-        return Enum.valueOf(ConfigurationType.class,
-                url.getFile().substring(url.getFile().lastIndexOf('.') + 1).toUpperCase());
-    }
-
-    /**
-     * Gets config type.
-     *
-     * @param file the file
-     * @return the config type
-     */
-    public static ConfigurationType getConfigType(File file) {
-        return Enum.valueOf(ConfigurationType.class,
-                file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf('.') + 1)
-                        .toUpperCase());
+    public static String getCommaSeparatedList(List list) {
+        return ((Stream<String>) list.stream().filter(o -> o != null && !o.toString().trim().isEmpty())
+                                         .map(o -> o.toString().trim())).collect(Collectors.joining(","));
     }
 
-    /**
-     * Is config boolean.
-     *
-     * @param url the url
-     * @return the boolean
-     */
     public static boolean isConfig(URL url) {
         return isConfig(url.getFile());
     }
 
-    /**
-     * Is config boolean.
-     *
-     * @param file the file
-     * @return the boolean
-     */
-    public static boolean isConfig(File file) {
-        return file != null && file.exists() && isConfig(file.getName());
-    }
-
-    /**
-     * Is config boolean.
-     *
-     * @param file the file
-     * @return the boolean
-     */
     public static boolean isConfig(String file) {
         file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
         file = file.substring(file.lastIndexOf('/') + 1);
         return file.matches(
-                "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
-                        + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
-                        + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
-                        + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$")
-                || file.matches("CONFIG(.)*\\.(" + ConfigurationType.PROPERTIES.name() + "|"
-                + ConfigurationType.XML.name() + "|" + ConfigurationType.JSON.name() + "|"
-                + ConfigurationType.YAML.name() + ")$");
-    }
-
-    /**
-     * Gets namespace.
-     *
-     * @param url the url
-     * @return the namespace
-     */
-    public static String getNamespace(URL url) {
-
-        Optional<String> namespace = getConfiguration(url).flatMap(ConfigurationUtils::getNamespace).map(String::toUpperCase);
-
-        return namespace.orElseGet(() -> getNamespace(url.getFile().toUpperCase()));
+                "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE + "|"
+                        + ConfigurationMode.UNION + ")){0,1}" + "\\.(" + ConfigurationType.PROPERTIES.name() + "|"
+                        + ConfigurationType.XML.name() + "|" + ConfigurationType.JSON.name() + "|"
+                        + ConfigurationType.YAML.name() + ")$") || file.matches(
+                "CONFIG(.)*\\.(" + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
+                        + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
     }
 
-    /**
-     * Gets namespace.
-     *
-     * @param file the file
-     * @return the namespace
-     */
-    public static String getNamespace(File file) {
-        Optional<String> namespace = getConfiguration(file)
-                .flatMap(ConfigurationUtils::getNamespace)
-                .map(String::toUpperCase);
-        return namespace.orElseGet(() -> getNamespace(file.getName().toUpperCase()));
+    public static boolean isConfig(File file) {
+        return file != null && file.exists() && isConfig(file.getName());
     }
 
     private static Optional<String> getNamespace(Configuration config) {
-        return ofNullable(config)
-                .flatMap(configuration -> ofNullable(configuration.getString(Constants.NAMESPACE_KEY)))
-                .map(String::toUpperCase);
+        return ofNullable(config).flatMap(configuration -> ofNullable(configuration.getString(Constants.NAMESPACE_KEY)))
+                       .map(String::toUpperCase);
     }
 
-    /**
-     * Gets namespace.
-     *
-     * @param file the file
-     * @return the namespace
-     */
-    public static String getNamespace(String file) {
-        file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
-        file = file.substring(file.lastIndexOf('/') + 1);
-        Pattern pattern = Pattern.compile(
-                "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
-                        + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
-                        + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
-                        + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
-        Matcher matcher = pattern.matcher(file);
-        boolean b1 = matcher.matches();
-        if (b1) {
-            if (matcher.group(1) != null) {
-                String moduleName = matcher.group(1).substring(1);
-                return moduleName.equalsIgnoreCase(ConfigurationMode.OVERRIDE.name())
-                        || moduleName.equalsIgnoreCase(ConfigurationMode.UNION.name())
-                        || moduleName.equalsIgnoreCase(ConfigurationMode.MERGE.name())
-                        ? Constants.DEFAULT_NAMESPACE : moduleName;
-            } else {
-                return Constants.DEFAULT_NAMESPACE;
-            }
-        } else if (isConfig(file)) {
-            return Constants.DEFAULT_NAMESPACE;
-        }
-
-        return null;
-    }
-
-    /**
-     * Gets merge strategy.
-     *
-     * @param url the url
-     * @return the merge strategy
-     */
     public static ConfigurationMode getMergeStrategy(URL url) {
-        Optional<ConfigurationMode> configurationMode = getConfiguration(url).flatMap(ConfigurationUtils::getMergeStrategy).flatMap(ConfigurationUtils::convertConfigurationMode);
+        Optional<ConfigurationMode> configurationMode =
+                getConfiguration(url).flatMap(ConfigurationUtils::getMergeStrategy)
+                        .flatMap(ConfigurationUtils::convertConfigurationMode);
         return configurationMode.orElseGet(() -> getMergeStrategy(url.getFile().toUpperCase()));
     }
 
-    private static Optional<ConfigurationMode> convertConfigurationMode(String configMode) {
-        ConfigurationMode configurationMode = null;
+    public static Optional<FileBasedConfiguration> getConfiguration(URL url) {
+        FileBasedConfiguration builder = null;
         try {
-            configurationMode = ConfigurationMode.valueOf(configMode);
-        } catch (Exception exception) {
-            LOGGER.error("Could not find convert {} into configuration mode", configMode);
+            ConfigurationType configType = ConfigurationUtils.getConfigType(url);
+            switch (configType) {
+                case PROPERTIES:
+                    builder = new Configurations().fileBased(PropertiesConfiguration.class, url);
+                    break;
+                case XML:
+                    builder = new Configurations().fileBased(XMLConfiguration.class, url);
+                    break;
+                case JSON:
+                    builder = new Configurations().fileBased(JsonConfiguration.class, url);
+                    break;
+                case YAML:
+                    builder = new Configurations().fileBased(YamlConfiguration.class, url);
+                    break;
+                default:
+                    throw new ConfigurationException(CONFIGURATION_TYPE_NOT_SUPPORTED + configType);
+            }
+        } catch (ConfigurationException exception) {
+            exception.printStackTrace();
         }
-        return Optional.ofNullable(configurationMode);
-    }
-
-    private static Optional<String> getMergeStrategy(Configuration config) {
-        return ofNullable(config)
-                .flatMap(configuration -> ofNullable(configuration.getString(Constants.MODE_KEY)))
-                .map(String::toUpperCase);
-    }
-
-
-    /**
-     * Gets merge strategy.
-     *
-     * @param file the file
-     * @return the merge strategy
-     */
-    public static ConfigurationMode getMergeStrategy(File file) {
-        Optional<ConfigurationMode> configurationMode = getConfiguration(file).flatMap(ConfigurationUtils::getMergeStrategy).flatMap(ConfigurationUtils::convertConfigurationMode);
-        return configurationMode.orElseGet(() -> getMergeStrategy(file.getName().toUpperCase()));
+        return ofNullable(builder);
     }
 
-    /**
-     * Gets merge strategy.
-     *
-     * @param file the file
-     * @return the merge strategy
-     */
     public static ConfigurationMode getMergeStrategy(String file) {
         file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
         file = file.substring(file.lastIndexOf('/') + 1);
         Pattern pattern = Pattern.compile(
-                "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE
-                        + "|" + ConfigurationMode.UNION + ")){0,1}" + "\\.("
-                        + ConfigurationType.PROPERTIES.name() + "|" + ConfigurationType.XML.name() + "|"
-                        + ConfigurationType.JSON.name() + "|" + ConfigurationType.YAML.name() + ")$");
+                "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE + "|"
+                        + ConfigurationMode.UNION + ")){0,1}" + "\\.(" + ConfigurationType.PROPERTIES.name() + "|"
+                        + ConfigurationType.XML.name() + "|" + ConfigurationType.JSON.name() + "|"
+                        + ConfigurationType.YAML.name() + ")$");
         Matcher matcher = pattern.matcher(file);
         boolean b1 = matcher.matches();
         if (b1) {
@@ -365,44 +224,33 @@ public class ConfigurationUtils {
         return null;
     }
 
-    /**
-     * Gets configuration.
-     *
-     * @param url the url
-     * @return the configuration
-     */
-    public static Optional<FileBasedConfiguration> getConfiguration(URL url) {
-        FileBasedConfiguration builder = null;
+    public static ConfigurationType getConfigType(URL url) {
+        return Enum.valueOf(ConfigurationType.class,
+                url.getFile().substring(url.getFile().lastIndexOf('.') + 1).toUpperCase());
+    }
+
+    private static Optional<ConfigurationMode> convertConfigurationMode(String configMode) {
+        ConfigurationMode configurationMode = null;
         try {
-            ConfigurationType configType = ConfigurationUtils.getConfigType(url);
-            switch (configType) {
-                case PROPERTIES:
-                    builder = new Configurations().fileBased(PropertiesConfiguration.class, url);
-                    break;
-                case XML:
-                    builder = new Configurations().fileBased(XMLConfiguration.class, url);
-                    break;
-                case JSON:
-                    builder = new Configurations().fileBased(JsonConfiguration.class, url);
-                    break;
-                case YAML:
-                    builder = new Configurations().fileBased(YamlConfiguration.class, url);
-                    break;
-                default:
-                    throw new ConfigurationException(CONFIGURATION_TYPE_NOT_SUPPORTED + configType);
-            }
-        } catch (ConfigurationException exception) {
-            exception.printStackTrace();
+            configurationMode = ConfigurationMode.valueOf(configMode);
+        } catch (Exception exception) {
+            LOGGER.error("Could not find convert {} into configuration mode", configMode);
         }
-        return ofNullable(builder);
+        return Optional.ofNullable(configurationMode);
+    }
+
+    private static Optional<String> getMergeStrategy(Configuration config) {
+        return ofNullable(config).flatMap(configuration -> ofNullable(configuration.getString(Constants.MODE_KEY)))
+                       .map(String::toUpperCase);
+    }
+
+    public static ConfigurationMode getMergeStrategy(File file) {
+        Optional<ConfigurationMode> configurationMode =
+                getConfiguration(file).flatMap(ConfigurationUtils::getMergeStrategy)
+                        .flatMap(ConfigurationUtils::convertConfigurationMode);
+        return configurationMode.orElseGet(() -> getMergeStrategy(file.getName().toUpperCase()));
     }
 
-    /**
-     * Gets configuration.
-     *
-     * @param file the file
-     * @return the configuration
-     */
     public static Optional<FileBasedConfiguration> getConfiguration(File file) {
         FileBasedConfiguration builder = null;
         try {
@@ -429,12 +277,11 @@ public class ConfigurationUtils {
         return ofNullable(builder);
     }
 
-    /**
-     * Gets collection generic type.
-     *
-     * @param field the field
-     * @return the collection generic type
-     */
+    public static ConfigurationType getConfigType(File file) {
+        return Enum.valueOf(ConfigurationType.class,
+                file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf('.') + 1).toUpperCase());
+    }
+
     public static Class getCollectionGenericType(Field field) {
         Type type = field.getGenericType();
 
@@ -442,74 +289,44 @@ public class ConfigurationUtils {
 
             ParameterizedType paramType = (ParameterizedType) type;
             Type[] arr = paramType.getActualTypeArguments();
-
-            for (Type tp : arr) {
-                Class<?> clzz = (Class<?>) tp;
-                if (isWrapperClass(clzz)) {
-                    return clzz;
+            if (arr.length > 0) {
+                Class<?> clazz = (Class<?>) arr[0];
+                if (isWrapperClass(clazz)) {
+                    return clazz;
                 } else {
-                    throw new RuntimeException("Collection of type " + clzz.getName() + " not supported.");
+                    throw new RuntimeException("Collection of type " + clazz.getName() + " not supported.");
                 }
             }
         }
+
         return String[].class;
     }
 
+    public static boolean isWrapperClass(Class clazz) {
+        return clazz == String.class || clazz == Boolean.class || clazz == Character.class
+                       || Number.class.isAssignableFrom(clazz);
+    }
 
-    /**
-     * Gets array class.
-     *
-     * @param clazz the clazz
-     * @return the array class
-     */
     public static Class getArrayClass(Class clazz) {
         return ARRAY_CLASS_MAP.getOrDefault(clazz, null);
     }
 
-    /**
-     * Gets all class path resources.
-     *
-     * @return the all class path resources
-     */
     public static List<URL> getAllClassPathResources() {
         return CPScanner.scanResources(new ResourceFilter());
     }
 
-    /**
-     * Gets configuration builder.
-     *
-     * @param url the url
-     * @return the configuration builder
-     */
     public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(URL url) {
         ConfigurationType configType = ConfigurationUtils.getConfigType(url);
-        ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder = getFileBasedConfigurationReloadingFileBasedConfigurationBuilder(
-                configType);
-        builder.configure(new Parameters().fileBased().setURL(url)
-                .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
+        ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder =
+                getFileBasedConfigurationReloadingFileBasedConfigurationBuilder(configType);
+        builder.configure(
+                new Parameters().fileBased().setURL(url).setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
         return builder;
     }
 
-    /**
-     * Gets configuration builder.
-     *
-     * @param file     the file
-     * @param autoSave the auto save
-     * @return the configuration builder
-     */
-    public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(File file,
-                                                                                            boolean autoSave) {
-        ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder;
-        ConfigurationType configType = ConfigurationUtils.getConfigType(file);
-        builder = getFileBasedConfigurationReloadingFileBasedConfigurationBuilder(configType);
-        builder.configure(new Parameters().fileBased().setFile(file)
-                .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
-        builder.setAutoSave(autoSave);
-        return builder;
-    }
+    private static ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>
+            getFileBasedConfigurationReloadingFileBasedConfigurationBuilder(ConfigurationType configType) {
 
-    private static ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> getFileBasedConfigurationReloadingFileBasedConfigurationBuilder(
-            ConfigurationType configType) {
         ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder;
         switch (configType) {
             case PROPERTIES:
@@ -530,30 +347,28 @@ public class ConfigurationUtils {
         return builder;
     }
 
-    /**
-     * Read t.
-     *
-     * @param <T>       the type parameter
-     * @param config    the config
-     * @param clazz     the clazz
-     * @param keyPrefix the key prefix
-     * @return the t
-     * @throws Exception the exception
-     */
-    public static <T> T read(Configuration config, Class<T> clazz, String keyPrefix)
-            throws Exception {
-        Config confAnnot =
-                clazz.getAnnotation(Config.class);
-        if (confAnnot != null) {
-            keyPrefix += (confAnnot.key() + ".");
+    public static BasicConfigurationBuilder<FileBasedConfiguration> getConfigurationBuilder(File file,
+            boolean autoSave) {
+        ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder;
+        ConfigurationType configType = ConfigurationUtils.getConfigType(file);
+        builder = getFileBasedConfigurationReloadingFileBasedConfigurationBuilder(configType);
+        builder.configure(new Parameters().fileBased().setFile(file)
+                                  .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
+        builder.setAutoSave(autoSave);
+        return builder;
+    }
+
+    public static <T> T read(Configuration config, Class<T> clazz, String keyPrefix) throws Exception {
+        Config confAnnotation = clazz.getAnnotation(Config.class);
+        if (confAnnotation != null) {
+            keyPrefix += (confAnnotation.key() + ".");
         }
         T objToReturn = clazz.newInstance();
         for (Field field : clazz.getDeclaredFields()) {
-            Config fieldConfAnnot =
-                    field.getAnnotation(Config.class);
-            if (fieldConfAnnot != null) {
+            Config fieldAnnotation = field.getAnnotation(Config.class);
+            if (fieldAnnotation != null) {
                 field.setAccessible(true);
-                field.set(objToReturn, config.getProperty(keyPrefix + fieldConfAnnot.key()));
+                field.set(objToReturn, config.getProperty(keyPrefix + fieldAnnotation.key()));
             } else if (field.getType().getAnnotation(Config.class) != null) {
                 field.set(objToReturn, read(config, field.getType(), keyPrefix));
             }
@@ -561,42 +376,6 @@ public class ConfigurationUtils {
         return objToReturn;
     }
 
-    /**
-     * Gets property.
-     *
-     * @param config          the config
-     * @param key             the key
-     * @param processingHints the processing hints
-     * @return the property
-     */
-    public static Object getProperty(Configuration config, String key, int processingHints) {
-        if (!isDirectLookup(processingHints)) {
-            if (config instanceof AgglomerateConfiguration) {
-                return ((AgglomerateConfiguration) config).getPropertyValue(key);
-            } else if (config instanceof CompositeConfiguration) {
-                CompositeConfiguration conf = (CompositeConfiguration) config;
-                for (int i = 0; i < conf.getNumberOfConfigurations(); i++) {
-                    if (conf.getConfiguration(i) instanceof AgglomerateConfiguration) {
-                        return ((AgglomerateConfiguration) conf.getConfiguration(i)).getPropertyValue(key);
-                    } else if (isNodeSpecific(processingHints)) {
-                        Object obj = conf.getConfiguration(i).getProperty(key);
-                        if (obj != null) {
-                            return obj;
-                        }
-                    }
-                }
-            }
-        }
-        return config.getProperty(key);
-    }
-
-    /**
-     * Gets primitive array.
-     *
-     * @param collection the collection
-     * @param clazz      the clazz
-     * @return the primitive array
-     */
     public static Object getPrimitiveArray(Collection collection, Class clazz) {
         if (clazz == int.class) {
             int[] array = new int[collection.size()];
@@ -657,23 +436,6 @@ public class ConfigurationUtils {
         return null;
     }
 
-    /**
-     * Is wrapper class boolean.
-     *
-     * @param clazz the clazz
-     * @return the boolean
-     */
-    public static boolean isWrapperClass(Class clazz) {
-        return clazz == String.class || clazz == Boolean.class || clazz == Character.class
-                || Number.class.isAssignableFrom(clazz);
-    }
-
-    /**
-     * Gets collection string.
-     *
-     * @param input the input
-     * @return the collection string
-     */
     public static String getCollectionString(String input) {
         Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
         Matcher matcher = pattern.matcher(input);
@@ -683,26 +445,6 @@ public class ConfigurationUtils {
         return input;
     }
 
-    /**
-     * Is collection boolean.
-     *
-     * @param input the input
-     * @return the boolean
-     */
-    public static boolean isCollection(String input) {
-        Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
-        Matcher matcher = pattern.matcher(input);
-        return matcher.matches();
-    }
-
-    /**
-     * Process variables if present string.
-     *
-     * @param tenant    the tenant
-     * @param namespace the namespace
-     * @param data      the data
-     * @return the string
-     */
     public static String processVariablesIfPresent(String tenant, String namespace, String data) {
         Pattern pattern = Pattern.compile("^.*\\$\\{(.*)\\}.*");
         Matcher matcher = pattern.matcher(data);
@@ -727,12 +469,6 @@ public class ConfigurationUtils {
         }
     }
 
-    /**
-     * Gets file contents.
-     *
-     * @param path the path
-     * @return the file contents
-     */
     public static String getFileContents(String path) {
         try {
             if (path != null) {
@@ -744,12 +480,6 @@ public class ConfigurationUtils {
         return null;
     }
 
-    /**
-     * Gets file contents.
-     *
-     * @param path the path
-     * @return the file contents
-     */
     public static String getFileContents(Path path) {
         try {
             if (path != null) {
@@ -761,40 +491,6 @@ public class ConfigurationUtils {
         return null;
     }
 
-    /**
-     * Gets concrete collection.
-     *
-     * @param clazz the clazz
-     * @return the concrete collection
-     */
-    public static Collection getConcreteCollection(Class clazz) {
-        switch (clazz.getName()) {
-            case "java.util.Collection":
-            case "java.util.List":
-                return new ArrayList<>();
-            case "java.util.Set":
-                return new HashSet<>();
-            case "java.util.SortedSet":
-                return new TreeSet<>();
-            case "java.util.Queue":
-                return new ConcurrentLinkedQueue<>();
-            case "java.util.Deque":
-                return new ArrayDeque<>();
-            case "java.util.concurrent.TransferQueue":
-                return new LinkedTransferQueue<>();
-            case "java.util.concurrent.BlockingQueue":
-                return new LinkedBlockingQueue<>();
-            default:
-                return null;
-        }
-    }
-
-    /**
-     * Gets default for.
-     *
-     * @param clazz the clazz
-     * @return the default for
-     */
     public static Object getDefaultFor(Class clazz) {
         if (byte.class == clazz) {
             return new Byte("0");
@@ -814,12 +510,6 @@ public class ConfigurationUtils {
         return (char) 0;
     }
 
-    /**
-     * Gets compatible collection for abstract def.
-     *
-     * @param clazz the clazz
-     * @return the compatible collection for abstract def
-     */
     public static Collection getCompatibleCollectionForAbstractDef(Class clazz) {
         if (BlockingQueue.class.isAssignableFrom(clazz)) {
             return getConcreteCollection(BlockingQueue.class);
@@ -845,12 +535,33 @@ public class ConfigurationUtils {
         return null;
     }
 
-    /**
-     * Gets configuration repository key.
-     *
-     * @param array the array
-     * @return the configuration repository key
-     */
+    public static Collection getConcreteCollection(Class clazz) {
+        switch (clazz.getName()) {
+            case "java.util.Collection":
+            case "java.util.List":
+                return new ArrayList<>();
+            case "java.util.Set":
+                return new HashSet<>();
+            case "java.util.SortedSet":
+                return new TreeSet<>();
+            case "java.util.Queue":
+                return new ConcurrentLinkedQueue<>();
+            case "java.util.Deque":
+                return new ArrayDeque<>();
+            case "java.util.concurrent.TransferQueue":
+                return new LinkedTransferQueue<>();
+            case "java.util.concurrent.BlockingQueue":
+                return new LinkedBlockingQueue<>();
+            default:
+                return null;
+        }
+    }
+
+    public static String getConfigurationRepositoryKey(File file) {
+        return getConfigurationRepositoryKey(
+                ConfigurationUtils.getNamespace(file).split(Constants.TENANT_NAMESPACE_SEPARATOR));
+    }
+
     public static String getConfigurationRepositoryKey(String[] array) {
         Deque<String> stack = new ArrayDeque<>();
         stack.push(Constants.DEFAULT_TENANT);
@@ -858,44 +569,61 @@ public class ConfigurationUtils {
             stack.push(element);
         }
         String toReturn = stack.pop();
-        return stack.pop() + Constants.KEY_ELEMENTS_DELEMETER + toReturn;
+        return stack.pop() + Constants.KEY_ELEMENTS_DELIMETER + toReturn;
     }
 
-    /**
-     * Gets configuration repository key.
-     *
-     * @param file the file
-     * @return the configuration repository key
-     */
-    public static String getConfigurationRepositoryKey(File file) {
-        return getConfigurationRepositoryKey(
-                ConfigurationUtils.getNamespace(file).split(Constants.TENANT_NAMESPACE_SAPERATOR));
+    public static String getNamespace(File file) {
+        Optional<String> namespace =
+                getConfiguration(file).flatMap(ConfigurationUtils::getNamespace).map(String::toUpperCase);
+        return namespace.orElseGet(() -> getNamespace(file.getName().toUpperCase()));
+    }
+
+    public static String getNamespace(String file) {
+        file = file.toUpperCase().substring(file.lastIndexOf('!') + 1);
+        file = file.substring(file.lastIndexOf('/') + 1);
+        Pattern pattern = Pattern.compile(
+                "CONFIG(-\\w*){0,1}(-" + "(" + ConfigurationMode.OVERRIDE + "|" + ConfigurationMode.MERGE + "|"
+                        + ConfigurationMode.UNION + ")){0,1}" + "\\.(" + ConfigurationType.PROPERTIES.name() + "|"
+                        + ConfigurationType.XML.name() + "|" + ConfigurationType.JSON.name() + "|"
+                        + ConfigurationType.YAML.name() + ")$");
+        Matcher matcher = pattern.matcher(file);
+        boolean b1 = matcher.matches();
+        if (b1) {
+            if (matcher.group(1) != null) {
+                String moduleName = matcher.group(1).substring(1);
+                return moduleName.equalsIgnoreCase(ConfigurationMode.OVERRIDE.name()) || moduleName.equalsIgnoreCase(
+                        ConfigurationMode.UNION.name()) || moduleName.equalsIgnoreCase(ConfigurationMode.MERGE.name())
+                               ? Constants.DEFAULT_NAMESPACE : moduleName;
+            } else {
+                return Constants.DEFAULT_NAMESPACE;
+            }
+        } else if (isConfig(file)) {
+            return Constants.DEFAULT_NAMESPACE;
+        }
+
+        return null;
     }
 
-    /**
-     * Gets configuration repository key.
-     *
-     * @param url the url
-     * @return the configuration repository key
-     */
     public static String getConfigurationRepositoryKey(URL url) {
         return getConfigurationRepositoryKey(
-                ConfigurationUtils.getNamespace(url).split(Constants.TENANT_NAMESPACE_SAPERATOR));
+                ConfigurationUtils.getNamespace(url).split(Constants.TENANT_NAMESPACE_SEPARATOR));
+    }
+
+    public static String getNamespace(URL url) {
+
+        Optional<String> namespace =
+                getConfiguration(url).flatMap(ConfigurationUtils::getNamespace).map(String::toUpperCase);
+
+        return namespace.orElseGet(() -> getNamespace(url.getFile().toUpperCase()));
     }
 
-    /**
-     * To map linked hash map.
-     *
-     * @param config the config
-     * @return the linked hash map
-     */
     public static LinkedHashMap toMap(Configuration config) {
         Iterator<String> iterator = config.getKeys();
         LinkedHashMap<String, String> map = new LinkedHashMap<>();
         while (iterator.hasNext()) {
             String key = iterator.next();
-            if (!(key.equals(Constants.MODE_KEY) || key.equals(Constants.NAMESPACE_KEY)
-                    || key.equals(Constants.LOAD_ORDER_KEY))) {
+            if (!(key.equals(Constants.MODE_KEY) || key.equals(Constants.NAMESPACE_KEY) || key.equals(
+                    Constants.LOAD_ORDER_KEY))) {
                 map.put(key, config.getProperty(key).toString());
             }
         }
@@ -903,13 +631,6 @@ public class ConfigurationUtils {
         return map;
     }
 
-    /**
-     * Diff map.
-     *
-     * @param orig   the orig
-     * @param latest the latest
-     * @return the map
-     */
     public static Map diff(LinkedHashMap orig, LinkedHashMap latest) {
         orig = new LinkedHashMap<>(orig);
         latest = new LinkedHashMap<>(latest);
@@ -930,54 +651,52 @@ public class ConfigurationUtils {
         return new HashMap<>(latest);
     }
 
-    /**
-     * Is array boolean.
-     *
-     * @param tenant          the tenant
-     * @param namespace       the namespace
-     * @param key             the key
-     * @param processingHints the processing hints
-     * @return the boolean
-     * @throws Exception the exception
-     */
-    public static boolean isArray(String tenant, String namespace, String key, int processingHints)
-            throws Exception {
+    public static boolean isArray(String tenant, String namespace, String key, int processingHints) throws Exception {
         Object obj = ConfigurationUtils
-                .getProperty(ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key,
-                        processingHints);
+                             .getProperty(ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key,
+                                     processingHints);
         return (obj != null) && ConfigurationUtils.isCollection(obj.toString());
     }
 
-    /**
-     * Is direct lookup boolean.
-     *
-     * @param hints the hints
-     * @return the boolean
-     */
-    public static boolean isDirectLookup(int hints) {
-        return (hints & LATEST_LOOKUP.value()) == LATEST_LOOKUP.value();
+    public static Object getProperty(Configuration config, String key, int processingHints) {
+        if (!isDirectLookup(processingHints)) {
+            if (config instanceof AgglomerateConfiguration) {
+                return ((AgglomerateConfiguration) config).getPropertyValue(key);
+            } else if (config instanceof CompositeConfiguration) {
+                CompositeConfiguration conf = (CompositeConfiguration) config;
+                for (int i = 0; i < conf.getNumberOfConfigurations(); i++) {
+                    if (conf.getConfiguration(i) instanceof AgglomerateConfiguration) {
+                        return ((AgglomerateConfiguration) conf.getConfiguration(i)).getPropertyValue(key);
+                    } else if (isNodeSpecific(processingHints)) {
+                        Object obj = conf.getConfiguration(i).getProperty(key);
+                        if (obj != null) {
+                            return obj;
+                        }
+                    }
+                }
+            }
+        }
+        return config.getProperty(key);
     }
 
-    /**
-     * Is external lookup boolean.
-     *
-     * @param hints the hints
-     * @return the boolean
-     */
-    public static boolean isExternalLookup(int hints) {
-        return (hints & EXTERNAL_LOOKUP.value()) == EXTERNAL_LOOKUP.value();
+    public static boolean isCollection(String input) {
+        Pattern pattern = Pattern.compile("^\\[(.*)\\]$");
+        Matcher matcher = pattern.matcher(input);
+        return matcher.matches();
+    }
+
+    public static boolean isDirectLookup(int hints) {
+        return (hints & LATEST_LOOKUP.value()) == LATEST_LOOKUP.value();
     }
 
-    /**
-     * Is node specific boolean.
-     *
-     * @param hints the hints
-     * @return the boolean
-     */
     public static boolean isNodeSpecific(int hints) {
         return (hints & NODE_SPECIFIC.value()) == NODE_SPECIFIC.value();
     }
 
+    public static boolean isExternalLookup(int hints) {
+        return (hints & EXTERNAL_LOOKUP.value()) == EXTERNAL_LOOKUP.value();
+    }
+
     public static boolean isZeroLengthArray(Class clazz, Object obj) {
         if (clazz.isArray() && clazz.getComponentType().isPrimitive()) {
             if (clazz.getComponentType() == int.class) {
@@ -1002,12 +721,6 @@ public class ConfigurationUtils {
         return false;
     }
 
-    /**
-     * Checks if value is blank
-     *
-     * @param value
-     * @return
-     */
     public static boolean isBlank(String value) {
         return value == null || value.trim().length() == 0;
     }
index 9f8e9e5..290a7a5 100644 (file)
@@ -1,3 +1,19 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config;
 
 public class Constants {
@@ -5,13 +21,14 @@ public class Constants {
     public static final String DEFAULT_TENANT = "GLOBAL";
     public static final String DEFAULT_NAMESPACE = "COMMON";
     public static final String DB_NAMESPACE = "SYSTEM";
-    public static final String KEY_ELEMENTS_DELEMETER = "-";
-    public static final String TENANT_NAMESPACE_SAPERATOR = ":";
+    public static final String KEY_ELEMENTS_DELIMETER = "-";
+    public static final String TENANT_NAMESPACE_SEPARATOR = ":";
     public static final String NAMESPACE_KEY = "_config.namespace";
     public static final String MODE_KEY = "_config.mergeStrategy";
     public static final String MBEAN_NAME = "org.openecomp.jmx:name=SystemConfig";
     public static final String LOAD_ORDER_KEY = "_config.loadOrder";
 
     private Constants() {
+        // prevent instantiation
     }
 }
index 830cdfe..e7128c7 100644 (file)
@@ -1,3 +1,19 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config;
 
 import java.io.File;
@@ -9,87 +25,68 @@ import java.util.HashSet;
 import java.util.Set;
 import java.util.function.Predicate;
 
-/**
- * The type Non config resource.
- */
 public class NonConfigResource {
 
-  private static Set<URL> urls = new HashSet<>();
-  private static Set<File> files = new HashSet<>();
+    private static final Set<URL> urls = new HashSet<>();
+    private static final Set<File> files = new HashSet<>();
 
-  /**
-   * Add.
-   *
-   * @param url the url
-   */
-  public static void add(URL url) {
-    urls.add(url);
-  }
-
-  /**
-   * Add.
-   *
-   * @param file the file
-   */
-  public static void add(File file) {
-    files.add(file);
-  }
+    public static void add(URL url) {
+        urls.add(url);
+    }
 
-  /**
-   * Locate path.
-   *
-   * @param resource the resource
-   * @return the path
-   */
-  public static Path locate(String resource) {
-    try {
-      if (resource != null) {
-        File file = new File(resource);
-        if (file.exists()) {
-          return Paths.get(resource);
-        }
-        for (File availableFile : files) {
-          if (availableFile.getAbsolutePath().endsWith(resource) && availableFile.exists()) {
-            return Paths.get(availableFile.getAbsolutePath());
-          }
+    public static Path locate(String resource) {
+        try {
+            if (resource != null) {
+                File file = new File(resource);
+                if (file.exists()) {
+                    return Paths.get(resource);
+                }
+                for (File availableFile : files) {
+                    if (availableFile.getAbsolutePath().endsWith(resource) && availableFile.exists()) {
+                        return Paths.get(availableFile.getAbsolutePath());
+                    }
+                }
+                if (System.getProperty("node.config.location") != null) {
+                    Path path = locate(new File(System.getProperty("node.config.location")), resource);
+                    if (path != null) {
+                        return path;
+                    }
+                }
+                if (System.getProperty("config.location") != null) {
+                    Path path = locate(new File(System.getProperty("config.location")), resource);
+                    if (path != null) {
+                        return path;
+                    }
+                }
+                for (URL url : urls) {
+                    if (url.getFile().endsWith(resource)) {
+                        return Paths.get(url.toURI());
+                    }
+                }
+            }
+        } catch (Exception exception) {
+            exception.printStackTrace();
         }
-        if (System.getProperty("node.config.location") != null) {
-          Path path = locate(new File(System.getProperty("node.config.location")), resource);
-          if (path != null) {
-            return path;
-          }
-        }
-        if (System.getProperty("config.location") != null) {
-          Path path = locate(new File(System.getProperty("config.location")), resource);
-          if (path != null) {
-            return path;
-          }
-        }
-        for (URL url : urls) {
-          if (url.getFile().endsWith(resource)) {
-            return Paths.get(url.toURI());
-          }
-        }
-      }
-    } catch (Exception exception) {
-      exception.printStackTrace();
+        return null;
     }
-    return null;
-  }
 
-  private static Path locate(File root, String resource) {
-    if (root.exists()) {
-      Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
-      Predicate<File> f1 = ConfigurationUtils::isConfig;
-      for (File file : filesystemResources) {
-        if (!f1.test(file)) {
-          add(file);
-          if (file.getAbsolutePath().endsWith(resource)) {
-            return Paths.get(file.getAbsolutePath());
-          }
+    private static Path locate(File root, String resource) {
+        if (root.exists()) {
+            Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
+            Predicate<File> f1 = ConfigurationUtils::isConfig;
+            for (File file : filesystemResources) {
+                if (!f1.test(file)) {
+                    add(file);
+                    if (file.getAbsolutePath().endsWith(resource)) {
+                        return Paths.get(file.getAbsolutePath());
+                    }
+                }
+            }
         }
-      }
+        return null;
+    }
+
+    public static void add(File file) {
+        files.add(file);
     }
-    return null;
-  }
 }
index 0934608..ed2511d 100644 (file)
@@ -1,33 +1,39 @@
-package org.onap.config.impl;
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 
-import org.apache.commons.configuration2.DatabaseConfiguration;
+package org.onap.config.impl;
 
 import java.util.Collections;
 import java.util.Map;
 import java.util.WeakHashMap;
+import org.apache.commons.configuration2.DatabaseConfiguration;
 
-/**
- * The type Agglomerate configuration.
- */
 public class AgglomerateConfiguration extends DatabaseConfiguration {
 
-  private final Map<String, Object> store =
-      Collections.synchronizedMap(new WeakHashMap<String, Object>());
-
-  /**
-   * Gets property value.
-   *
-   * @param key the key
-   * @return the property value
-   */
-  public Object getPropertyValue(String key) {
-    Object objToReturn;
-    objToReturn = store.get(key);
-    if (objToReturn == null && !store.containsKey(key)) {
-      objToReturn = super.getProperty(key);
-      store.put(key, objToReturn);
+    private final Map<String, Object> store = Collections.synchronizedMap(new WeakHashMap<>());
+
+    public Object getPropertyValue(String key) {
+
+        Object objToReturn = store.get(key);
+        if (objToReturn == null && !store.containsKey(key)) {
+            objToReturn = super.getProperty(key);
+            store.put(key, objToReturn);
+        }
+
+        return objToReturn;
     }
-    return objToReturn;
-  }
 
 }
index 7698d3f..80fbaf8 100644 (file)
@@ -1,5 +1,30 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.impl;
 
+import static org.onap.config.Constants.LOAD_ORDER_KEY;
+
+import java.io.File;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
 import org.apache.commons.configuration2.CombinedConfiguration;
 import org.apache.commons.configuration2.Configuration;
 import org.apache.commons.configuration2.tree.MergeCombiner;
@@ -8,166 +33,124 @@ import org.apache.commons.configuration2.tree.UnionCombiner;
 import org.onap.config.ConfigurationUtils;
 import org.onap.config.type.ConfigurationMode;
 
-import java.io.File;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.*;
-
-import static org.onap.config.Constants.LOAD_ORDER_KEY;
-
-/**
- * The type Aggregate configuration.
- */
 public final class AggregateConfiguration {
 
-  private Map<String, Configuration> rootConfig = new HashMap<>();
-  private Map<String, Configuration> unionConfig = new HashMap<>();
-  private Map<String, Configuration> mergeConfig = new HashMap<>();
-  private Map<String, Configuration> overrideConfig = new LinkedHashMap<>();
+    private final Map<String, Configuration> rootConfig = new HashMap<>();
+    private final Map<String, Configuration> unionConfig = new HashMap<>();
+    private final Map<String, Configuration> mergeConfig = new HashMap<>();
+    private final Map<String, Configuration> overrideConfig = new LinkedHashMap<>();
 
-  /**
-   * Instantiates a new Aggregate configuration.
-   */
-  public AggregateConfiguration() {
-    try {
-      Class clazz = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName());
-      if (!clazz.getCanonicalName()
-          .equals(ConfigurationImpl.class.getCanonicalName())) {
-        throw new RuntimeException("Illegal access.");
-      }
-    } catch (ClassNotFoundException cfe) {
-      throw new RuntimeException("Class not found while loading change notifier");
-    }
-  }
+    public AggregateConfiguration() {
 
-  private void addConfig(String path, ConfigurationMode configMode, Configuration config) {
-    if (configMode != null) {
-      switch (configMode) {
-        case MERGE:
-          mergeConfig.put(path, config);
-          break;
-        case OVERRIDE:
-          overrideConfig.put(path, config);
-          break;
-        case UNION:
-          unionConfig.put(path, config);
-          break;
-        default:
-      }
-    } else {
-      rootConfig.put(path, config);
+        try {
+            Class clazz = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName());
+            if (!clazz.getCanonicalName().equals(ConfigurationImpl.class.getCanonicalName())) {
+                throw new RuntimeException("Illegal access.");
+            }
+        } catch (ClassNotFoundException cfe) {
+            throw new RuntimeException("Class not found while loading change notifier");
+        }
     }
-  }
 
-  /**
-   * Add config.
-   *
-   * @param file the file
-   * @throws Exception the exception
-   */
-  public void addConfig(File file) throws Exception {
-    addConfig(file.getAbsolutePath().toUpperCase(), ConfigurationUtils.getMergeStrategy(file),
-        ConfigurationUtils.getConfigurationBuilder(file, false).getConfiguration());
-  }
-
-  /**
-   * Add config.
-   *
-   * @param url the url
-   * @throws Exception the exception
-   */
-  public void addConfig(URL url) throws Exception {
-    addConfig(url.getFile().toUpperCase(), ConfigurationUtils.getMergeStrategy(url),
-        ConfigurationUtils.getConfigurationBuilder(url).getConfiguration());
-  }
-
-  /**
-   * Remove config.
-   *
-   * @param file the file
-   */
-  public void removeConfig(File file) {
-    String key = file.getAbsolutePath().toUpperCase();
-    if (rootConfig.containsKey(key)) {
-      rootConfig.remove(key);
-    } else if (mergeConfig.containsKey(key)) {
-      mergeConfig.remove(key);
-    } else if (unionConfig.containsKey(key)) {
-      unionConfig.remove(key);
-    } else if (overrideConfig.containsKey(key)) {
-      overrideConfig.remove(key);
+    public void addConfig(File file) throws Exception {
+        addConfig(file.getAbsolutePath().toUpperCase(), ConfigurationUtils.getMergeStrategy(file),
+                ConfigurationUtils.getConfigurationBuilder(file, false).getConfiguration());
     }
-  }
-
-  /**
-   * Contains config boolean.
-   *
-   * @param file the file
-   * @return the boolean
-   */
-  public boolean containsConfig(File file) {
-    String key = file.getAbsolutePath().toUpperCase();
-    return rootConfig.containsKey(key) || mergeConfig.containsKey(key)
-        || unionConfig.containsKey(key) || overrideConfig.containsKey(key);
-  }
 
-  /**
-   * Gets final configuration.
-   *
-   * @return the final configuration
-   */
-  public Configuration getFinalConfiguration() {
-    CombinedConfiguration ccRoot = new CombinedConfiguration(new MergeCombiner());
-    ArrayList<Configuration> tempList = new ArrayList<>(rootConfig.values());
-    Collections.sort(tempList, this::sortForMerge);
-    for (Configuration conf : tempList) {
-      ccRoot.addConfiguration(conf);
+    private void addConfig(String path, ConfigurationMode configMode, Configuration config) {
+        if (configMode != null) {
+            switch (configMode) {
+                case MERGE:
+                    mergeConfig.put(path, config);
+                    break;
+                case OVERRIDE:
+                    overrideConfig.put(path, config);
+                    break;
+                case UNION:
+                    unionConfig.put(path, config);
+                    break;
+                default:
+            }
+        } else {
+            rootConfig.put(path, config);
+        }
     }
-    CombinedConfiguration ccMergeRoot = new CombinedConfiguration(new MergeCombiner());
-    ccMergeRoot.addConfiguration(ccRoot);
-    tempList = new ArrayList<>(mergeConfig.values());
-    Collections.sort(tempList, this::sortForMerge);
-    for (Configuration conf : tempList) {
-      ccMergeRoot.addConfiguration(conf);
-    }
-    CombinedConfiguration ccUnionRoot = new CombinedConfiguration(new UnionCombiner());
-    ccUnionRoot.addConfiguration(ccMergeRoot);
-    for (Configuration conf : unionConfig.values()) {
-      ccUnionRoot.addConfiguration(conf);
-    }
-    ArrayList<Configuration> tempOverrideConfigs = new ArrayList<>(overrideConfig.values());
-    Collections.reverse(tempOverrideConfigs);
-    Collections.sort(tempOverrideConfigs, this::sortForOverride);
-    CombinedConfiguration ccOverrideRoot = new CombinedConfiguration(new OverrideCombiner());
-    for (Configuration conf : tempOverrideConfigs) {
-      ccOverrideRoot.addConfiguration(conf);
+
+    public void addConfig(URL url) throws Exception {
+        addConfig(url.getFile().toUpperCase(), ConfigurationUtils.getMergeStrategy(url),
+                ConfigurationUtils.getConfigurationBuilder(url).getConfiguration());
     }
-    ccOverrideRoot.addConfiguration(ccUnionRoot);
-    return ccOverrideRoot;
-  }
 
-  private int sortForOverride(Configuration conf1, Configuration conf2){
-    String order1 = conf1.getString(LOAD_ORDER_KEY);
-    String order2 = conf2.getString(LOAD_ORDER_KEY);
-    if (ConfigurationUtils.isBlank(order1) || !order1.trim().matches("\\d+")){
-      order1 = "0";
+    public void removeConfig(File file) {
+        String key = file.getAbsolutePath().toUpperCase();
+        if (rootConfig.containsKey(key)) {
+            rootConfig.remove(key);
+        } else if (mergeConfig.containsKey(key)) {
+            mergeConfig.remove(key);
+        } else if (unionConfig.containsKey(key)) {
+            unionConfig.remove(key);
+        } else if (overrideConfig.containsKey(key)) {
+            overrideConfig.remove(key);
+        }
     }
-    if (ConfigurationUtils.isBlank(order2) || !order2.trim().matches("\\d+")){
-      order2 = "0";
+
+    public boolean containsConfig(File file) {
+        String key = file.getAbsolutePath().toUpperCase();
+        return rootConfig.containsKey(key) || mergeConfig.containsKey(key) || unionConfig.containsKey(key)
+                       || overrideConfig.containsKey(key);
     }
-    return Integer.parseInt(order2.trim())-Integer.parseInt(order1.trim());
-  }
 
-  private int sortForMerge(Configuration conf1, Configuration conf2){
-    String order1 = conf1.getString(LOAD_ORDER_KEY);
-    String order2 = conf2.getString(LOAD_ORDER_KEY);
-    if (ConfigurationUtils.isBlank(order1) || !order1.trim().matches("\\d+")){
-      order1 = "0";
+    public Configuration getFinalConfiguration() {
+        CombinedConfiguration ccRoot = new CombinedConfiguration(new MergeCombiner());
+        ArrayList<Configuration> tempList = new ArrayList<>(rootConfig.values());
+        tempList.sort(this::sortForMerge);
+        for (Configuration conf : tempList) {
+            ccRoot.addConfiguration(conf);
+        }
+        CombinedConfiguration ccMergeRoot = new CombinedConfiguration(new MergeCombiner());
+        ccMergeRoot.addConfiguration(ccRoot);
+        tempList = new ArrayList<>(mergeConfig.values());
+        tempList.sort(this::sortForMerge);
+        for (Configuration conf : tempList) {
+            ccMergeRoot.addConfiguration(conf);
+        }
+        CombinedConfiguration ccUnionRoot = new CombinedConfiguration(new UnionCombiner());
+        ccUnionRoot.addConfiguration(ccMergeRoot);
+        for (Configuration conf : unionConfig.values()) {
+            ccUnionRoot.addConfiguration(conf);
+        }
+        ArrayList<Configuration> tempOverrideConfigs = new ArrayList<>(overrideConfig.values());
+        Collections.reverse(tempOverrideConfigs);
+        tempOverrideConfigs.sort(this::sortForOverride);
+        CombinedConfiguration ccOverrideRoot = new CombinedConfiguration(new OverrideCombiner());
+        for (Configuration conf : tempOverrideConfigs) {
+            ccOverrideRoot.addConfiguration(conf);
+        }
+        ccOverrideRoot.addConfiguration(ccUnionRoot);
+        return ccOverrideRoot;
     }
-    if (ConfigurationUtils.isBlank(order2) || !order2.trim().matches("\\d+")){
-      order2 = "0";
+
+    private int sortForOverride(Configuration conf1, Configuration conf2) {
+        String order1 = conf1.getString(LOAD_ORDER_KEY);
+        String order2 = conf2.getString(LOAD_ORDER_KEY);
+        if (ConfigurationUtils.isBlank(order1) || !order1.trim().matches("\\d+")) {
+            order1 = "0";
+        }
+        if (ConfigurationUtils.isBlank(order2) || !order2.trim().matches("\\d+")) {
+            order2 = "0";
+        }
+        return Integer.parseInt(order2.trim()) - Integer.parseInt(order1.trim());
     }
-    return Integer.parseInt(order1.trim())-Integer.parseInt(order2.trim());
-  }
 
+    private int sortForMerge(Configuration conf1, Configuration conf2) {
+        String order1 = conf1.getString(LOAD_ORDER_KEY);
+        String order2 = conf2.getString(LOAD_ORDER_KEY);
+        if (ConfigurationUtils.isBlank(order1) || !order1.trim().matches("\\d+")) {
+            order1 = "0";
+        }
+        if (ConfigurationUtils.isBlank(order2) || !order2.trim().matches("\\d+")) {
+            order2 = "0";
+        }
+        return Integer.parseInt(order1.trim()) - Integer.parseInt(order2.trim());
+    }
 }
index ada40ce..7f753fd 100644 (file)
@@ -19,7 +19,7 @@ package org.onap.config.impl;
 import static org.onap.config.Constants.DB_NAMESPACE;
 import static org.onap.config.Constants.DEFAULT_NAMESPACE;
 import static org.onap.config.Constants.DEFAULT_TENANT;
-import static org.onap.config.Constants.KEY_ELEMENTS_DELEMETER;
+import static org.onap.config.Constants.KEY_ELEMENTS_DELIMETER;
 import static org.onap.config.Constants.LOAD_ORDER_KEY;
 import static org.onap.config.Constants.MBEAN_NAME;
 import static org.onap.config.Constants.MODE_KEY;
@@ -32,6 +32,7 @@ import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -55,16 +56,8 @@ import org.onap.config.api.Hint;
 import org.onap.config.type.ConfigurationQuery;
 import org.onap.config.type.ConfigurationUpdate;
 
-/**
- * The type Cli configuration.
- */
 public final class CliConfigurationImpl extends ConfigurationImpl implements ConfigurationManager {
 
-    /**
-     * Instantiates a new Cli configuration.
-     *
-     * @throws Exception the exception
-     */
     public CliConfigurationImpl() throws Exception {
         MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
         ObjectName name = new ObjectName(MBEAN_NAME);
@@ -73,26 +66,17 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
         }
         mbs.registerMBean(new StandardMBean(this, ConfigurationManager.class), name);
         mbs.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME,
-                (notification, handback) -> handleNotification(notification), null,
-                null);
+                (notification, handback) -> handleNotification(notification), null, null);
     }
 
-
-    /**
-     * Handle notification.
-     *
-     * @param notification the notification
-     */
     public void handleNotification(Notification notification) {
         if (notification instanceof MBeanServerNotification) {
             MBeanServerNotification mbs = (MBeanServerNotification) notification;
             if (MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(mbs.getType())) {
                 try {
-                    String mbean =
-                            ConfigurationRepository.lookup().getConfigurationFor(DEFAULT_TENANT, DB_NAMESPACE)
-                                    .getString("shutdown.mbean");
-                    if (mbs.getMBeanName()
-                                .equals(mbean == null ? new ObjectName(MBEAN_NAME) : new ObjectName(mbean))) {
+                    String mbean = ConfigurationRepository.lookup().getConfigurationFor(DEFAULT_TENANT, DB_NAMESPACE)
+                                           .getString("shutdown.mbean");
+                    if (mbs.getMBeanName().equals(mbean == null ? new ObjectName(MBEAN_NAME) : new ObjectName(mbean))) {
                         changeNotifier.shutdown();
                     }
                 } catch (Exception exception) {
@@ -118,12 +102,12 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
                                 queryData.isNodeSpecific() ? Hint.NODE_SPECIFIC : Hint.DEFAULT));
             } else {
                 String[] list =
-                        getInternal(queryData.getTenant(), queryData.getNamespace(), queryData.getKey(),
-                                String[].class, queryData.isLatest() ? Hint.LATEST_LOOKUP : Hint.DEFAULT,
+                        getInternal(queryData.getTenant(), queryData.getNamespace(), queryData.getKey(), String[].class,
+                                queryData.isLatest() ? Hint.LATEST_LOOKUP : Hint.DEFAULT,
                                 queryData.isExternalLookup() ? Hint.EXTERNAL_LOOKUP : Hint.DEFAULT,
                                 queryData.isNodeSpecific() ? Hint.NODE_SPECIFIC : Hint.DEFAULT);
                 return ConfigurationUtils
-                               .getCommaSeparatedList(list == null ? Arrays.asList() : Arrays.asList(list));
+                               .getCommaSeparatedList(list == null ? Collections.emptyList() : Arrays.asList(list));
             }
         } catch (Exception exception) {
             exception.printStackTrace();
@@ -131,6 +115,23 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
         return null;
     }
 
+    private Object getInput(Map<String, Object> input) {
+        Object toReturn = null;
+        try {
+            toReturn = Class.forName(input.get("ImplClass").toString()).newInstance();
+            Method[] methods = toReturn.getClass().getMethods();
+            for (Method method : methods) {
+                if (input.containsKey(method.getName())) {
+                    method.invoke(toReturn, input.get(method.getName()));
+                }
+            }
+        } catch (Exception exception) {
+            exception.printStackTrace();
+        }
+
+        return toReturn;
+    }
+
     public void updateConfigurationValue(Map<String, Object> input) {
         updateConfigurationValue((ConfigurationUpdate) getInput(input));
     }
@@ -149,14 +150,13 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
         }
 
         try {
-            boolean keyPresent =
-                    isKeyExists(updateData.getTenant(), updateData.getNamespace(), updateData.getKey());
+            boolean keyPresent = isKeyExists(updateData.getTenant(), updateData.getNamespace(), updateData.getKey());
             if (keyPresent) {
                 boolean isUpdated = false;
-                Object[] paramArray = new Object[]{
-                        updateData.getTenant() + KEY_ELEMENTS_DELEMETER + updateData.getNamespace(),
-                        new Long(System.currentTimeMillis()), updateData.getKey(),
-                        getConfigurationValue(updateData), updateData.getValue()};
+                Object[] paramArray =
+                        new Object[] {updateData.getTenant() + KEY_ELEMENTS_DELIMETER + updateData.getNamespace(),
+                                System.currentTimeMillis(), updateData.getKey(), getConfigurationValue(updateData),
+                                updateData.getValue()};
                 Configuration config = ConfigurationRepository.lookup()
                                                .getConfigurationFor(updateData.getTenant(), updateData.getNamespace());
                 if (config instanceof AgglomerateConfiguration || config instanceof CombinedConfiguration) {
@@ -167,17 +167,15 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
                 CompositeConfiguration configuration = (CompositeConfiguration) config;
                 int overrideIndex = -1;
                 for (int i = 0; i < configuration.getNumberOfConfigurations(); i++) {
-                    if (!updateData.isNodeOverride()
-                                && (configuration.getConfiguration(i) instanceof AgglomerateConfiguration
-                                            || configuration.getConfiguration(i) instanceof CombinedConfiguration)) {
-                        configuration.getConfiguration(i)
-                                .setProperty(updateData.getKey(), updateData.getValue());
+                    if (!updateData.isNodeOverride() && (
+                            configuration.getConfiguration(i) instanceof AgglomerateConfiguration
+                                    || configuration.getConfiguration(i) instanceof CombinedConfiguration)) {
+                        configuration.getConfiguration(i).setProperty(updateData.getKey(), updateData.getValue());
                         isUpdated = true;
                         break;
-                    } else if (updateData.isNodeOverride()
-                                       && configuration.getConfiguration(i) instanceof FileBasedConfiguration) {
-                        configuration.getConfiguration(i)
-                                .setProperty(updateData.getKey(), updateData.getValue());
+                    } else if (updateData.isNodeOverride() && configuration.getConfiguration(
+                            i) instanceof FileBasedConfiguration) {
+                        configuration.getConfiguration(i).setProperty(updateData.getKey(), updateData.getValue());
                         isUpdated = true;
                         overrideIndex = i;
                         break;
@@ -187,32 +185,29 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
                     if (updateData.isNodeOverride()) {
                         PropertiesConfiguration pc = new PropertiesConfiguration();
                         pc.setProperty(NAMESPACE_KEY,
-                                updateData.getTenant() + Constants.TENANT_NAMESPACE_SAPERATOR
+                                updateData.getTenant() + Constants.TENANT_NAMESPACE_SEPARATOR
                                         + updateData.getNamespace());
                         pc.setProperty(MODE_KEY, "OVERRIDE");
                         pc.setProperty(updateData.getKey(), updateData.getValue());
                         String nodeConfigLocation = System.getProperty("node.config.location");
                         if (nodeConfigLocation != null && nodeConfigLocation.trim().length() > 0) {
                             File file = new File(nodeConfigLocation,
-                                    updateData.getTenant() + File.separator + updateData.getNamespace()
-                                            + File.separator + "config.properties");
+                                    updateData.getTenant() + File.separator + updateData.getNamespace() + File.separator
+                                            + "config.properties");
                             file.getParentFile().mkdirs();
                             PrintWriter out = new PrintWriter(file);
                             pc.write(out);
                             out.close();
-                            ConfigurationRepository.lookup().populateOverrideConfigurtaion(
-                                    updateData.getTenant() + KEY_ELEMENTS_DELEMETER + updateData.getNamespace(),
-                                    file);
+                            ConfigurationRepository.lookup().populateOverrideConfiguration(
+                                    updateData.getTenant() + KEY_ELEMENTS_DELIMETER + updateData.getNamespace(), file);
                         }
                     } else {
-                        configuration.getConfiguration(0)
-                                .setProperty(updateData.getKey(), updateData.getValue());
+                        configuration.getConfiguration(0).setProperty(updateData.getKey(), updateData.getValue());
                     }
                 }
                 if (updateData.isNodeOverride()) {
-                    ConfigurationRepository.lookup().refreshOverrideConfigurtaionFor(
-                            updateData.getTenant() + KEY_ELEMENTS_DELEMETER + updateData.getNamespace(),
-                            overrideIndex);
+                    ConfigurationRepository.lookup().refreshOverrideConfigurationFor(
+                            updateData.getTenant() + KEY_ELEMENTS_DELIMETER + updateData.getNamespace(), overrideIndex);
                 }
             }
         } catch (Exception exception) {
@@ -223,8 +218,7 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
     private boolean isKeyExists(String tenant, String namespace, String key) {
         boolean keyExist = false;
         try {
-            keyExist =
-                    ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace).containsKey(key);
+            keyExist = ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace).containsKey(key);
             if (!keyExist && !DEFAULT_TENANT.equals(tenant)) {
                 keyExist = ConfigurationRepository.lookup().getConfigurationFor(DEFAULT_TENANT, namespace)
                                    .containsKey(key);
@@ -234,9 +228,8 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
                                    .containsKey(key);
             }
             if (!keyExist && !DEFAULT_TENANT.equals(tenant) && !DEFAULT_NAMESPACE.equals(namespace)) {
-                keyExist =
-                        ConfigurationRepository.lookup().getConfigurationFor(DEFAULT_TENANT, DEFAULT_NAMESPACE)
-                                .containsKey(key);
+                keyExist = ConfigurationRepository.lookup().getConfigurationFor(DEFAULT_TENANT, DEFAULT_NAMESPACE)
+                                   .containsKey(key);
             }
         } catch (Exception exception) {
             exception.printStackTrace();
@@ -262,14 +255,30 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
         return map;
     }
 
+    private ArrayList<String> getInMemoryKeys(String tenant, String namespace) {
+        ArrayList<String> keys = new ArrayList<>();
+
+        try {
+            Iterator<String> iter = ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace).getKeys();
+            while (iter.hasNext()) {
+                String key = iter.next();
+                if (!(key.equals(NAMESPACE_KEY) || key.equals(MODE_KEY) || key.equals(LOAD_ORDER_KEY))) {
+                    keys.add(key);
+                }
+            }
+        } catch (Exception exception) {
+            //do nothing
+        }
+
+        return keys;
+    }
+
     @Override
-    public boolean updateConfigurationValues(String tenant, String namespace,
-            Map configKeyValueStore) {
+    public boolean updateConfigurationValues(String tenant, String namespace, Map configKeyValueStore) {
         boolean valueToReturn = true;
-        Iterator<String> keys = configKeyValueStore.keySet().iterator();
-        while (keys.hasNext()) {
+        for (String s : (Iterable<String>) configKeyValueStore.keySet()) {
             try {
-                String key = keys.next();
+                String key = s;
                 ConfigurationUpdate updateData = new ConfigurationUpdate();
                 updateData.tenant(tenant).namespace(namespace).key(key);
                 updateData.value(configKeyValueStore.get(key).toString());
@@ -282,23 +291,6 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
         return valueToReturn;
     }
 
-    private Object getInput(Map<String, Object> input) {
-        Object toReturn = null;
-        try {
-            toReturn = Class.forName(input.get("ImplClass").toString()).newInstance();
-            Method[] methods = toReturn.getClass().getMethods();
-            for (Method method : methods) {
-                if (input.containsKey(method.getName())) {
-                    method.invoke(toReturn, input.get(method.getName()));
-                }
-            }
-        } catch (Exception exception) {
-            exception.printStackTrace();
-        }
-
-        return toReturn;
-    }
-
     @Override
     public Collection<String> getTenants() {
         return ConfigurationRepository.lookup().getTenants();
@@ -309,26 +301,6 @@ public final class CliConfigurationImpl extends ConfigurationImpl implements Con
         return ConfigurationRepository.lookup().getNamespaces();
     }
 
-    private ArrayList<String> getInMemoryKeys(String tenant, String namespace) {
-        ArrayList<String> keys = new ArrayList<>();
-
-        try {
-            Iterator<String> iter =
-                    ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace).getKeys();
-            while (iter.hasNext()) {
-                String key = iter.next();
-                if (!(key.equals(NAMESPACE_KEY) || key.equals(MODE_KEY)
-                              || key.equals(LOAD_ORDER_KEY))) {
-                    keys.add(key);
-                }
-            }
-        } catch (Exception exception) {
-            //do nothing
-        }
-
-        return keys;
-    }
-
     @Override
     public Collection<String> getKeys(String tenant, String namespace) {
         Set<String> keyCollection = new HashSet<>();
index 88c71c1..cd6481f 100644 (file)
@@ -1,11 +1,21 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.impl;
 
-import org.onap.config.ConfigurationUtils;
-import org.onap.config.Constants;
-import org.onap.config.api.ConfigurationChangeListener;
-import org.onap.config.api.ConfigurationManager;
-import org.onap.config.api.Hint;
 import java.io.File;
 import java.io.IOException;
 import java.lang.management.ManagementFactory;
@@ -35,441 +45,349 @@ import java.util.concurrent.TimeUnit;
 import javax.management.JMX;
 import javax.management.MBeanServerConnection;
 import javax.management.ObjectName;
+import org.onap.config.ConfigurationUtils;
+import org.onap.config.Constants;
+import org.onap.config.api.ConfigurationChangeListener;
+import org.onap.config.api.ConfigurationManager;
+import org.onap.config.api.Hint;
 
 
-
-/**
- * The type Configuration change notifier.
- */
 public final class ConfigurationChangeNotifier {
 
-  private final HashMap<String, List<NotificationData>> store = new HashMap<>();
-  private final ScheduledExecutorService executor =
-      Executors.newScheduledThreadPool(5, ConfigurationUtils.getThreadFactory());
-  private final ExecutorService notificationExecutor =
-      Executors.newCachedThreadPool(ConfigurationUtils.getThreadFactory());
-  private final Map<String, WatchService> watchServiceCollection =
-      Collections.synchronizedMap(new HashMap<>());
-
-  static {
-    if (!Thread.currentThread().getStackTrace()[2].getClassName()
-        .equals(ConfigurationImpl.class.getName())) {
-      throw new RuntimeException("Illegal access.");
+    static {
+        if (!Thread.currentThread().getStackTrace()[2].getClassName().equals(ConfigurationImpl.class.getName())) {
+            throw new RuntimeException("Illegal access.");
+        }
     }
-  }
 
-  /**
-   * Instantiates a new Configuration change notifier.
-   *
-   * @param inMemoryConfig the in memory config
-   */
-  public ConfigurationChangeNotifier(Map<String, AggregateConfiguration> inMemoryConfig) {
-    executor.scheduleWithFixedDelay(() -> this
-        .pollFilesystemAndUpdateConfigurationIfRequired(inMemoryConfig,
-            System.getProperty("config.location"), false), 1, 1, TimeUnit.MILLISECONDS);
-    executor.scheduleWithFixedDelay(() -> this
-        .pollFilesystemAndUpdateConfigurationIfRequired(inMemoryConfig,
-            System.getProperty("tenant.config.location"), true), 1, 1, TimeUnit.MILLISECONDS);
-    executor.scheduleWithFixedDelay(() -> this
-        .pollFilesystemAndUpdateNodeSpecificConfigurationIfRequired(
-            System.getProperty("node.config.location")), 1, 1, TimeUnit.MILLISECONDS);
-  }
+    private final HashMap<String, List<NotificationData>> store = new HashMap<>();
+    private final ScheduledExecutorService executor =
+            Executors.newScheduledThreadPool(5, ConfigurationUtils.getThreadFactory());
+    private final ExecutorService notificationExecutor =
+            Executors.newCachedThreadPool(ConfigurationUtils.getThreadFactory());
+    private final Map<String, WatchService> watchServiceCollection = Collections.synchronizedMap(new HashMap<>());
 
-  /**
-   * Shutdown.
-   */
-  public void shutdown() {
-    for (WatchService watch : watchServiceCollection.values()) {
-      try {
-        watch.close();
-      } catch (IOException exception) {
-        //do nothing
-      }
+    public ConfigurationChangeNotifier(Map<String, AggregateConfiguration> inMemoryConfig) {
+        executor.scheduleWithFixedDelay(() -> this.pollFilesystemAndUpdateConfigurationIfRequired(inMemoryConfig,
+                System.getProperty("config.location"), false), 1, 1, TimeUnit.MILLISECONDS);
+        executor.scheduleWithFixedDelay(() -> this.pollFilesystemAndUpdateConfigurationIfRequired(inMemoryConfig,
+                System.getProperty("tenant.config.location"), true), 1, 1, TimeUnit.MILLISECONDS);
+        executor.scheduleWithFixedDelay(() -> this.pollFilesystemAndUpdateNodeSpecificConfigurationIfRequired(
+                System.getProperty("node.config.location")), 1, 1, TimeUnit.MILLISECONDS);
     }
-    executor.shutdownNow();
-  }
 
-  /**
-   * Poll filesystem and update configuration if required.
-   *
-   * @param inMemoryConfig   the in memory config
-   * @param location         the location
-   * @param isTenantLocation the is tenant location
-   */
-  public void pollFilesystemAndUpdateConfigurationIfRequired(
-      Map<String, AggregateConfiguration> inMemoryConfig, String location,
-      boolean isTenantLocation) {
-    try {
-      Set<Path> paths = watchForChange(location);
-      if (paths != null) {
-        for (Path path : paths) {
-          File file = path.toAbsolutePath().toFile();
-          String repositoryKey = null;
-          if (ConfigurationUtils.isConfig(file) && file.isFile()) {
-            if (isTenantLocation) {
-              Collection<File> tenantsRoot =
-                  ConfigurationUtils.getAllFiles(new File(location), false, true);
-              for (File tenantRoot : tenantsRoot) {
-                if (file.getAbsolutePath().startsWith(tenantRoot.getAbsolutePath())) {
-                  repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(
-                      (tenantRoot.getName() + Constants.TENANT_NAMESPACE_SAPERATOR
-                          + ConfigurationUtils.getNamespace(file))
-                          .split(Constants.TENANT_NAMESPACE_SAPERATOR));
+    public void pollFilesystemAndUpdateConfigurationIfRequired(Map<String, AggregateConfiguration> inMemoryConfig,
+            String location, boolean isTenantLocation) {
+        try {
+            Set<Path> paths = watchForChange(location);
+            if (paths != null) {
+                for (Path path : paths) {
+                    File file = path.toAbsolutePath().toFile();
+                    String repositoryKey = null;
+                    if (ConfigurationUtils.isConfig(file) && file.isFile()) {
+                        if (isTenantLocation) {
+                            Collection<File> tenantsRoot =
+                                    ConfigurationUtils.getAllFiles(new File(location), false, true);
+                            for (File tenantRoot : tenantsRoot) {
+                                if (file.getAbsolutePath().startsWith(tenantRoot.getAbsolutePath())) {
+                                    repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(
+                                            (tenantRoot.getName() + Constants.TENANT_NAMESPACE_SEPARATOR
+                                                     + ConfigurationUtils.getNamespace(file))
+                                                    .split(Constants.TENANT_NAMESPACE_SEPARATOR));
+                                }
+                            }
+                        } else {
+                            repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(file);
+                        }
+                        AggregateConfiguration config = inMemoryConfig.get(repositoryKey);
+                        if (config != null) {
+                            LinkedHashMap origConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
+                            config.addConfig(file);
+                            LinkedHashMap latestConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
+                            Map map = ConfigurationUtils.diff(origConfig, latestConfig);
+                            String[] tenantNamespaceArray = repositoryKey.split(Constants.KEY_ELEMENTS_DELIMETER);
+                            updateConfigurationValues(tenantNamespaceArray[0], tenantNamespaceArray[1], map);
+                        }
+                    } else {
+                        for (String configKey : inMemoryConfig.keySet()) {
+                            repositoryKey = configKey;
+                            AggregateConfiguration config = inMemoryConfig.get(repositoryKey);
+                            if (config.containsConfig(file)) {
+                                LinkedHashMap origConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
+                                config.removeConfig(file);
+                                LinkedHashMap latestConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
+                                Map map = ConfigurationUtils.diff(origConfig, latestConfig);
+                                String[] tenantNamespaceArray = repositoryKey.split(Constants.KEY_ELEMENTS_DELIMETER);
+                                updateConfigurationValues(tenantNamespaceArray[0], tenantNamespaceArray[1], map);
+                            }
+                        }
+                    }
                 }
-              }
-            } else {
-              repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(file);
             }
-            AggregateConfiguration config = inMemoryConfig.get(repositoryKey);
-            if (config != null) {
-              LinkedHashMap origConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
-              config.addConfig(file);
-              LinkedHashMap latestConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
-              Map map = ConfigurationUtils.diff(origConfig, latestConfig);
-              String[] tenantNamespaceArray =
-                  repositoryKey.split(Constants.KEY_ELEMENTS_DELEMETER);
-              updateConfigurationValues(tenantNamespaceArray[0], tenantNamespaceArray[1], map);
-            }
-          } else {
-            for (String configKey : inMemoryConfig.keySet()) {
-              repositoryKey = configKey;
-              AggregateConfiguration config = inMemoryConfig.get(repositoryKey);
-              if (config.containsConfig(file)) {
-                LinkedHashMap origConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
-                config.removeConfig(file);
-                LinkedHashMap latestConfig =
-                        ConfigurationUtils.toMap(config.getFinalConfiguration());
-                Map map = ConfigurationUtils.diff(origConfig, latestConfig);
-                String[] tenantNamespaceArray =
-                        repositoryKey.split(Constants.KEY_ELEMENTS_DELEMETER);
-                updateConfigurationValues(tenantNamespaceArray[0], tenantNamespaceArray[1],
-                        map);
-              }
-            }
-          }
+        } catch (ClosedWatchServiceException exception) {
+            // do nothing.
+        } catch (Exception exception) {
+            exception.printStackTrace();
         }
-      }
-    } catch (ClosedWatchServiceException exception) {
-      // do nothing.
-    } catch (Exception exception) {
-      exception.printStackTrace();
     }
-  }
-
-  private void updateConfigurationValues(String tenant, String namespace, Map map)
-      throws Exception {
-    MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
-    ObjectName mbeanName = new ObjectName(Constants.MBEAN_NAME);
-    ConfigurationManager conf =
-        JMX.newMBeanProxy(mbsc, mbeanName, ConfigurationManager.class,
-            true);
-    conf.updateConfigurationValues(tenant, namespace, map);
-  }
 
-  /**
-   * Poll filesystem and update node specific configuration if required.
-   *
-   * @param location the location
-   */
-  public void pollFilesystemAndUpdateNodeSpecificConfigurationIfRequired(String location) {
-    try {
-      Set<Path> paths = watchForChange(location);
-      if (paths != null) {
-        for (Path path : paths) {
-          File file = path.toAbsolutePath().toFile();
+    public void pollFilesystemAndUpdateNodeSpecificConfigurationIfRequired(String location) {
+        try {
+            Set<Path> paths = watchForChange(location);
+            if (paths != null) {
+                for (Path path : paths) {
+                    File file = path.toAbsolutePath().toFile();
 
-          if (ConfigurationUtils.isConfig(file)) {
-            String repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(file);
-            ConfigurationRepository.lookup().populateOverrideConfigurtaion(repositoryKey, file);
-          } else {
-            ConfigurationRepository.lookup().removeOverrideConfigurtaion(file);
-          }
+                    if (ConfigurationUtils.isConfig(file)) {
+                        String repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(file);
+                        ConfigurationRepository.lookup().populateOverrideConfiguration(repositoryKey, file);
+                    } else {
+                        ConfigurationRepository.lookup().removeOverrideConfiguration(file);
+                    }
+                }
+            }
+        } catch (Exception exception) {
+            exception.printStackTrace();
         }
-      }
-    } catch (Exception exception) {
-      exception.printStackTrace();
     }
-  }
 
-  /**
-   * Notify changes towards.
-   *
-   * @param tenant    the tenant
-   * @param component the component
-   * @param key       the key
-   * @param myself    the myself
-   * @throws Exception the exception
-   */
-  public void notifyChangesTowards(String tenant, String component, String key,
-                                   ConfigurationChangeListener myself) throws Exception {
-    List<NotificationData> notificationList =
-        store.get(tenant + Constants.KEY_ELEMENTS_DELEMETER + component);
-    if (notificationList == null) {
-      notificationList = Collections.synchronizedList(new ArrayList<>());
-      store.put(tenant + Constants.KEY_ELEMENTS_DELEMETER + component, notificationList);
-      executor.scheduleWithFixedDelay(
-          () -> triggerScanning(tenant + Constants.KEY_ELEMENTS_DELEMETER + component), 1, 30000,
-          TimeUnit.MILLISECONDS);
+    private Set<Path> watchForChange(String location) throws Exception {
+        if (location == null || location.trim().length() == 0) {
+            return Collections.emptySet();
+        }
+        File file = new File(location);
+        if (!file.exists()) {
+            return Collections.emptySet();
+        }
+        Path path = file.toPath();
+        Set<Path> toReturn = new HashSet<>();
+        try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
+            watchServiceCollection.put(location, watchService);
+            path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE,
+                    StandardWatchEventKinds.ENTRY_DELETE);
+            for (File dir : ConfigurationUtils.getAllFiles(file, true, true)) {
+                dir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
+                        StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
+            }
+            while (true) {
+                final WatchKey wk = watchService.take();
+                Thread.sleep(ConfigurationRepository.lookup()
+                                     .getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
+                                     .getLong("event.fetch.delay"));
+                for (WatchEvent<?> event : wk.pollEvents()) {
+                    Object context = event.context();
+                    if (context instanceof Path) {
+                        File newFile = new File(((Path) wk.watchable()).toFile(), context.toString());
+                        if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
+                            if (newFile.isDirectory()) {
+                                newFile.toPath().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
+                                        StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
+                                continue;
+                            }
+                        } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
+                            if (newFile.isDirectory()) {
+                                continue;
+                            }
+                        }
+                        toReturn.add(newFile.toPath());
+                    }
+                }
+                if (toReturn.isEmpty()) {
+                    continue;
+                }
+                break;
+            }
+        }
+        return toReturn;
     }
-    notificationList.add(new NotificationData(tenant, component, key, myself));
-  }
 
-  /**
-   * Stop notification towards.
-   *
-   * @param tenant    the tenant
-   * @param component the component
-   * @param key       the key
-   * @param myself    the myself
-   * @throws Exception the exception
-   */
-  public void stopNotificationTowards(String tenant, String component, String key,
-                                      ConfigurationChangeListener myself) throws Exception {
-    List<NotificationData> notificationList =
-        store.get(tenant + Constants.KEY_ELEMENTS_DELEMETER + component);
-    if (notificationList != null) {
-      boolean removed =
-          notificationList.remove(new NotificationData(tenant, component, key, myself));
-      if (removed && notificationList.isEmpty()) {
-        store.remove(tenant + Constants.KEY_ELEMENTS_DELEMETER + component);
-      }
+    private void updateConfigurationValues(String tenant, String namespace, Map map) throws Exception {
+        MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
+        ObjectName mbeanName = new ObjectName(Constants.MBEAN_NAME);
+        ConfigurationManager conf = JMX.newMBeanProxy(mbsc, mbeanName, ConfigurationManager.class, true);
+        conf.updateConfigurationValues(tenant, namespace, map);
     }
 
-  }
-
-  private void triggerScanning(String key) {
-    if (store.get(key) != null) {
-      notificationExecutor.submit(() -> scanForChanges(key));
-    } else {
-      throw new IllegalArgumentException("Notification service for " + key + " is suspended.");
+    public void shutdown() {
+        for (WatchService watch : watchServiceCollection.values()) {
+            try {
+                watch.close();
+            } catch (IOException exception) {
+                //do nothing
+            }
+        }
+        executor.shutdownNow();
     }
-  }
 
-  private void scanForChanges(String key) {
-    List<NotificationData> list = store.get(key);
-    if (list != null) {
-      list.stream()
-              .filter(NotificationData::isChanged)
-              .forEach(notificationData -> notificationExecutor.submit(() -> sendNotification(notificationData)));
+    public void notifyChangesTowards(String tenant, String component, String key, ConfigurationChangeListener myself)
+            throws Exception {
+        List<NotificationData> notificationList = store.get(tenant + Constants.KEY_ELEMENTS_DELIMETER + component);
+        if (notificationList == null) {
+            notificationList = Collections.synchronizedList(new ArrayList<>());
+            store.put(tenant + Constants.KEY_ELEMENTS_DELIMETER + component, notificationList);
+            executor.scheduleWithFixedDelay(
+                    () -> triggerScanning(tenant + Constants.KEY_ELEMENTS_DELIMETER + component), 1, 30000,
+                    TimeUnit.MILLISECONDS);
+        }
+        notificationList.add(new NotificationData(tenant, component, key, myself));
     }
-  }
 
-  private void sendNotification(NotificationData notificationData) {
-    try {
-      notificationData.dispatchNotification();
-    } catch (Exception exception) {
-      exception.printStackTrace();
+    private void triggerScanning(String key) {
+        if (store.get(key) != null) {
+            notificationExecutor.submit(() -> scanForChanges(key));
+        } else {
+            throw new IllegalArgumentException("Notification service for " + key + " is suspended.");
+        }
     }
-  }
 
-  private Set<Path> watchForChange(String location) throws Exception {
-    if (location == null || location.trim().length() == 0) {
-      return Collections.emptySet();
+    private void scanForChanges(String key) {
+        List<NotificationData> list = store.get(key);
+        if (list != null) {
+            list.stream().filter(NotificationData::isChanged)
+                    .forEach(notificationData -> notificationExecutor.submit(() -> sendNotification(notificationData)));
+        }
     }
-    File file = new File(location);
-    if (!file.exists()) {
-      return Collections.emptySet();
+
+    private void sendNotification(NotificationData notificationData) {
+        try {
+            notificationData.dispatchNotification();
+        } catch (Exception exception) {
+            exception.printStackTrace();
+        }
     }
-    Path path = file.toPath();
-    Set<Path> toReturn = new HashSet<>();
-    try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
-      watchServiceCollection.put(location, watchService);
-      path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
-          StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
-      for (File dir : ConfigurationUtils.getAllFiles(file, true, true)) {
-        dir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
-            StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
-      }
-      while (true) {
-        final WatchKey wk = watchService.take();
-        Thread.sleep(ConfigurationRepository.lookup()
-            .getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
-            .getLong("event.fetch.delay"));
-        for (WatchEvent<?> event : wk.pollEvents()) {
-          Object context = event.context();
-          if (context instanceof Path) {
-            File newFile = new File(((Path) wk.watchable()).toFile(), context.toString());
-            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
-              if (newFile.isDirectory()) {
-                newFile.toPath().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
-                    StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
-                continue;
-              }
-            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
-              if (newFile.isDirectory()) {
-                continue;
-              }
+
+    public void stopNotificationTowards(String tenant, String component, String key, ConfigurationChangeListener myself)
+            throws Exception {
+        List<NotificationData> notificationList = store.get(tenant + Constants.KEY_ELEMENTS_DELIMETER + component);
+        if (notificationList != null) {
+            boolean removed = notificationList.remove(new NotificationData(tenant, component, key, myself));
+            if (removed && notificationList.isEmpty()) {
+                store.remove(tenant + Constants.KEY_ELEMENTS_DELIMETER + component);
             }
-            toReturn.add(newFile.toPath());
-          }
         }
-        if (toReturn.isEmpty()) {
-          continue;
-        }
-        break;
-      }
+
     }
-    return toReturn;
-  }
 
-  /**
-   * The type Notification data.
-   */
-  static class NotificationData {
+    static class NotificationData {
 
-    /**
-     * The Tenant.
-     */
-    final String tenant;
-    /**
-     * The Namespace.
-     */
-    final String namespace;
-    /**
-     * The Key.
-     */
-    final String key;
-    /**
-     * The Myself.
-     */
-    final ConfigurationChangeListener myself;
-    /**
-     * The Current value.
-     */
-    Object currentValue;
-    /**
-     * The Is array.
-     */
-    boolean isArray;
+        final String tenant;
 
-    /**
-     * Instantiates a new Notification data.
-     *
-     * @param tenant    the tenant
-     * @param component the component
-     * @param key       the key
-     * @param myself    the myself
-     * @throws Exception the exception
-     */
-    public NotificationData(String tenant, String component, String key,
-                            ConfigurationChangeListener myself) throws Exception {
-      this.tenant = tenant;
-      this.namespace = component;
-      this.key = key;
-      this.myself = myself;
-      if (!ConfigurationRepository.lookup().getConfigurationFor(tenant, component)
-          .containsKey(key)) {
-        throw new RuntimeException("Key[" + key + "] not found.");
-      }
-      isArray = ConfigurationUtils.isArray(tenant, component, key, Hint.DEFAULT.value());
-      if (isArray) {
-        currentValue = ConfigurationManager.lookup().getAsStringValues(tenant, component, key);
-      } else {
-        currentValue = ConfigurationManager.lookup().getAsString(tenant, component, key);
-      }
-    }
+        final String namespace;
 
-    @Override
-    public boolean equals(Object obj) {
-      if (!(obj instanceof NotificationData)) {
-        return false;
-      }
-      NotificationData nd = (NotificationData) obj;
-      return Objects.equals(tenant, nd.tenant)
-              && Objects.equals(namespace, nd.namespace)
-              && Objects.equals(key, nd.key)
-              && Objects.equals(myself, nd.myself)
-              && Objects.equals(currentValue, nd.currentValue) // it's either String or List<String>
-              && isArray == nd.isArray;
-    }
+        final String key;
 
-    @Override
-    public int hashCode() {
-      return Objects.hash(tenant, namespace, key, myself, currentValue, isArray);
-    }
+        final ConfigurationChangeListener myself;
 
-    /**
-     * Is changed boolean.
-     *
-     * @return the boolean
-     */
-    public boolean isChanged() {
-      Object latestValue;
-      try {
-        if (isArray) {
-          latestValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
-        } else {
-          latestValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
-        }
-        if (!isArray) {
-          return !currentValue.equals(latestValue);
-        } else {
-          Collection<String> oldCollection = (Collection<String>) currentValue;
-          Collection<String> newCollection = (Collection<String>) latestValue;
-          for (String val : oldCollection) {
-            if (!newCollection.remove(val)) {
-              return true;
+        Object currentValue;
+
+        boolean isArray;
+
+        public NotificationData(String tenant, String component, String key, ConfigurationChangeListener myself)
+                throws Exception {
+            this.tenant = tenant;
+            this.namespace = component;
+            this.key = key;
+            this.myself = myself;
+            if (!ConfigurationRepository.lookup().getConfigurationFor(tenant, component).containsKey(key)) {
+                throw new RuntimeException("Key[" + key + "] not found.");
+            }
+            isArray = ConfigurationUtils.isArray(tenant, component, key, Hint.DEFAULT.value());
+            if (isArray) {
+                currentValue = ConfigurationManager.lookup().getAsStringValues(tenant, component, key);
+            } else {
+                currentValue = ConfigurationManager.lookup().getAsString(tenant, component, key);
             }
-          }
-          return !newCollection.isEmpty();
         }
-      } catch (Exception exception) {
-        return false;
-      }
-    }
 
-    /**
-     * Dispatch notification.
-     *
-     * @throws Exception the exception
-     */
-    public void dispatchNotification() throws Exception {
-      Method method = null;
-      Vector<Object> parameters = null;
-      try {
-        Object latestValue;
-        if (isArray) {
-          latestValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
-        } else {
-          latestValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
+        @Override
+        public int hashCode() {
+            return Objects.hash(tenant, namespace, key, myself, currentValue, isArray);
         }
-        Method[] methods = myself.getClass().getDeclaredMethods();
-        if (methods != null && methods.length > 0) {
-          method = methods[0];
-          int paramCount = method.getParameterCount();
-          parameters = new Vector<>();
-          if (paramCount > 4) {
-            if (tenant.equals(Constants.DEFAULT_TENANT)) {
-              parameters.add(null);
-            } else {
-              parameters.add(tenant);
-            }
-          }
-          if (paramCount > 3) {
-            if (namespace.equals(Constants.DEFAULT_NAMESPACE)) {
-              parameters.add(null);
-            } else {
-              parameters.add(namespace);
+
+        @Override
+        public boolean equals(Object obj) {
+            if (!(obj instanceof NotificationData)) {
+                return false;
             }
-          }
-          parameters.add(key);
-          parameters.add(currentValue);
-          parameters.add(latestValue);
-          method.setAccessible(true);
+            NotificationData nd = (NotificationData) obj;
+            return Objects.equals(tenant, nd.tenant) && Objects.equals(namespace, nd.namespace) && Objects.equals(key,
+                    nd.key) && Objects.equals(myself, nd.myself) && Objects.equals(currentValue, nd.currentValue)
+                           // it's either String or List<String>
+                           && isArray == nd.isArray;
         }
-      } catch (Exception exception) {
-        exception.printStackTrace();
-      } finally {
-        isArray = ConfigurationUtils.isArray(tenant, namespace, key, Hint.DEFAULT.value());
-        if (isArray) {
-          currentValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
-        } else {
-          currentValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
+
+        public boolean isChanged() {
+            Object latestValue;
+            try {
+                if (isArray) {
+                    latestValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
+                } else {
+                    latestValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
+                }
+                if (!isArray) {
+                    return !currentValue.equals(latestValue);
+                } else {
+                    Collection<String> oldCollection = (Collection<String>) currentValue;
+                    Collection<String> newCollection = (Collection<String>) latestValue;
+                    for (String val : oldCollection) {
+                        if (!newCollection.remove(val)) {
+                            return true;
+                        }
+                    }
+                    return !newCollection.isEmpty();
+                }
+            } catch (Exception exception) {
+                return false;
+            }
         }
-        if (method != null && parameters != null) {
-          method.invoke(myself, parameters.toArray());
+
+        public void dispatchNotification() throws Exception {
+            Method method = null;
+            Vector<Object> parameters = null;
+            try {
+                Object latestValue;
+                if (isArray) {
+                    latestValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
+                } else {
+                    latestValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
+                }
+                Method[] methods = myself.getClass().getDeclaredMethods();
+                if (methods != null && methods.length > 0) {
+                    method = methods[0];
+                    int paramCount = method.getParameterCount();
+                    parameters = new Vector<>();
+                    if (paramCount > 4) {
+                        if (tenant.equals(Constants.DEFAULT_TENANT)) {
+                            parameters.add(null);
+                        } else {
+                            parameters.add(tenant);
+                        }
+                    }
+                    if (paramCount > 3) {
+                        if (namespace.equals(Constants.DEFAULT_NAMESPACE)) {
+                            parameters.add(null);
+                        } else {
+                            parameters.add(namespace);
+                        }
+                    }
+                    parameters.add(key);
+                    parameters.add(currentValue);
+                    parameters.add(latestValue);
+                    method.setAccessible(true);
+                }
+            } catch (Exception exception) {
+                exception.printStackTrace();
+            } finally {
+                isArray = ConfigurationUtils.isArray(tenant, namespace, key, Hint.DEFAULT.value());
+                if (isArray) {
+                    currentValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
+                } else {
+                    currentValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
+                }
+                if (method != null && parameters != null) {
+                    method.invoke(myself, parameters.toArray());
+                }
+            }
         }
-      }
     }
-  }
 }
index 2956943..06981e4 100644 (file)
@@ -1,9 +1,21 @@
-package org.onap.config.impl;
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 
-import org.onap.config.Constants;
-import org.onap.config.api.Configuration;
+package org.onap.config.impl;
 
-import javax.servlet.annotation.WebFilter;
 import java.io.IOException;
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
@@ -11,31 +23,33 @@ import javax.servlet.FilterConfig;
 import javax.servlet.ServletException;
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
-
+import javax.servlet.annotation.WebFilter;
+import org.onap.config.Constants;
+import org.onap.config.api.Configuration;
 
 
 @WebFilter("/")
 public class ConfigurationFilter implements Filter {
 
-  @Override
-  public void init(FilterConfig paramFilterConfig) throws ServletException {
-    //Use the default behavior
-  }
-
-  @Override
-  public void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse,
-                       FilterChain paramFilterChain) throws IOException, ServletException {
-    Configuration.tenant.set(Constants.DEFAULT_TENANT);
-    try {
-      paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
-    } finally {
-      Configuration.tenant.remove();
+    @Override
+    public void init(FilterConfig paramFilterConfig) {
+        //Use the default behavior
     }
-  }
 
-  @Override
-  public void destroy() {
-    //Use the default behavior
-  }
+    @Override
+    public void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse,
+            FilterChain paramFilterChain) throws IOException, ServletException {
+        Configuration.TENANT.set(Constants.DEFAULT_TENANT);
+        try {
+            paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
+        } finally {
+            Configuration.TENANT.remove();
+        }
+    }
+
+    @Override
+    public void destroy() {
+        //Use the default behavior
+    }
 
 }
index 7da0a0f..58720fc 100644 (file)
@@ -37,614 +37,553 @@ import org.onap.config.api.Config;
 import org.onap.config.api.ConfigurationChangeListener;
 import org.onap.config.api.Hint;
 
-/**
- * The type Configuration.
- */
 public class ConfigurationImpl implements org.onap.config.api.Configuration {
 
-  private static final String KEY_CANNOT_BE_NULL = "Key can't be null.";
-  private static ThreadLocal<String> tenant = new ThreadLocal<String>() {
+    private static final String KEY_CANNOT_BE_NULL = "Key can't be null.";
+    private static final ThreadLocal<String> tenant = ThreadLocal.withInitial(() -> Constants.DEFAULT_TENANT);
 
-    @Override
-    protected String initialValue() {
-      return Constants.DEFAULT_TENANT;
-    }
+    private static boolean instantiated = false;
 
-    ;
-  };
-  private static boolean instantiated = false;
-  /**
-   * The Change notifier.
-   */
-  ConfigurationChangeNotifier changeNotifier;
+    ConfigurationChangeNotifier changeNotifier;
 
-  /**
-   * Instantiates a new Configuration.
-   *
-   * @throws Exception the exception
-   */
-  public ConfigurationImpl() throws Exception {
-    if (instantiated || !CliConfigurationImpl.class.isAssignableFrom(this.getClass())) {
-      throw new RuntimeException("Illegal access to configuration.");
-    }
-    Map<String, AggregateConfiguration> moduleConfigStore = new HashMap<>();
-    List<URL> classpathResources = ConfigurationUtils.getAllClassPathResources();
-    Predicate<URL> predicate = ConfigurationUtils::isConfig;
-    for (URL url : classpathResources) {
-      if (predicate.test(url)) {
-        String moduleName = ConfigurationUtils.getConfigurationRepositoryKey(url);
-        AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
-        if (moduleConfig == null) {
-          moduleConfig = new AggregateConfiguration();
-          moduleConfigStore.put(moduleName, moduleConfig);
-        }
-        moduleConfig.addConfig(url);
-      } else {
-        NonConfigResource.add(url);
-      }
-    }
-    String configLocation = System.getProperty("config.location");
-    if (configLocation != null && configLocation.trim().length() > 0) {
-      File root = new File(configLocation);
-      Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
-      Predicate<File> filePredicate = ConfigurationUtils::isConfig;
-      for (File file : filesystemResources) {
-        if (filePredicate.test(file)) {
-          String moduleName = ConfigurationUtils.getConfigurationRepositoryKey(file);
-          AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
-          if (moduleConfig == null) {
-            moduleConfig = new AggregateConfiguration();
-            moduleConfigStore.put(moduleName, moduleConfig);
-          }
-          moduleConfig.addConfig(file);
-        } else {
-          NonConfigResource.add(file);
+    public ConfigurationImpl() throws Exception {
+        if (instantiated || !CliConfigurationImpl.class.isAssignableFrom(this.getClass())) {
+            throw new RuntimeException("Illegal access to configuration.");
         }
-      }
-    }
-    String tenantConfigLocation = System.getProperty("tenant.config.location");
-    if (tenantConfigLocation != null && tenantConfigLocation.trim().length() > 0) {
-      File root = new File(tenantConfigLocation);
-      Collection<File> tenantsRoot = ConfigurationUtils.getAllFiles(root, false, true);
-      Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
-      Predicate<File> filePredicate = ConfigurationUtils::isConfig;
-      for (File file : filesystemResources) {
-        if (filePredicate.test(file)) {
-          String moduleName = ConfigurationUtils.getNamespace(file);
-          for (File tenanatFileRoot : tenantsRoot) {
-            if (file.getAbsolutePath().startsWith(tenanatFileRoot.getAbsolutePath())) {
-              moduleName = ConfigurationUtils.getConfigurationRepositoryKey(
-                  (tenanatFileRoot.getName().toUpperCase() + Constants.TENANT_NAMESPACE_SAPERATOR
-                      + moduleName).split(Constants.TENANT_NAMESPACE_SAPERATOR));
+        Map<String, AggregateConfiguration> moduleConfigStore = new HashMap<>();
+        List<URL> classpathResources = ConfigurationUtils.getAllClassPathResources();
+        Predicate<URL> predicate = ConfigurationUtils::isConfig;
+        for (URL url : classpathResources) {
+            if (predicate.test(url)) {
+                String moduleName = ConfigurationUtils.getConfigurationRepositoryKey(url);
+                AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
+                if (moduleConfig == null) {
+                    moduleConfig = new AggregateConfiguration();
+                    moduleConfigStore.put(moduleName, moduleConfig);
+                }
+                moduleConfig.addConfig(url);
+            } else {
+                NonConfigResource.add(url);
             }
-          }
-          AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
-          if (moduleConfig == null) {
-            moduleConfig = new AggregateConfiguration();
-            moduleConfigStore.put(moduleName, moduleConfig);
-          }
-          moduleConfig.addConfig(file);
-        }
-      }
-    }
-    populateFinalConfigurationIncrementally(moduleConfigStore);
-    ConfigurationRepository.lookup().initTenantsAndNamespaces();
-    String nodeConfigLocation = System.getProperty("node.config.location");
-    if (nodeConfigLocation != null && nodeConfigLocation.trim().length() > 0) {
-      File root = new File(nodeConfigLocation);
-      Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
-      Predicate<File> filePredicate = ConfigurationUtils::isConfig;
-      for (File file : filesystemResources) {
-        if (filePredicate.test(file)) {
-          ConfigurationRepository.lookup().populateOverrideConfigurtaion(
-              ConfigurationUtils.getConfigurationRepositoryKey(ConfigurationUtils.getNamespace(file)
-                  .split(Constants.TENANT_NAMESPACE_SAPERATOR)), file);
-        }
-      }
-    }
-    instantiated = true;
-    changeNotifier = new ConfigurationChangeNotifier(moduleConfigStore);
-  }
-
-  @Override
-  public void addConfigurationChangeListener(String tenant, String namespace, String key,
-                                             ConfigurationChangeListener myself) {
-    tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
-        : Constants.DEFAULT_TENANT;
-    namespace =
-        ConfigurationRepository.lookup().isValidNamespace(namespace) ? namespace.toUpperCase()
-            : Constants.DEFAULT_NAMESPACE;
-    if (key == null || key.trim().length() == 0) {
-      throw new IllegalArgumentException(KEY_CANNOT_BE_NULL);
-    }
-    if (myself == null) {
-      throw new IllegalArgumentException("ConfigurationChangeListener instance is null.");
-    }
-    try {
-      changeNotifier.notifyChangesTowards(tenant, namespace, key, myself);
-    } catch (Exception exception) {
-      exception.printStackTrace();
+        }
+        String configLocation = System.getProperty("config.location");
+        if (configLocation != null && configLocation.trim().length() > 0) {
+            File root = new File(configLocation);
+            Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
+            Predicate<File> filePredicate = ConfigurationUtils::isConfig;
+            for (File file : filesystemResources) {
+                if (filePredicate.test(file)) {
+                    String moduleName = ConfigurationUtils.getConfigurationRepositoryKey(file);
+                    AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
+                    if (moduleConfig == null) {
+                        moduleConfig = new AggregateConfiguration();
+                        moduleConfigStore.put(moduleName, moduleConfig);
+                    }
+                    moduleConfig.addConfig(file);
+                } else {
+                    NonConfigResource.add(file);
+                }
+            }
+        }
+        String tenantConfigLocation = System.getProperty("tenant.config.location");
+        if (tenantConfigLocation != null && tenantConfigLocation.trim().length() > 0) {
+            File root = new File(tenantConfigLocation);
+            Collection<File> tenantsRoot = ConfigurationUtils.getAllFiles(root, false, true);
+            Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
+            Predicate<File> filePredicate = ConfigurationUtils::isConfig;
+            for (File file : filesystemResources) {
+                if (filePredicate.test(file)) {
+                    String moduleName = ConfigurationUtils.getNamespace(file);
+                    for (File tenantFileRoot : tenantsRoot) {
+                        if (file.getAbsolutePath().startsWith(tenantFileRoot.getAbsolutePath())) {
+                            moduleName = ConfigurationUtils.getConfigurationRepositoryKey(
+                                    (tenantFileRoot.getName().toUpperCase() + Constants.TENANT_NAMESPACE_SEPARATOR
+                                             + moduleName).split(Constants.TENANT_NAMESPACE_SEPARATOR));
+                        }
+                    }
+                    AggregateConfiguration moduleConfig = moduleConfigStore.get(moduleName);
+                    if (moduleConfig == null) {
+                        moduleConfig = new AggregateConfiguration();
+                        moduleConfigStore.put(moduleName, moduleConfig);
+                    }
+                    moduleConfig.addConfig(file);
+                }
+            }
+        }
+        populateFinalConfigurationIncrementally(moduleConfigStore);
+        String nodeConfigLocation = System.getProperty("node.config.location");
+        if (nodeConfigLocation != null && nodeConfigLocation.trim().length() > 0) {
+            File root = new File(nodeConfigLocation);
+            Collection<File> filesystemResources = ConfigurationUtils.getAllFiles(root, true, false);
+            Predicate<File> filePredicate = ConfigurationUtils::isConfig;
+            for (File file : filesystemResources) {
+                if (filePredicate.test(file)) {
+                    ConfigurationRepository.lookup().populateOverrideConfiguration(
+                            ConfigurationUtils.getConfigurationRepositoryKey(
+                                    ConfigurationUtils.getNamespace(file).split(Constants.TENANT_NAMESPACE_SEPARATOR)),
+                            file);
+                }
+            }
+        }
+        instantiated = true;
+        changeNotifier = new ConfigurationChangeNotifier(moduleConfigStore);
     }
-  }
 
-  private void populateFinalConfigurationIncrementally(Map<String, AggregateConfiguration> configs) {
+    private void populateFinalConfigurationIncrementally(Map<String, AggregateConfiguration> configs) {
 
-    if (configs.get(
-        Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELEMETER + Constants.DB_NAMESPACE)
-        != null) {
-      ConfigurationRepository.lookup().populateConfigurtaion(
-          Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELEMETER + Constants.DB_NAMESPACE,
-          configs.remove(
-              Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELEMETER + Constants.DB_NAMESPACE)
-              .getFinalConfiguration());
-    }
+        if (configs.get(Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELIMETER + Constants.DB_NAMESPACE) != null) {
+            ConfigurationRepository.lookup().populateConfiguration(
+                    Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELIMETER + Constants.DB_NAMESPACE,
+                    configs.remove(Constants.DEFAULT_TENANT + Constants.KEY_ELEMENTS_DELIMETER + Constants.DB_NAMESPACE)
+                            .getFinalConfiguration());
+        }
 
-    Set<String> modules = configs.keySet();
-    for (String module : modules) {
-        ConfigurationRepository.lookup()
-            .populateConfigurtaion(module, configs.get(module).getFinalConfiguration());
+        Set<String> modules = configs.keySet();
+        for (String module : modules) {
+            ConfigurationRepository.lookup().populateConfiguration(module, configs.get(module).getFinalConfiguration());
+        }
     }
-  }
 
-  @Override
-  public <T> T get(String tenant, String namespace, String key, Class<T> clazz, Hint... hints) {
+    @Override
+    public <T> T get(String tenant, String namespace, String key, Class<T> clazz, Hint... hints) {
+
+        String[] tenantNamespaceArray;
+        if (tenant == null && namespace != null) {
+            tenantNamespaceArray = namespace.split(Constants.TENANT_NAMESPACE_SEPARATOR);
+            if (tenantNamespaceArray.length > 1) {
+                tenant = tenantNamespaceArray[0];
+                namespace = tenantNamespaceArray[1];
+            }
+        }
 
-    String[] tenantNamespaceArrayy;
-    if (tenant == null && namespace != null) {
-      tenantNamespaceArrayy = namespace.split(Constants.TENANT_NAMESPACE_SAPERATOR);
-      if (tenantNamespaceArrayy.length > 1) {
-        tenant = tenantNamespaceArrayy[0];
-        namespace = tenantNamespaceArrayy[1];
-      }
+        tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
+                         : Constants.DEFAULT_TENANT;
+        namespace = ConfigurationRepository.lookup().isValidNamespace(namespace) ? namespace.toUpperCase()
+                            : Constants.DEFAULT_NAMESPACE;
+        T returnValue;
+        returnValue = (T) getInternal(tenant, namespace, key, clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
+                hints == null || hints.length == 0 ? new Hint[] {Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC} : hints);
+        if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
+                    && !Constants.DEFAULT_TENANT.equals(tenant)) {
+            returnValue = (T) getInternal(Constants.DEFAULT_TENANT, namespace, key,
+                    clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
+                    hints == null || hints.length == 0 ? new Hint[] {Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC} : hints);
+        }
+        if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
+                    && !Constants.DEFAULT_NAMESPACE.equals(namespace)) {
+            returnValue = (T) getInternal(tenant, Constants.DEFAULT_NAMESPACE, key,
+                    clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
+                    hints == null || hints.length == 0 ? new Hint[] {Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC} : hints);
+        }
+        if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
+                    && !Constants.DEFAULT_NAMESPACE.equals(namespace) && !Constants.DEFAULT_TENANT.equals(tenant)) {
+            returnValue = (T) getInternal(Constants.DEFAULT_TENANT, Constants.DEFAULT_NAMESPACE, key,
+                    clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
+                    hints == null || hints.length == 0 ? new Hint[] {Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC} : hints);
+        }
+        if (returnValue == null && clazz.isPrimitive()) {
+            return (T) ConfigurationUtils.getDefaultFor(clazz);
+        } else {
+            return returnValue;
+        }
     }
 
-    tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
-        : Constants.DEFAULT_TENANT;
-    namespace =
-        ConfigurationRepository.lookup().isValidNamespace(namespace) ? namespace.toUpperCase()
-            : Constants.DEFAULT_NAMESPACE;
-    T returnValue = null;
-    returnValue = (T) getInternal(tenant, namespace, key,
-        clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
-        hints == null || hints.length == 0 ? new Hint[]{Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC}
-            : hints);
-    if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
-        && !Constants.DEFAULT_TENANT.equals(tenant)) {
-      returnValue = (T) getInternal(Constants.DEFAULT_TENANT, namespace, key,
-          clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
-          hints == null || hints.length == 0 ? new Hint[]{Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC}
-              : hints);
-    }
-    if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
-        && !Constants.DEFAULT_NAMESPACE.equals(namespace)) {
-      returnValue = (T) getInternal(tenant, Constants.DEFAULT_NAMESPACE, key,
-          clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
-          hints == null || hints.length == 0 ? new Hint[]{Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC}
-              : hints);
-    }
-    if ((returnValue == null || ConfigurationUtils.isZeroLengthArray(clazz, returnValue))
-        && !Constants.DEFAULT_NAMESPACE.equals(namespace)
-        && !Constants.DEFAULT_TENANT.equals(tenant)) {
-      returnValue = (T) getInternal(Constants.DEFAULT_TENANT, Constants.DEFAULT_NAMESPACE, key,
-          clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
-          hints == null || hints.length == 0 ? new Hint[]{Hint.EXTERNAL_LOOKUP, Hint.NODE_SPECIFIC}
-              : hints);
-    }
-    if (returnValue == null && clazz.isPrimitive()) {
-      return (T) ConfigurationUtils.getDefaultFor(clazz);
-    } else {
-      return returnValue;
+    @Override
+    public void addConfigurationChangeListener(String tenant, String namespace, String key,
+            ConfigurationChangeListener myself) {
+        tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
+                         : Constants.DEFAULT_TENANT;
+        namespace = ConfigurationRepository.lookup().isValidNamespace(namespace) ? namespace.toUpperCase()
+                            : Constants.DEFAULT_NAMESPACE;
+        if (key == null || key.trim().length() == 0) {
+            throw new IllegalArgumentException(KEY_CANNOT_BE_NULL);
+        }
+        if (myself == null) {
+            throw new IllegalArgumentException("ConfigurationChangeListener instance is null.");
+        }
+        try {
+            changeNotifier.notifyChangesTowards(tenant, namespace, key, myself);
+        } catch (Exception exception) {
+            exception.printStackTrace();
+        }
     }
-  }
 
-
-  /**
-   * Gets internal.
-   *
-   * @param <T>       the type parameter
-   * @param tenant    the tenant
-   * @param namespace the namespace
-   * @param key       the key
-   * @param clazz     the clazz
-   * @param hints     the hints
-   * @return the internal
-   */
-  protected <T> T getInternal(String tenant, String namespace, String key, Class<T> clazz,
-                              Hint... hints) {
-    int processingHints = Hint.DEFAULT.value();
-    if (hints != null) {
-      for (Hint hint : hints) {
-        processingHints = processingHints | hint.value();
-      }
+    @Override
+    public void removeConfigurationChangeListener(String tenant, String namespace, String key,
+            ConfigurationChangeListener myself) {
+        tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
+                         : Constants.DEFAULT_TENANT;
+        namespace = ConfigurationRepository.lookup().isValidNamespace(namespace) ? namespace.toUpperCase()
+                            : Constants.DEFAULT_NAMESPACE;
+        if (key == null || key.trim().length() == 0) {
+            throw new IllegalArgumentException(KEY_CANNOT_BE_NULL);
+        }
+        try {
+            changeNotifier.stopNotificationTowards(tenant, namespace, key, myself);
+        } catch (Exception exception) {
+            exception.printStackTrace();
+        }
     }
 
-    if (tenant == null || tenant.trim().length() == 0) {
-      tenant = ConfigurationImpl.tenant.get();
-    } else {
-      tenant = tenant.toUpperCase();
-    }
-    if (namespace == null || namespace.trim().length() == 0) {
-      namespace = Constants.DEFAULT_NAMESPACE;
-    } else {
-      namespace = namespace.toUpperCase();
-    }
-    if ((key == null || key.trim().length() == 0) && !clazz.isAnnotationPresent(Config.class)) {
-      throw new IllegalArgumentException(KEY_CANNOT_BE_NULL);
-    }
-    if (clazz == null) {
-      throw new IllegalArgumentException("clazz is null.");
-    }
-    if (clazz.isPrimitive()) {
-      clazz = getWrapperClass(clazz);
-    }
-    try {
-      if (ConfigurationUtils.isWrapperClass(clazz) || clazz.isPrimitive()) {
-        Object obj =
-            ConfigurationUtils
-                .getProperty(ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace),
-                key, processingHints);
-        if (obj != null) {
-          if (ConfigurationUtils.isCollection(obj.toString())) {
-            obj = ConfigurationUtils.getCollectionString(obj.toString());
-          }
-          String value = obj.toString().split(",")[0];
-          value = ConfigurationUtils.processVariablesIfPresent(tenant, namespace, value);
-          return (T) getValue(value, clazz.isPrimitive() ? getWrapperClass(clazz) : clazz,
-              processingHints);
+    @Override
+    public <T> Map<String, T> populateMap(String tenantId, String namespace, String key, Class<T> clazz) {
+        if (tenantId == null || tenantId.trim().length() == 0) {
+            tenantId = tenant.get();
         } else {
-          return null;
-        }
-      } else if (clazz.isArray()
-          && (clazz.getComponentType().isPrimitive() || ConfigurationUtils.isWrapperClass(clazz.getComponentType()))) {
-        Object obj =
-            ConfigurationUtils
-                .getProperty(ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace),
-                key, processingHints);
-        if (obj != null) {
-          Class componentClass = clazz.getComponentType();
-          if (clazz.getComponentType().isPrimitive()) {
-            componentClass = getWrapperClass(clazz.getComponentType());
-          }
-          String collString = ConfigurationUtils.getCollectionString(obj.toString());
-          ArrayList<String> tempCollection = new ArrayList<>();
-          for (String itemValue : collString.split(",")) {
-            tempCollection
-                .add(ConfigurationUtils.processVariablesIfPresent(tenant, namespace, itemValue));
-          }
-          Collection<T> collection = convert(
-              ConfigurationUtils.getCollectionString(Arrays.toString(tempCollection.toArray())),
-              componentClass, processingHints);
-          if (clazz.getComponentType().isPrimitive()) {
-            return (T) ConfigurationUtils.getPrimitiveArray(collection, clazz.getComponentType());
-          } else {
-            return (T) collection
-                .toArray(getZeroLengthArrayFor(getWrapperClass(clazz.getComponentType())));
-          }
+            tenantId = tenantId.toUpperCase();
+        }
+        if (namespace == null || namespace.trim().length() == 0) {
+            namespace = Constants.DEFAULT_NAMESPACE;
         } else {
-          return null;
-        }
-      } else if (clazz.isAnnotationPresent(Config.class)) {
-        return read(tenant, namespace, clazz,
-            (key == null || key.trim().length() == 0) ? "" : (key + "."), hints);
-      } else {
-        throw new IllegalArgumentException(
-            "Only pimitive classes, wrapper classes, corresponding array classes and any "
-                + "class decorated with @org.openecomp.config.api.Config are allowed as argument.");
-      }
-    } catch (Exception exception) {
-      exception.printStackTrace();
+            namespace = namespace.toUpperCase();
+        }
+        Map<String, T> map = new HashMap<>();
+        Iterator<String> keys;
+        try {
+            keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys(key);
+            while (keys.hasNext()) {
+                String k = keys.next();
+                if (k.startsWith(key + ".")) {
+                    k = k.substring(key.length() + 1);
+                    String subkey = k.substring(0, k.indexOf("."));
+                    if (!map.containsKey(subkey)) {
+                        map.put(subkey, get(tenantId, namespace, key + "." + subkey, clazz));
+                    }
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return map;
     }
-    return null;
-  }
 
-
-  private <T> T read(String tenant, String namespace, Class<T> clazz, String keyPrefix,
-                     Hint... hints) throws Exception {
-    Config confAnnot =
-        clazz.getAnnotation(Config.class);
-    if (confAnnot != null && confAnnot.key().length()>0 && !keyPrefix.endsWith(".")) {
-      keyPrefix += (confAnnot.key() + ".");
-    }
-    Constructor<T> constructor = clazz.getDeclaredConstructor();
-    constructor.setAccessible(true);
-    T objToReturn = constructor.newInstance();
-    for (Field field : clazz.getDeclaredFields()) {
-      field.setAccessible(true);
-      Config fieldConfAnnot =
-          field.getAnnotation(Config.class);
-      if (fieldConfAnnot != null) {
-        if (field.getType().isPrimitive() || ConfigurationUtils.isWrapperClass(field.getType())
-            || (field.getType().isArray() && (field.getType().getComponentType().isPrimitive()
-            || ConfigurationUtils.isWrapperClass(field.getType().getComponentType())))
-            || field.getType().getAnnotation(Config.class) != null) {
-          field.set(objToReturn,
-              get(tenant, namespace, keyPrefix + fieldConfAnnot.key(), field.getType(), hints));
-        } else if (Collection.class.isAssignableFrom(field.getType())) {
-          Object obj = get(tenant, namespace, keyPrefix + fieldConfAnnot.key(),
-              ConfigurationUtils.getArrayClass(ConfigurationUtils.getCollectionGenericType(field)),
-              hints);
-          if (obj != null) {
-            List list = Arrays.asList((Object[]) obj);
-            Class clazzToInstantiate = null;
-            if (field.getType().isInterface()) {
-              clazzToInstantiate =
-                  ConfigurationUtils.getConcreteCollection(field.getType()).getClass();
-            } else if (Modifier.isAbstract(field.getType().getModifiers())) {
-              clazzToInstantiate =
-                  ConfigurationUtils.getCompatibleCollectionForAbstractDef(field.getType())
-                      .getClass();
+    @Override
+    public Map generateMap(String tenantId, String namespace, String key) {
+        if (tenantId == null || tenantId.trim().length() == 0) {
+            tenantId = tenant.get();
+        } else {
+            tenantId = tenantId.toUpperCase();
+        }
+        if (namespace == null || namespace.trim().length() == 0) {
+            namespace = Constants.DEFAULT_NAMESPACE;
+        } else {
+            namespace = namespace.toUpperCase();
+        }
+        Map map;
+        Map parentMap = new HashMap<>();
+        Iterator<String> keys;
+        try {
+            if (key == null || key.trim().length() == 0) {
+                keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys();
             } else {
-              clazzToInstantiate = field.getType();
+                keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys(key);
             }
-            Constructor construct =
-                getConstructorWithArguments(clazzToInstantiate, Collection.class);
-            if (construct != null) {
-              construct.setAccessible(true);
-              field.set(objToReturn, construct.newInstance(list));
-            } else if ((construct =
-                getConstructorWithArguments(clazzToInstantiate, Integer.class, Boolean.class,
-                    Collection.class)) != null) {
-              construct.setAccessible(true);
-              field.set(objToReturn, construct.newInstance(list.size(), true, list));
+            while (keys.hasNext()) {
+                map = parentMap;
+                String k = keys.next();
+
+                if (key != null && key.trim().length() != 0 && !k.startsWith(key + ".")) {
+                    continue;
+                }
+                String value = getAsString(tenantId, namespace, k);
+                if (key != null && key.trim().length() != 0 && k.startsWith(key + ".")) {
+                    k = k.substring(key.trim().length() + 1);
+                }
+
+                while (k.contains(".")) {
+                    if (k.contains(".")) {
+                        String subkey = k.substring(0, k.indexOf("."));
+                        k = k.substring(k.indexOf(".") + 1);
+                        if (!map.containsKey(subkey)) {
+                            map.put(subkey, map = new HashMap<>());
+                        } else {
+                            map = (Map) map.get(subkey);
+                        }
+                    }
+                }
+                map.put(k, value);
             }
-          }
-        }else if (Map.class.isAssignableFrom(field.getType())){
-          field.set(objToReturn, generateMap(tenant, namespace, keyPrefix+fieldConfAnnot.key()));
+        } catch (Exception e) {
+            e.printStackTrace();
         }
-      }
-    }
-    return objToReturn;
-  }
-
-  private Constructor getConstructorWithArguments(Class clazz, Class... classes) {
-    try {
-      return clazz.getDeclaredConstructor(classes);
-    } catch (Exception exception) {
-      return null;
-    }
-  }
-
-  private Class getWrapperClass(Class clazz) {
-    if (byte.class == clazz) {
-      return Byte.class;
-    } else if (short.class == clazz) {
-      return Short.class;
-    } else if (int.class == clazz) {
-      return Integer.class;
-    } else if (long.class == clazz) {
-      return Long.class;
-    } else if (float.class == clazz) {
-      return Float.class;
-    } else if (double.class == clazz) {
-      return Double.class;
-    } else if (char.class == clazz) {
-      return Character.class;
-    } else if (boolean.class == clazz) {
-      return Boolean.class;
+        return parentMap;
     }
-    return clazz;
-  }
 
-  private <T> T getValue(Object obj, Class<T> clazz, int processingHint) {
-    if (obj == null || obj.toString().trim().length() == 0) {
-      return null;
-    } else {
-      obj = obj.toString().trim();
-    }
-    if (String.class.equals(clazz)) {
-      if (obj.toString().startsWith("@") && ConfigurationUtils.isExternalLookup(processingHint)) {
-        String contents = ConfigurationUtils
-            .getFileContents(NonConfigResource.locate(obj.toString().substring(1).trim()));
-        if (contents == null) {
-          contents = ConfigurationUtils.getFileContents(obj.toString().substring(1).trim());
-        }
-        if (contents != null) {
-          obj = contents;
-        }
-      }
-      return (T) obj.toString();
-    } else if (Number.class.isAssignableFrom(clazz)) {
-      Double doubleValue = Double.valueOf(obj.toString());
-      switch (clazz.getName()) {
-        case "java.lang.Byte":
-          Byte byteVal = doubleValue.byteValue();
-          return (T) byteVal;
-        case "java.lang.Short":
-          Short shortVal = doubleValue.shortValue();
-          return (T) shortVal;
-        case "java.lang.Integer":
-          Integer intVal = doubleValue.intValue();
-          return (T) intVal;
-        case "java.lang.Long":
-          Long longVal = doubleValue.longValue();
-          return (T) longVal;
-        case "java.lang.Float":
-          Float floatVal = doubleValue.floatValue();
-          return (T) floatVal;
-        case "java.lang.Double":
-          Double doubleVal = doubleValue;
-          return (T) doubleVal;
-        default:
-      }
-    } else if (Boolean.class.equals(clazz)) {
-      return (T) Boolean.valueOf(obj.toString());
-    } else if (Character.class.equals(clazz)) {
-      return (T) Character.valueOf(obj.toString().charAt(0));
-    }
-    return null;
-  }
-
-  private <T> T[] getZeroLengthArrayFor(Class<T> clazz) {
-    Object obj = null;
-    if (clazz == int.class) {
-      obj = new int[]{};
-    } else if (clazz == byte.class) {
-      obj = new byte[]{};
-    } else if (clazz == short.class) {
-      obj = new short[]{};
-    } else if (clazz == long.class) {
-      obj = new long[]{};
-    } else if (clazz == float.class) {
-      obj = new float[]{};
-    } else if (clazz == double.class) {
-      obj = new double[]{};
-    } else if (clazz == boolean.class) {
-      obj = new boolean[]{};
-    } else if (clazz == char.class) {
-      obj = new char[]{};
-    } else if (clazz == Byte.class) {
-      obj = new Byte[]{};
-    } else if (clazz == Short.class) {
-      obj = new Short[]{};
-    } else if (clazz == Integer.class) {
-      obj = new Integer[]{};
-    } else if (clazz == Long.class) {
-      obj = new Long[]{};
-    } else if (clazz == Float.class) {
-      obj = new Float[]{};
-    } else if (clazz == Double.class) {
-      obj = new Double[]{};
-    } else if (clazz == Boolean.class) {
-      obj = new Boolean[]{};
-    } else if (clazz == Character.class) {
-      obj = new Character[]{};
-    } else if (clazz == String.class) {
-      obj = new String[]{};
-    }
-    return (T[]) obj;
-  }
-
-  private <T> Collection<T> convert(String commaSaperatedValues, Class<T> clazz,
-                                    int processingHints) {
-    ArrayList<T> collection = new ArrayList<>();
-    for (String value : commaSaperatedValues.split(",")) {
-      try {
-        T type1 = getValue(value, clazz, processingHints);
-        if (type1 != null) {
-          collection.add(type1);
-        }
-      } catch (RuntimeException re) {
-        // do nothing
-      }
-    }
-    return collection;
-  }
+    protected <T> T getInternal(String tenant, String namespace, String key, Class<T> clazz, Hint... hints) {
+        int processingHints = Hint.DEFAULT.value();
+        if (hints != null) {
+            for (Hint hint : hints) {
+                processingHints = processingHints | hint.value();
+            }
+        }
 
-  /**
-   * Shutdown.
-   */
-  public void shutdown() {
-    if (changeNotifier != null) {
-      try {
-        changeNotifier.shutdown();
-      } catch (Exception exception) {
-        exception.printStackTrace();
-      }
+        if (tenant == null || tenant.trim().length() == 0) {
+            tenant = ConfigurationImpl.tenant.get();
+        } else {
+            tenant = tenant.toUpperCase();
+        }
+        if (namespace == null || namespace.trim().length() == 0) {
+            namespace = Constants.DEFAULT_NAMESPACE;
+        } else {
+            namespace = namespace.toUpperCase();
+        }
+        if ((key == null || key.trim().length() == 0) && !clazz.isAnnotationPresent(Config.class)) {
+            throw new IllegalArgumentException(KEY_CANNOT_BE_NULL);
+        }
+        if (clazz == null) {
+            throw new IllegalArgumentException("clazz is null.");
+        }
+        if (clazz.isPrimitive()) {
+            clazz = getWrapperClass(clazz);
+        }
+        try {
+            if (ConfigurationUtils.isWrapperClass(clazz) || clazz.isPrimitive()) {
+                Object obj = ConfigurationUtils.getProperty(
+                        ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key, processingHints);
+                if (obj != null) {
+                    if (ConfigurationUtils.isCollection(obj.toString())) {
+                        obj = ConfigurationUtils.getCollectionString(obj.toString());
+                    }
+                    String value = obj.toString().split(",")[0];
+                    value = ConfigurationUtils.processVariablesIfPresent(tenant, namespace, value);
+                    return (T) getValue(value, clazz.isPrimitive() ? getWrapperClass(clazz) : clazz, processingHints);
+                } else {
+                    return null;
+                }
+            } else if (clazz.isArray() && (clazz.getComponentType().isPrimitive() || ConfigurationUtils.isWrapperClass(
+                    clazz.getComponentType()))) {
+                Object obj = ConfigurationUtils.getProperty(
+                        ConfigurationRepository.lookup().getConfigurationFor(tenant, namespace), key, processingHints);
+                if (obj != null) {
+                    Class componentClass = clazz.getComponentType();
+                    if (clazz.getComponentType().isPrimitive()) {
+                        componentClass = getWrapperClass(clazz.getComponentType());
+                    }
+                    String collString = ConfigurationUtils.getCollectionString(obj.toString());
+                    ArrayList<String> tempCollection = new ArrayList<>();
+                    for (String itemValue : collString.split(",")) {
+                        tempCollection.add(ConfigurationUtils.processVariablesIfPresent(tenant, namespace, itemValue));
+                    }
+                    Collection<T> collection =
+                            convert(ConfigurationUtils.getCollectionString(Arrays.toString(tempCollection.toArray())),
+                                    componentClass, processingHints);
+                    if (clazz.getComponentType().isPrimitive()) {
+                        return (T) ConfigurationUtils.getPrimitiveArray(collection, clazz.getComponentType());
+                    } else {
+                        return (T) collection.toArray(getZeroLengthArrayFor(getWrapperClass(clazz.getComponentType())));
+                    }
+                } else {
+                    return null;
+                }
+            } else if (clazz.isAnnotationPresent(Config.class)) {
+                return read(tenant, namespace, clazz, (key == null || key.trim().length() == 0) ? "" : (key + "."),
+                        hints);
+            } else {
+                throw new IllegalArgumentException(
+                        "Only primitive classes, wrapper classes, corresponding array classes and any "
+                                + "class decorated with @org.openecomp.config.api.Config are allowed as argument.");
+            }
+        } catch (Exception exception) {
+            exception.printStackTrace();
+        }
+        return null;
     }
-  }
 
-  @Override
-  public void removeConfigurationChangeListener(String tenant, String namespace, String key,
-                                                ConfigurationChangeListener myself) {
-    tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
-        : Constants.DEFAULT_TENANT;
-    namespace =
-        ConfigurationRepository.lookup().isValidNamespace(namespace) ? namespace.toUpperCase()
-            : Constants.DEFAULT_NAMESPACE;
-    if (key == null || key.trim().length() == 0) {
-      throw new IllegalArgumentException(KEY_CANNOT_BE_NULL);
-    }
-    try {
-      changeNotifier.stopNotificationTowards(tenant, namespace, key, myself);
-    } catch (Exception exception) {
-      exception.printStackTrace();
+    private <T> T read(String tenant, String namespace, Class<T> clazz, String keyPrefix, Hint... hints)
+            throws Exception {
+        Config confAnnotation = clazz.getAnnotation(Config.class);
+        if (confAnnotation != null && confAnnotation.key().length() > 0 && !keyPrefix.endsWith(".")) {
+            keyPrefix += (confAnnotation.key() + ".");
+        }
+        Constructor<T> constructor = clazz.getDeclaredConstructor();
+        constructor.setAccessible(true);
+        T objToReturn = constructor.newInstance();
+        for (Field field : clazz.getDeclaredFields()) {
+            field.setAccessible(true);
+            Config fieldConfAnnotation = field.getAnnotation(Config.class);
+            if (fieldConfAnnotation != null) {
+                if (field.getType().isPrimitive() || ConfigurationUtils.isWrapperClass(field.getType()) || (
+                        field.getType().isArray() && (field.getType().getComponentType().isPrimitive()
+                                                              || ConfigurationUtils.isWrapperClass(
+                                field.getType().getComponentType())))
+                            || field.getType().getAnnotation(Config.class) != null) {
+                    field.set(objToReturn,
+                            get(tenant, namespace, keyPrefix + fieldConfAnnotation.key(), field.getType(), hints));
+                } else if (Collection.class.isAssignableFrom(field.getType())) {
+                    Object obj = get(tenant, namespace, keyPrefix + fieldConfAnnotation.key(),
+                            ConfigurationUtils.getArrayClass(ConfigurationUtils.getCollectionGenericType(field)),
+                            hints);
+                    if (obj != null) {
+                        List list = Arrays.asList((Object[]) obj);
+                        Class clazzToInstantiate;
+                        if (field.getType().isInterface()) {
+                            clazzToInstantiate = ConfigurationUtils.getConcreteCollection(field.getType()).getClass();
+                        } else if (Modifier.isAbstract(field.getType().getModifiers())) {
+                            clazzToInstantiate =
+                                    ConfigurationUtils.getCompatibleCollectionForAbstractDef(field.getType())
+                                            .getClass();
+                        } else {
+                            clazzToInstantiate = field.getType();
+                        }
+                        Constructor construct = getConstructorWithArguments(clazzToInstantiate, Collection.class);
+                        if (construct != null) {
+                            construct.setAccessible(true);
+                            field.set(objToReturn, construct.newInstance(list));
+                        } else if ((construct = getConstructorWithArguments(clazzToInstantiate, Integer.class,
+                                Boolean.class, Collection.class)) != null) {
+                            construct.setAccessible(true);
+                            field.set(objToReturn, construct.newInstance(list.size(), true, list));
+                        }
+                    }
+                } else if (Map.class.isAssignableFrom(field.getType())) {
+                    field.set(objToReturn, generateMap(tenant, namespace, keyPrefix + fieldConfAnnotation.key()));
+                }
+            }
+        }
+        return objToReturn;
     }
-  }
 
-  @Override
-  public <T> Map<String, T> populateMap(String tenantId, String namespace, String key, Class<T> clazz){
-    if (tenantId==null || tenantId.trim().length()==0){
-      tenantId = tenant.get();
-    }else{
-      tenantId = tenantId.toUpperCase();
-    }
-    if (namespace==null || namespace.trim().length()==0){
-      namespace = Constants.DEFAULT_NAMESPACE;
-    }else{
-      namespace = namespace.toUpperCase();
-    }
-    Map<String, T> map = new HashMap<>();
-    Iterator<String> keys ;
-    try {
-      keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys(key);
-      while(keys.hasNext()){
-        String k = keys.next();
-        if (k.startsWith(key+".")){
-          k = k.substring(key.length()+1);
-          String subkey = k.substring(0, k.indexOf("."));
-          if (!map.containsKey(subkey)){
-            map.put(subkey, get(tenantId, namespace, key+"."+subkey, clazz));
-          }
-        }
-      }
-    }catch (Exception e){
-      e.printStackTrace();
+    private Constructor getConstructorWithArguments(Class clazz, Class... classes) {
+        try {
+            return clazz.getDeclaredConstructor(classes);
+        } catch (Exception exception) {
+            return null;
+        }
     }
-    return map;
-  }
 
-  @Override
-  public Map generateMap(String tenantId, String namespace, String key){
-    if (tenantId==null || tenantId.trim().length()==0){
-      tenantId = tenant.get();
-    }else{
-      tenantId = tenantId.toUpperCase();
-    }
-    if (namespace==null || namespace.trim().length()==0){
-      namespace = Constants.DEFAULT_NAMESPACE;
-    }else{
-      namespace = namespace.toUpperCase();
+    private Class getWrapperClass(Class clazz) {
+        if (byte.class == clazz) {
+            return Byte.class;
+        } else if (short.class == clazz) {
+            return Short.class;
+        } else if (int.class == clazz) {
+            return Integer.class;
+        } else if (long.class == clazz) {
+            return Long.class;
+        } else if (float.class == clazz) {
+            return Float.class;
+        } else if (double.class == clazz) {
+            return Double.class;
+        } else if (char.class == clazz) {
+            return Character.class;
+        } else if (boolean.class == clazz) {
+            return Boolean.class;
+        }
+        return clazz;
     }
-    Map map, parentMap = new HashMap<>();
-    Iterator<String> keys ;
-    try {
-      if (key==null || key.trim().length()==0){
-        keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys();
-      }else{
-        keys = ConfigurationRepository.lookup().getConfigurationFor(tenantId, namespace).getKeys(key);
-      }
-      while(keys.hasNext()){
-        map = parentMap;
-        String k = keys.next();
 
-        if (key!=null && key.trim().length()!=0 && !k.startsWith(key+".")){
-          continue;
+    private <T> T getValue(Object obj, Class<T> clazz, int processingHint) {
+        if (obj == null || obj.toString().trim().length() == 0) {
+            return null;
+        } else {
+            obj = obj.toString().trim();
+        }
+        if (String.class.equals(clazz)) {
+            if (obj.toString().startsWith("@") && ConfigurationUtils.isExternalLookup(processingHint)) {
+                String contents = ConfigurationUtils.getFileContents(
+                        NonConfigResource.locate(obj.toString().substring(1).trim()));
+                if (contents == null) {
+                    contents = ConfigurationUtils.getFileContents(obj.toString().substring(1).trim());
+                }
+                if (contents != null) {
+                    obj = contents;
+                }
+            }
+            return (T) obj.toString();
+        } else if (Number.class.isAssignableFrom(clazz)) {
+            Double doubleValue = Double.valueOf(obj.toString());
+            switch (clazz.getName()) {
+                case "java.lang.Byte":
+                    Byte byteVal = doubleValue.byteValue();
+                    return (T) byteVal;
+                case "java.lang.Short":
+                    Short shortVal = doubleValue.shortValue();
+                    return (T) shortVal;
+                case "java.lang.Integer":
+                    Integer intVal = doubleValue.intValue();
+                    return (T) intVal;
+                case "java.lang.Long":
+                    Long longVal = doubleValue.longValue();
+                    return (T) longVal;
+                case "java.lang.Float":
+                    Float floatVal = doubleValue.floatValue();
+                    return (T) floatVal;
+                case "java.lang.Double":
+                    return (T) doubleValue;
+                default:
+            }
+        } else if (Boolean.class.equals(clazz)) {
+            return (T) Boolean.valueOf(obj.toString());
+        } else if (Character.class.equals(clazz)) {
+            return (T) Character.valueOf(obj.toString().charAt(0));
         }
-        String value = getAsString(tenantId, namespace, k);
-        if (key!=null && key.trim().length()!=0 && k.startsWith(key+".")){
-          k = k.substring(key.trim().length()+1);
+        return null;
+    }
+
+    private <T> T[] getZeroLengthArrayFor(Class<T> clazz) {
+        Object obj = null;
+        if (clazz == int.class) {
+            obj = new int[] {};
+        } else if (clazz == byte.class) {
+            obj = new byte[] {};
+        } else if (clazz == short.class) {
+            obj = new short[] {};
+        } else if (clazz == long.class) {
+            obj = new long[] {};
+        } else if (clazz == float.class) {
+            obj = new float[] {};
+        } else if (clazz == double.class) {
+            obj = new double[] {};
+        } else if (clazz == boolean.class) {
+            obj = new boolean[] {};
+        } else if (clazz == char.class) {
+            obj = new char[] {};
+        } else if (clazz == Byte.class) {
+            obj = new Byte[] {};
+        } else if (clazz == Short.class) {
+            obj = new Short[] {};
+        } else if (clazz == Integer.class) {
+            obj = new Integer[] {};
+        } else if (clazz == Long.class) {
+            obj = new Long[] {};
+        } else if (clazz == Float.class) {
+            obj = new Float[] {};
+        } else if (clazz == Double.class) {
+            obj = new Double[] {};
+        } else if (clazz == Boolean.class) {
+            obj = new Boolean[] {};
+        } else if (clazz == Character.class) {
+            obj = new Character[] {};
+        } else if (clazz == String.class) {
+            obj = new String[] {};
         }
-
-        while(k.contains(".")){
-          if (k.contains(".")){
-            String subkey = k.substring(0, k.indexOf("."));
-            k = k.substring(k.indexOf(".")+1);
-            if (!map.containsKey(subkey)){
-              map.put(subkey, map=new HashMap<>());
-            }else{
-              map = (Map)map.get(subkey);
+        return (T[]) obj;
+    }
+
+    private <T> Collection<T> convert(String commaSaperatedValues, Class<T> clazz, int processingHints) {
+        ArrayList<T> collection = new ArrayList<>();
+        for (String value : commaSaperatedValues.split(",")) {
+            try {
+                T type1 = getValue(value, clazz, processingHints);
+                if (type1 != null) {
+                    collection.add(type1);
+                }
+            } catch (RuntimeException re) {
+                // do nothing
             }
-          }
         }
-        map.put(k, value);
-      }
-    }catch (Exception e){
-      e.printStackTrace();
+        return collection;
     }
-    return parentMap;
-  }
-
 
+    public void shutdown() {
+        if (changeNotifier != null) {
+            try {
+                changeNotifier.shutdown();
+            } catch (Exception exception) {
+                exception.printStackTrace();
+            }
+        }
+    }
 
 
 }
index 90346d1..276dbe2 100644 (file)
@@ -23,7 +23,6 @@ import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Set;
@@ -37,354 +36,190 @@ import org.apache.commons.configuration2.ex.ConfigurationException;
 import org.onap.config.ConfigurationUtils;
 import org.onap.config.Constants;
 
-/**
- * The type Configuration repository.
- */
 public final class ConfigurationRepository {
 
-  /**
-   * The Repo.
-   */
-  static ConfigurationRepository repo;
-  private static Set<String> validCallers = Collections.unmodifiableSet(new HashSet<>(Arrays
-      .asList(ConfigurationChangeNotifier.NotificationData.class.getName(),
-          ConfigurationUtils.class.getName(), CliConfigurationImpl.class.getName(),
-          ConfigurationChangeNotifier.class.getName(),
-          ConfigurationImpl.class.getName())));
-
-  static {
-    repo = new ConfigurationRepository();
-  }
-
-  private boolean dbAccessible = true;
-  private Set<String> tenants = new HashSet<>();
-  private Set<String> namespaces = new HashSet<>();
-  private LinkedHashMap<String, ConfigurationHolder> store =
-      new LinkedHashMap<String, ConfigurationHolder>(16, 0.75f, true) {
-        @Override
-        protected boolean removeEldestEntry(Map.Entry eldest) {
-          try {
-            return size() > getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
-                .getInt("config.size.max");
-          } catch (Exception exception) {
-            return false;
-          }
+    private static final ConfigurationRepository repo;
+
+    private static final Set<String> validCallers = Collections.unmodifiableSet(new HashSet<>(
+            Arrays.asList(ConfigurationChangeNotifier.NotificationData.class.getName(),
+                    ConfigurationUtils.class.getName(), CliConfigurationImpl.class.getName(),
+                    ConfigurationChangeNotifier.class.getName(), ConfigurationImpl.class.getName())));
+
+    static {
+        repo = new ConfigurationRepository();
+    }
+
+    private final Set<String> tenants = new HashSet<>();
+    private final Set<String> namespaces = new HashSet<>();
+    private final LinkedHashMap<String, ConfigurationHolder> store =
+            new LinkedHashMap<String, ConfigurationHolder>(16, 0.75f, true) {
+                @Override
+                protected boolean removeEldestEntry(Map.Entry eldest) {
+                    try {
+                        return size() > getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
+                                                .getInt("config.size.max");
+                    } catch (Exception exception) {
+                        return false;
+                    }
+                }
+            };
+
+    private ConfigurationRepository() {
+        if (repo != null) {
+            throw new RuntimeException("Illegal access to configuration.");
         }
-      };
-
-  private ConfigurationRepository() {
-    if (repo != null) {
-      throw new RuntimeException("Illegal access to configuration.");
+        tenants.add(Constants.DEFAULT_TENANT);
+        namespaces.add(Constants.DEFAULT_NAMESPACE);
     }
-    tenants.add(Constants.DEFAULT_TENANT);
-    namespaces.add(Constants.DEFAULT_NAMESPACE);
-  }
 
-  /**
-   * Lookup configuration repository.
-   *
-   * @return the configuration repository
-   */
-  public static ConfigurationRepository lookup() {
-    if (validCallers.contains(Thread.currentThread().getStackTrace()[2].getClassName())) {
-      return repo;
+    public static ConfigurationRepository lookup() {
+        if (validCallers.contains(Thread.currentThread().getStackTrace()[2].getClassName())) {
+            return repo;
+        }
+        return null;
     }
-    return null;
-  }
-
-  /**
-   * Gets tenants.
-   *
-   * @return the tenants
-   */
-  public Set<String> getTenants() {
-    return tenants;
-  }
-
-  /**
-   * Gets namespaces.
-   *
-   * @return the namespaces
-   */
-  public Set<String> getNamespaces() {
-    return namespaces;
-  }
 
-  private void populateTenantsNamespace(String key, boolean sourcedFromDb) {
-    String[] array = key.split(Constants.KEY_ELEMENTS_DELEMETER);
-    if (!array[1].equalsIgnoreCase(Constants.DB_NAMESPACE)) {
-      if (!sourcedFromDb) {
-        dbAccessible = false;
-      }
-      tenants.add(array[0]);
-      namespaces.add(array[1]);
+    public Set<String> getTenants() {
+        return tenants;
     }
-  }
 
-  /**
-   * Init tenants and namespaces.
-   */
-  public void initTenantsAndNamespaces() {
-    // nothing to do here, left for backward compatibility
-  }
-
-  /**
-   * Is valid tenant boolean.
-   *
-   * @param tenant the tenant
-   * @return the boolean
-   */
-  public boolean isValidTenant(String tenant) {
-    return tenant != null && tenants.contains(tenant.toUpperCase());
-  }
-
-  /**
-   * Is valid namespace boolean.
-   *
-   * @param namespace the namespace
-   * @return the boolean
-   */
-  public boolean isValidNamespace(String namespace) {
-    return namespace != null && namespaces.contains(namespace.toUpperCase());
-  }
-
-  /**
-   * Gets configuration for.
-   *
-   * @param tenant    the tenant
-   * @param namespace the namespace
-   * @return the configuration for
-   * @throws Exception the exception
-   */
-  public Configuration getConfigurationFor(String tenant, String namespace) throws Exception {
-    ConfigurationHolder config;
-    String module = tenant + Constants.KEY_ELEMENTS_DELEMETER + namespace;
-    config = store.get(module);
-    if (config == null) {
-      config = new ConfigurationHolder(new BasicConfigurationBuilder<>(AgglomerateConfiguration.class));
-      store.put(module, config);
+    public Set<String> getNamespaces() {
+        return namespaces;
     }
-    return config.getConfiguration(tenant + Constants.KEY_ELEMENTS_DELEMETER + namespace);
-  }
 
-  /**
-   * Populate configurtaion.
-   *
-   * @param key     the key
-   * @param builder the builder
-   */
-  public void populateConfigurtaion(String key, Configuration builder) {
-    store.put(key, new ConfigurationHolder(builder));
-    populateTenantsNamespace(key, false);
-  }
 
-  /**
-   * Populate override configurtaion.
-   *
-   * @param key  the key
-   * @param file the file
-   * @throws Exception the exception
-   */
-  public void populateOverrideConfigurtaion(String key, File file) {
-    ConfigurationHolder holder = store.get(key);
-    if (holder == null) {
-        holder = new ConfigurationHolder(new CombinedConfiguration());
-      store.put(key, holder);
+    public boolean isValidTenant(String tenant) {
+        return tenant != null && tenants.contains(tenant.toUpperCase());
     }
-    holder.addOverrideConfiguration(file.getAbsolutePath(),
-        ConfigurationUtils.getConfigurationBuilder(file, true));
-    populateTenantsNamespace(key, true);
-  }
 
-  /**
-   * Refresh override configurtaion for.
-   *
-   * @param key   the key
-   * @param index the index
-   * @throws Exception the exception
-   */
-  public void refreshOverrideConfigurtaionFor(String key, int index) {
-    ConfigurationHolder holder = store.get(key);
-    if (holder != null) {
-      holder.refreshOverrideConfiguration(index);
+    public boolean isValidNamespace(String namespace) {
+        return namespace != null && namespaces.contains(namespace.toUpperCase());
     }
-  }
 
-  /**
-   * Remove override configurtaion.
-   *
-   * @param file the file
-   * @throws Exception the exception
-   */
-  public void removeOverrideConfigurtaion(File file) throws Exception {
-    Iterator<String> iterator = new ArrayList(store.keySet()).iterator();
-    while (iterator.hasNext()) {
-      ConfigurationHolder holder = store.get(iterator.next());
-      if (holder.containsOverrideConfiguration(file.getAbsolutePath())) {
-        holder.removeOverrideConfiguration(file.getAbsolutePath());
-      }
+    public Configuration getConfigurationFor(String tenant, String namespace) throws Exception {
+        ConfigurationHolder config;
+        String module = tenant + Constants.KEY_ELEMENTS_DELIMETER + namespace;
+        config = store.get(module);
+        if (config == null) {
+            config = new ConfigurationHolder(new BasicConfigurationBuilder<>(AgglomerateConfiguration.class));
+            store.put(module, config);
+        }
+        return config.getConfiguration(tenant + Constants.KEY_ELEMENTS_DELIMETER + namespace);
     }
 
-  }
-
-  private class ConfigurationHolder {
-
-    /**
-     * The Builder.
-     */
-    BasicConfigurationBuilder<Configuration> builder;
-    /**
-     * The Last configuration build time.
-     */
-    Timestamp lastConfigurationBuildTime;
-    /**
-     * The Config.
-     */
-    Configuration config;
-    /**
-     * The Composite.
-     */
-    Configuration composite;
-    /**
-     * The Last config change timestamp.
-     */
-    Timestamp lastConfigChangeTimestamp;
-    private Map<String, FileBasedConfigurationBuilder<FileBasedConfiguration>>
-        overrideConfiguration = new LinkedHashMap<>();
-
-
-    /**
-     * Instantiates a new Configuration holder.
-     *
-     * @param builder the builder
-     */
-    public ConfigurationHolder(BasicConfigurationBuilder builder) {
-      this.builder = builder;
+    public void populateConfiguration(String key, Configuration builder) {
+        store.put(key, new ConfigurationHolder(builder));
+        populateTenantsNamespace(key, false);
     }
 
-    /**
-     * Instantiates a new Configuration holder.
-     *
-     * @param builder the builder
-     */
-    public ConfigurationHolder(Configuration builder) {
-      this.config = builder;
+    private void populateTenantsNamespace(String key, boolean sourcedFromDb) {
+        String[] array = key.split(Constants.KEY_ELEMENTS_DELIMETER);
+        if (!array[1].equalsIgnoreCase(Constants.DB_NAMESPACE)) {
+            tenants.add(array[0]);
+            namespaces.add(array[1]);
+        }
     }
 
-    /**
-     * Refresh override configuration.
-     *
-     * @param index the index
-     */
-    public void refreshOverrideConfiguration(int index) {
-      int count = -1;
-      for (FileBasedConfigurationBuilder overrides : overrideConfiguration.values()) {
-        try {
-          if (++count == index) {
-            overrides.save();
-            overrides.resetResult();
-          }
-        } catch (ConfigurationException exception) {
-          //do nothing
+    public void populateOverrideConfiguration(String key, File file) {
+        ConfigurationHolder holder = store.get(key);
+        if (holder == null) {
+            holder = new ConfigurationHolder(new CombinedConfiguration());
+            store.put(key, holder);
         }
-      }
+        holder.addOverrideConfiguration(file.getAbsolutePath(), ConfigurationUtils.getConfigurationBuilder(file, true));
+        populateTenantsNamespace(key, true);
     }
 
-    /**
-     * Add override configuration.
-     *
-     * @param path    the path
-     * @param builder the builder
-     */
-    public void addOverrideConfiguration(String path,
-                                     BasicConfigurationBuilder<FileBasedConfiguration> builder) {
-      overrideConfiguration.put(path.toUpperCase(), (FileBasedConfigurationBuilder) builder);
-      getEffectiveConfiguration(config, overrideConfiguration.values());
+    public void refreshOverrideConfigurationFor(String key, int index) {
+        ConfigurationHolder holder = store.get(key);
+        if (holder != null) {
+            holder.refreshOverrideConfiguration(index);
+        }
     }
 
-    /**
-     * Remove override configuration.
-     *
-     * @param path the path
-     */
-    public void removeOverrideConfiguration(String path) {
-      overrideConfiguration.remove(path.toUpperCase());
-      getEffectiveConfiguration(config, overrideConfiguration.values());
+    public void removeOverrideConfiguration(File file) {
+        for (String s : (Iterable<String>) new ArrayList(store.keySet())) {
+            ConfigurationHolder holder = store.get(s);
+            if (holder.containsOverrideConfiguration(file.getAbsolutePath())) {
+                holder.removeOverrideConfiguration(file.getAbsolutePath());
+            }
+        }
     }
 
-    /**
-     * Contains override configuration boolean.
-     *
-     * @param path the path
-     * @return the boolean
-     */
-    public boolean containsOverrideConfiguration(String path) {
-      return overrideConfiguration.containsKey(path.toUpperCase());
-    }
+    private class ConfigurationHolder {
 
-    /**
-     * Gets configuration.
-     *
-     * @param namespace the namespace
-     * @return the configuration
-     * @throws Exception the exception
-     */
-    public Configuration getConfiguration(String namespace) throws Exception {
-      if (config == null) {
-        config = builder.getConfiguration();
-        lastConfigurationBuildTime = new Timestamp(System.currentTimeMillis());
-      } else if (lastConfigurationBuildTime != null
-          && System.currentTimeMillis() - lastConfigurationBuildTime.getTime()
-          > getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
-                  .getInt("config.refresh.interval")) {
-        Timestamp temp = getLastUpdateTimestampFor(namespace);
-        if ((temp != null)
-            && (lastConfigChangeTimestamp == null
-            || temp.getTime() > lastConfigChangeTimestamp.getTime())) {
-          builder.resetResult();
-          config = builder.getConfiguration();
-          lastConfigChangeTimestamp = temp;
-          getEffectiveConfiguration(config, overrideConfiguration.values());
+        private final Map<String, FileBasedConfigurationBuilder<FileBasedConfiguration>> overrideConfiguration =
+                new LinkedHashMap<>();
+        BasicConfigurationBuilder<Configuration> builder;
+        Timestamp lastConfigurationBuildTime;
+        Configuration config;
+        Configuration composite;
+
+        public ConfigurationHolder(BasicConfigurationBuilder builder) {
+            this.builder = builder;
         }
-        lastConfigurationBuildTime = new Timestamp(System.currentTimeMillis());
-      }
-      if (composite == null && overrideConfiguration.size() != 0) {
-        composite = getEffectiveConfiguration(config, overrideConfiguration.values());
-      }
-      return overrideConfiguration.size() == 0 ? config : composite;
-    }
 
-    private Configuration getEffectiveConfiguration(Configuration configuration,
-                    Collection<FileBasedConfigurationBuilder<FileBasedConfiguration>> list) {
-      try {
-        CompositeConfiguration cc = new CompositeConfiguration();
-        for (FileBasedConfigurationBuilder<FileBasedConfiguration> b : list) {
-          cc.addConfiguration(b.getConfiguration());
+        public ConfigurationHolder(Configuration builder) {
+            this.config = builder;
         }
-        cc.addConfiguration(configuration);
-        composite = cc;
-        return composite;
-      } catch (Exception exception) {
-        return null;
-      }
-    }
 
-    /**
-     * Gets last update timestamp for.
-     *
-     * @param namespace the namespace
-     * @return the last update timestamp for
-     */
-    public Timestamp getLastUpdateTimestampFor(String namespace) {
-      return null;
-    }
+        public void refreshOverrideConfiguration(int index) {
+            int count = -1;
+            for (FileBasedConfigurationBuilder overrides : overrideConfiguration.values()) {
+                try {
+                    if (++count == index) {
+                        overrides.save();
+                        overrides.resetResult();
+                    }
+                } catch (ConfigurationException exception) {
+                    //do nothing
+                }
+            }
+        }
 
+        public void addOverrideConfiguration(String path, BasicConfigurationBuilder<FileBasedConfiguration> builder) {
+            overrideConfiguration.put(path.toUpperCase(), (FileBasedConfigurationBuilder) builder);
+            getEffectiveConfiguration(config, overrideConfiguration.values());
+        }
 
-  }
+        private Configuration getEffectiveConfiguration(Configuration configuration,
+                Collection<FileBasedConfigurationBuilder<FileBasedConfiguration>> list) {
+            try {
+                CompositeConfiguration cc = new CompositeConfiguration();
+                for (FileBasedConfigurationBuilder<FileBasedConfiguration> b : list) {
+                    cc.addConfiguration(b.getConfiguration());
+                }
+                cc.addConfiguration(configuration);
+                composite = cc;
+                return composite;
+            } catch (Exception exception) {
+                return null;
+            }
+        }
 
-  public boolean isDBAccessible(){
-    return dbAccessible;
-  }
+        public void removeOverrideConfiguration(String path) {
+            overrideConfiguration.remove(path.toUpperCase());
+            getEffectiveConfiguration(config, overrideConfiguration.values());
+        }
 
+        public boolean containsOverrideConfiguration(String path) {
+            return overrideConfiguration.containsKey(path.toUpperCase());
+        }
 
+        public Configuration getConfiguration(String namespace) throws Exception {
+            if (config == null) {
+                config = builder.getConfiguration();
+                lastConfigurationBuildTime = new Timestamp(System.currentTimeMillis());
+            } else if (lastConfigurationBuildTime != null
+                               && System.currentTimeMillis() - lastConfigurationBuildTime.getTime()
+                                          > getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
+                                                    .getInt("config.refresh.interval")) {
+                lastConfigurationBuildTime = new Timestamp(System.currentTimeMillis());
+            }
+            if (composite == null && overrideConfiguration.size() != 0) {
+                composite = getEffectiveConfiguration(config, overrideConfiguration.values());
+            }
+            return overrideConfiguration.size() == 0 ? config : composite;
+        }
+    }
 }
index cc31e77..9431e12 100644 (file)
@@ -1,29 +1,44 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.impl;
 
-import org.onap.config.api.ConfigurationManager;
+import static org.onap.config.Constants.MBEAN_NAME;
 
+import java.lang.management.ManagementFactory;
 import javax.management.ObjectName;
 import javax.servlet.ServletContextEvent;
 import javax.servlet.ServletContextListener;
 import javax.servlet.annotation.WebListener;
-import java.lang.management.ManagementFactory;
-
-import static org.onap.config.Constants.MBEAN_NAME;
+import org.onap.config.api.ConfigurationManager;
 
 @WebListener
 public class ContextListener implements ServletContextListener {
 
-  @Override
-  public void contextDestroyed(ServletContextEvent arg0) {
-    try {
-      ManagementFactory.getPlatformMBeanServer().unregisterMBean(new ObjectName(MBEAN_NAME));
-    } catch (Exception exception) {
-      exception.printStackTrace();
+    @Override
+    public void contextInitialized(ServletContextEvent arg0) {
+        ConfigurationManager.lookup();
     }
-  }
 
-  @Override
-  public void contextInitialized(ServletContextEvent arg0) {
-    ConfigurationManager.lookup();
-  }
+    @Override
+    public void contextDestroyed(ServletContextEvent arg0) {
+        try {
+            ManagementFactory.getPlatformMBeanServer().unregisterMBean(new ObjectName(MBEAN_NAME));
+        } catch (Exception exception) {
+            exception.printStackTrace();
+        }
+    }
 }
index dc6785f..bdaf219 100644 (file)
@@ -1,3 +1,19 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.impl;
 
 import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
@@ -7,12 +23,12 @@ import org.apache.commons.configuration2.tree.ImmutableNode;
 
 public class YamlConfiguration extends JacksonConfiguration {
 
-  protected YamlConfiguration(HierarchicalConfiguration<ImmutableNode> config) {
-    super(new YAMLFactory(), config);
-  }
+    protected YamlConfiguration(HierarchicalConfiguration<ImmutableNode> config) {
+        super(new YAMLFactory(), config);
+    }
 
-  public YamlConfiguration() {
-    super(new YAMLFactory());
-  }
+    public YamlConfiguration() {
+        super(new YAMLFactory());
+    }
 
 }
index 826d53e..8293aba 100644 (file)
@@ -1,5 +1,21 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.type;
 
 public enum ConfigurationMode {
-  OVERRIDE, UNION, MERGE
+    OVERRIDE, UNION, MERGE
 }
index 6aec7c2..faefdb0 100644 (file)
@@ -1,94 +1,98 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.type;
 
 import org.onap.config.Constants;
 
 public class ConfigurationQuery {
 
-  String tenant = Constants.DEFAULT_TENANT;
-  String namespace = Constants.DEFAULT_NAMESPACE;
-  String key;
-  boolean fallback;
-  boolean externalLookup;
-  boolean latest;
-  private boolean nodeSpecific;
-
-  public ConfigurationQuery fallback(boolean fallback) {
-    this.fallback = fallback;
-    return this;
-  }
-
-  public ConfigurationQuery latest(boolean val) {
-    this.latest = val;
-    return this;
-  }
-
-  public ConfigurationQuery nodeSpecific(boolean val) {
-    this.nodeSpecific = val;
-    return this;
-  }
-
-  public ConfigurationQuery externalLookup(boolean val) {
-    this.externalLookup = val;
-    return this;
-  }
-
-  /**
-   * Tenant configuration query.
-   *
-   * @param id the id
-   * @return the configuration query
-   */
-  public ConfigurationQuery tenant(String id) {
-    if (id != null) {
-      tenant = id;
+    private String tenant = Constants.DEFAULT_TENANT;
+    private String namespace = Constants.DEFAULT_NAMESPACE;
+    private String key;
+    private boolean fallback;
+    private boolean externalLookup;
+    private boolean latest;
+    private boolean nodeSpecific;
+
+    public ConfigurationQuery fallback(boolean fallback) {
+        this.fallback = fallback;
+        return this;
     }
-    return this;
-  }
-
-
-  /**
-   * Namespace configuration query.
-   *
-   * @param id the id
-   * @return the configuration query
-   */
-  public ConfigurationQuery namespace(String id) {
-    if (id != null) {
-      namespace = id;
+
+    public ConfigurationQuery latest(boolean val) {
+        this.latest = val;
+        return this;
     }
-    return this;
-  }
 
-  public ConfigurationQuery key(String id) {
-    key = id;
-    return this;
-  }
+    public ConfigurationQuery nodeSpecific(boolean val) {
+        this.nodeSpecific = val;
+        return this;
+    }
+
+    public ConfigurationQuery externalLookup(boolean val) {
+        this.externalLookup = val;
+        return this;
+    }
 
-  public String getTenant() {
-    return tenant.toUpperCase();
-  }
+    public ConfigurationQuery tenant(String id) {
+        if (id != null) {
+            tenant = id;
+        }
+        return this;
+    }
 
-  public String getNamespace() {
-    return namespace.toUpperCase();
-  }
 
-  public String getKey() {
-    return key;
-  }
+    public ConfigurationQuery namespace(String id) {
+        if (id != null) {
+            namespace = id;
+        }
+        return this;
+    }
 
-  public boolean isFallback() {
-    return fallback;
-  }
+    public ConfigurationQuery key(String id) {
+        key = id;
+        return this;
+    }
 
-  public boolean isNodeSpecific() {
-    return nodeSpecific;
-  }
+    public String getTenant() {
+        return tenant.toUpperCase();
+    }
 
-  public boolean isExternalLookup() {
-    return externalLookup;
-  }
+    public String getNamespace() {
+        return namespace.toUpperCase();
+    }
 
-  public boolean isLatest() {
-    return latest;
-  }
+    public String getKey() {
+        return key;
+    }
+
+    public boolean isFallback() {
+        return fallback;
+    }
+
+    public boolean isNodeSpecific() {
+        return nodeSpecific;
+    }
+
+    public boolean isExternalLookup() {
+        return externalLookup;
+    }
+
+    public boolean isLatest() {
+        return latest;
+    }
 }
index 54253fa..3fd4865 100644 (file)
@@ -1,5 +1,21 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.type;
 
 public enum ConfigurationType {
-  PROPERTIES, XML, JSON, YAML
+    PROPERTIES, XML, JSON, YAML
 }
index 739dd77..f14b4ec 100644 (file)
@@ -1,33 +1,45 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.type;
 
 public class ConfigurationUpdate extends ConfigurationQuery {
-  private String value;
-  private boolean nodeOverride;
-
-  public ConfigurationUpdate value(String val) {
-    value = val;
-    return this;
-  }
-
-  public ConfigurationUpdate nodeOverride(boolean val) {
-    nodeOverride = val;
-    return this;
-  }
-
-  /**
-   * Gets value.
-   *
-   * @return the value
-   */
-  public String getValue() {
-    if (value != null && value.split(",").length > 1 && !value.matches("^\\[.*\\]$")) {
-      return "[" + value + "]";
+
+    private String value;
+    private boolean nodeOverride;
+
+    public ConfigurationUpdate value(String val) {
+        value = val;
+        return this;
+    }
+
+    public ConfigurationUpdate nodeOverride(boolean val) {
+        nodeOverride = val;
+        return this;
+    }
+
+    public String getValue() {
+        if (value != null && value.split(",").length > 1 && !value.matches("^\\[.*\\]$")) {
+            return "[" + value + "]";
+        }
+        return value;
     }
-    return value;
-  }
 
-  public boolean isNodeOverride() {
-    return nodeOverride;
-  }
+    public boolean isNodeOverride() {
+        return nodeOverride;
+    }
 
 }
index cfe91e6..f8222a3 100644 (file)
@@ -1,22 +1,3 @@
-driverClassName=com.github.adejanovski.cassandra.jdbc.CassandraDriver
-jdbcURL=jdbc:${dbname}://${dbhost}:${dbport}/${configdb}
-dbuser=
-dbpassword=
-config.Table=configuration
-config.monitor.Table=configuration_change
-configKey=key
-configValue=value
-configNameColumn=name
-configdb=dox
-dbhost=
-dbport=9042
-dbname=cassandra
-createtablecql=create table if not exists ${configdb}.${config.Table} (name text\, key text\, value text\, PRIMARY KEY (name\, key)) with clustering order by (key asc)
-createmonitoringtablecql=create table if not exists ${configdb}.${config.monitor.Table} (name text\, changed_when bigint\, key text\, old_value text\, new_value text\, PRIMARY KEY (name\, changed_when)) with clustering order by (changed_when desc)
-insertconfigurationchangecql=insert into ${configdb}.${config.monitor.Table} (name\, changed_when\, key\, old_value\, new_value) values(?\, ?\, ?\, ?\, ?)
-fetchkeysql=select ${configKey} from ${config.Table} where ${configNameColumn}=?
-fetchlastchangecql=select changed_when from ${configdb}.${config.monitor.Table} where name=? limit 1
-fetchnamescql=select distinct name from ${configdb}.${config.Table}
 config.size.max=100
 config.refresh.interval=30000
 event.fetch.delay=5000
\ No newline at end of file
index 9360ce1..6c46016 100755 (executable)
@@ -18,44 +18,32 @@ package org.onap.config;
 
 import org.junit.runner.RunWith;
 import org.junit.runners.Suite;
-import org.onap.config.test.CLIFallbackAndLookupTest;
+import org.onap.config.test.CliFallbackAndLookupTest;
 import org.onap.config.test.CliTest;
 import org.onap.config.test.ConfigSourceLocationTest;
 import org.onap.config.test.FallbackConfigTest;
-import org.onap.config.test.FallbackToGlobalNSTest;
-import org.onap.config.test.GlobalAndNSConfigTest;
-import org.onap.config.test.JAVAPropertiesConfigTest;
-import org.onap.config.test.JSONConfigTest;
+import org.onap.config.test.FallbackToGlobalNamespaceTest;
+import org.onap.config.test.GlobalAndNamespaceConfigTest;
+import org.onap.config.test.JavaPropertiesConfigTest;
+import org.onap.config.test.JsonConfigTest;
 import org.onap.config.test.LoadOrderMergeAndOverrideTest;
 import org.onap.config.test.ModeAsConfigPropTest;
 import org.onap.config.test.MultiTenancyConfigTest;
 import org.onap.config.test.NodeSpecificCliTest;
 import org.onap.config.test.ValidateDefaultModeTest;
-import org.onap.config.test.XMLConfigTest;
-import org.onap.config.test.YAMLConfigTest;
+import org.onap.config.test.XmlConfigTest;
+import org.onap.config.test.YamlConfigTest;
 
 /**
  * Created by sheetalm on 10/25/2016.
  */
-
 @RunWith(Suite.class)
-@Suite.SuiteClasses({
-        ConfigurationUtilsTest.class,
-        JAVAPropertiesConfigTest.class,
-        JSONConfigTest.class,
-        XMLConfigTest.class,
-        YAMLConfigTest.class,
-        CLIFallbackAndLookupTest.class,
-        CliTest.class,
-        ConfigSourceLocationTest.class,
-        FallbackConfigTest.class,
-        FallbackToGlobalNSTest.class,
-        GlobalAndNSConfigTest.class,
-        ModeAsConfigPropTest.class,
-        MultiTenancyConfigTest.class,
-        NodeSpecificCliTest.class,
-        ValidateDefaultModeTest.class,
-        LoadOrderMergeAndOverrideTest.class})
+@Suite.SuiteClasses(
+        {ConfigurationUtilsTest.class, JavaPropertiesConfigTest.class, JsonConfigTest.class, XmlConfigTest.class,
+                YamlConfigTest.class, CliFallbackAndLookupTest.class, CliTest.class, ConfigSourceLocationTest.class,
+                FallbackConfigTest.class, FallbackToGlobalNamespaceTest.class, GlobalAndNamespaceConfigTest.class,
+                ModeAsConfigPropTest.class, MultiTenancyConfigTest.class, NodeSpecificCliTest.class,
+                ValidateDefaultModeTest.class, LoadOrderMergeAndOverrideTest.class})
 public class TestCMSuite extends junit.framework.TestSuite {
 
     private TestCMSuite() {
@@ -1,5 +1,28 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.test;
 
+import java.io.IOException;
+import java.lang.management.ManagementFactory;
+import java.util.HashMap;
+import java.util.Map;
+import javax.management.JMX;
+import javax.management.MBeanServerConnection;
+import javax.management.ObjectName;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -9,15 +32,6 @@ import org.onap.config.api.ConfigurationManager;
 import org.onap.config.util.ConfigTestConstant;
 import org.onap.config.util.TestUtil;
 
-import javax.management.JMX;
-import javax.management.MBeanServerConnection;
-import javax.management.ObjectName;
-import java.io.IOException;
-import java.lang.management.ManagementFactory;
-import java.util.HashMap;
-import java.util.Map;
-
-
 
 /**
  * Created by sheetalm on 10/18/2016.
@@ -25,10 +39,10 @@ import java.util.Map;
  * 21 - Verify the CLI fetches only the current value unless the fallback option is specified
  * 23 - Fetch value using CLI for a key with underlying resource
  */
-public class CLIFallbackAndLookupTest {
+public class CliFallbackAndLookupTest {
 
-    public final static String NAMESPACE = "CLIFallback";
-    public final static String TENANT = "OPENECOMP";
+    private static final String NAMESPACE = "CLIFallback";
+    private static final String TENANT = "OPENECOMP";
 
     @Before
     public void setUp() throws IOException {
@@ -37,7 +51,7 @@ public class CLIFallbackAndLookupTest {
     }
 
     @Test
-    public void testCLIFallbackAndLookup() throws Exception{
+    public void testCliFallbackAndLookup() throws Exception {
 
         //Verify without fallback
         Map<String, Object> input = new HashMap<>();
@@ -50,19 +64,19 @@ public class CLIFallbackAndLookupTest {
         ObjectName mbeanName = new ObjectName(Constants.MBEAN_NAME);
         ConfigurationManager conf = JMX.newMBeanProxy(mbsc, mbeanName, ConfigurationManager.class, true);
         String maxSizeWithNoFallback = conf.getConfigurationValue(input);
-        Assert.assertEquals("",maxSizeWithNoFallback);
+        Assert.assertEquals("", maxSizeWithNoFallback);
 
         //Verify underlying resource without lookup switch
         input.put("key", ConfigTestConstant.ARTIFACT_JSON_SCHEMA);
         String jsonSchema = conf.getConfigurationValue(input);
-        System.out.println("jsonSchema=="+jsonSchema);
-        Assert.assertEquals("@"+System.getProperty("user.home")+"/TestResources/GeneratorsList.json" , jsonSchema);
+        System.out.println("jsonSchema==" + jsonSchema);
+        Assert.assertEquals("@" + System.getProperty("user.home") + "/TestResources/GeneratorsList.json", jsonSchema);
 
         //Verify underlying resource with lookup switch
         input.put("externalLookup", true);
         jsonSchema = conf.getConfigurationValue(input);
-        System.out.println("jsonSchema=="+jsonSchema);
-        Assert.assertEquals("{name:\"SCM\"}" , jsonSchema);
+        System.out.println("jsonSchema==" + jsonSchema);
+        Assert.assertEquals("{name:\"SCM\"}", jsonSchema);
 
         //Verify with fallback
         Map<String, Object> fallbackInput = new HashMap<>();
@@ -73,11 +87,11 @@ public class CLIFallbackAndLookupTest {
         fallbackInput.put("key", ConfigTestConstant.ARTIFACT_MAXSIZE);
 
         String maxSizeWithFallback = conf.getConfigurationValue(fallbackInput);
-        Assert.assertEquals("1024",maxSizeWithFallback);
+        Assert.assertEquals("1024", maxSizeWithFallback);
     }
 
     @After
     public void tearDown() throws Exception {
-      TestUtil.cleanUp();
+        TestUtil.cleanUp();
     }
 }
index c997e09..f291f8e 100644 (file)
@@ -1,5 +1,26 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.test;
 
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Properties;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -9,21 +30,15 @@ import org.onap.config.api.ConfigurationManager;
 import org.onap.config.util.ConfigTestConstant;
 import org.onap.config.util.TestUtil;
 
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Properties;
-
 /**
  * Created by sheetalm on 10/14/2016.
  * Scenario 11
- * Validate conventional and configurational source location
- *
+ * Validate conventional and configurational source location.
  * Pre-requisite - set -Dconfig.location=${"user.home"}/TestResources/ while running test
  */
 public class ConfigSourceLocationTest {
-    public final static String NAMESPACE = "SourceLocation";
+
+    private static final String NAMESPACE = "SourceLocation";
 
     @Before
     public void setUp() throws IOException {
@@ -40,7 +55,7 @@ public class ConfigSourceLocationTest {
     }
 
     @Test
-    public void testMergeStrategyInConfig() throws IOException, InterruptedException {
+    public void testMergeStrategyInConfig() {
         Configuration config = ConfigurationManager.lookup();
         Assert.assertEquals("a-zA-Z_0-9", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_UPPER));
         Assert.assertEquals("1024", config.getAsString(ConfigTestConstant.ARTIFACT_MAXSIZE));
index 17b4aee..876aed0 100644 (file)
@@ -1,22 +1,36 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.test;
 
+import static org.onap.config.util.TestUtil.validateConfiguration;
+import static org.onap.config.util.TestUtil.writeFile;
+
+import java.io.IOException;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.io.IOException;
-
-import static org.onap.config.util.TestUtil.validateConfiguraton;
-import static org.onap.config.util.TestUtil.writeFile;
-
 /**
  * Created by ARR on 10/14/2016.
- *
- * Validate configuration with properties,xml,json,yaml file format with mode
+ * Validate configuration with properties,xml,json,yaml file format with mode.
  */
 public class FallbackConfigTest {
 
-    public static final String NAMESPACE = "fallback";
+    private static final String NAMESPACE = "fallback";
 
     @Before
     public void setUp() throws IOException {
@@ -25,14 +39,13 @@ public class FallbackConfigTest {
     }
 
     @Test
-    public void testConfigurationWithFallbackFileFormat(){
-        validateConfiguraton(NAMESPACE);
+    public void testConfigurationWithFallbackFileFormat() {
+        validateConfiguration(NAMESPACE);
     }
 
     @After
     public void tearDown() throws Exception {
         String data = "{name:\"SCM\"}";
         writeFile(data);
-        //ConfigurationUtils.executeDDLSQL("truncate dox.configuration");
     }
 }
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/FallbackToGlobalNSTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/FallbackToGlobalNSTest.java
deleted file mode 100644 (file)
index b70247b..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-package org.onap.config.test;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.config.api.Configuration;
-import org.onap.config.api.ConfigurationManager;
-import org.onap.config.util.ConfigTestConstant;
-import org.onap.config.util.TestUtil;
-
-import java.io.IOException;
-
-/**
- * Scenario 12
- * Verify configuration value fallback to the global namespace if the configuraton property doesnot exist in the namespace configuration
- * Created by sheetalm on 10/14/2016.
- */
-public class FallbackToGlobalNSTest {
-
-    public final static String NAMESPACE = "FallbackToGlobalNS";
-
-    @Before
-    public void setUp() throws IOException {
-        String data = "{name:\"SCM\"}";
-        TestUtil.writeFile(data);
-    }
-
-    @Test
-    public void testFallbackToGlobalNS() throws IOException, InterruptedException {
-        Configuration config = ConfigurationManager.lookup();
-        Assert.assertEquals("14",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH));
-        Assert.assertEquals("1024",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_MAXSIZE));
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        TestUtil.cleanUp();
-    }
-
-
-}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/FallbackToGlobalNamespaceTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/FallbackToGlobalNamespaceTest.java
new file mode 100644 (file)
index 0000000..b398a70
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.config.test;
+
+import java.io.IOException;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.config.api.Configuration;
+import org.onap.config.api.ConfigurationManager;
+import org.onap.config.util.ConfigTestConstant;
+import org.onap.config.util.TestUtil;
+
+/**
+ * Scenario 12
+ * Verify configuration value fallback to the global namespace if the configuration property does
+ * not exist in the namespace configuration.
+ * Created by sheetalm on 10/14/2016.
+ */
+public class FallbackToGlobalNamespaceTest {
+
+    private static final String NAMESPACE = "FallbackToGlobalNS";
+
+    @Before
+    public void setUp() throws IOException {
+        String data = "{name:\"SCM\"}";
+        TestUtil.writeFile(data);
+    }
+
+    @Test
+    public void testFallbackToGlobalNamespace() {
+        Configuration config = ConfigurationManager.lookup();
+        Assert.assertEquals("14", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH));
+        Assert.assertEquals("1024", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_MAXSIZE));
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        TestUtil.cleanUp();
+    }
+
+
+}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/GlobalAndNSConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/GlobalAndNSConfigTest.java
deleted file mode 100644 (file)
index e4a5110..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-package org.onap.config.test;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.config.api.Configuration;
-import org.onap.config.api.ConfigurationManager;
-import org.onap.config.util.ConfigTestConstant;
-import org.onap.config.util.TestUtil;
-
-import java.io.IOException;
-
-/**
- * Created by sheetalm on 10/13/2016.
- * Scenario 10 Verify configuration present in both global and defined namespace
- */
-public class GlobalAndNSConfigTest {
-
-    public final static String NAMESPACE = "GlobalAndNSConfig";
-
-    @Before
-    public void setUp() throws IOException {
-        String data = "{name:\"SCM\"}";
-        TestUtil.writeFile(data);
-    }
-
-    @Test
-    public void testNamespaceInConfig() throws IOException, InterruptedException {
-        Configuration config = ConfigurationManager.lookup();
-        Assert.assertEquals("a-zA-Z",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_UPPER ));
-        Assert.assertEquals("a-zA-Z_0-9",config.getAsString(ConfigTestConstant.ARTIFACT_NAME_UPPER ));
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        TestUtil.cleanUp();
-    }
-
-
-
-
-}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/GlobalAndNamespaceConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/GlobalAndNamespaceConfigTest.java
new file mode 100644 (file)
index 0000000..d66165c
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.config.test;
+
+import java.io.IOException;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.config.api.Configuration;
+import org.onap.config.api.ConfigurationManager;
+import org.onap.config.util.ConfigTestConstant;
+import org.onap.config.util.TestUtil;
+
+/**
+ * Created by sheetalm on 10/13/2016.
+ * Scenario 10 Verify configuration present in both global and defined namespace
+ */
+public class GlobalAndNamespaceConfigTest {
+
+    private static final String NAMESPACE = "GlobalAndNSConfig";
+
+    @Before
+    public void setUp() throws IOException {
+        String data = "{name:\"SCM\"}";
+        TestUtil.writeFile(data);
+    }
+
+    @Test
+    public void testNamespaceInConfig() {
+        Configuration config = ConfigurationManager.lookup();
+        Assert.assertEquals("a-zA-Z", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_UPPER));
+        Assert.assertEquals("a-zA-Z_0-9", config.getAsString(ConfigTestConstant.ARTIFACT_NAME_UPPER));
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        TestUtil.cleanUp();
+    }
+
+
+}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JAVAPropertiesConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JAVAPropertiesConfigTest.java
deleted file mode 100644 (file)
index 994bd72..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-package org.onap.config.test;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.config.util.TestUtil;
-
-import java.io.IOException;
-
-import static org.onap.config.util.TestUtil.validateConfiguraton;
-import static org.onap.config.util.TestUtil.writeFile;
-
-/**
- * Created by ARR on 10/13/2016.
- *
- * Scenario 1
- * Validate configuration with Java Properties file format with mode
- */
-public class JAVAPropertiesConfigTest {
-
-    public static final String NAMESPACE = "javaProperties";
-
-    @Before
-    public void setUp() throws IOException {
-        String data = "{name:\"SCM\"}";
-        writeFile(data);
-    }
-
-    @Test
-    public void testConfigurationWithPropertiesFileFormat(){
-        validateConfiguraton(NAMESPACE);
-    }
-
-
-
-    @After
-    public void tearDown() throws Exception {
-        TestUtil.cleanUp();
-    }
-}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JSONConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JSONConfigTest.java
deleted file mode 100644 (file)
index bf6ea5c..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-package org.onap.config.test;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.config.util.TestUtil;
-
-import java.io.IOException;
-
-import static org.onap.config.util.TestUtil.validateConfiguraton;
-import static org.onap.config.util.TestUtil.writeFile;
-
-/**
- * Created by ARR on 10/14/2016.
- *
- * Scenario 3
- * Validate configuration with JSON file format with mode
- */
-public class JSONConfigTest {
-
-    public static final String NAMESPACE = "JSONConfig";
-
-    @Before
-    public void setUp() throws IOException {
-        String data = "{name:\"SCM\"}";
-        writeFile(data);
-    }
-
-    @Test
-    public void testConfigurationWithJSONFileFormat(){
-        validateConfiguraton(NAMESPACE);
-    }
-
-
-
-    @After
-    public void tearDown() throws Exception {
-        TestUtil.cleanUp();
-    }
-}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JavaPropertiesConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JavaPropertiesConfigTest.java
new file mode 100644 (file)
index 0000000..0c82fe4
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.config.test;
+
+import static org.onap.config.util.TestUtil.validateConfiguration;
+import static org.onap.config.util.TestUtil.writeFile;
+
+import java.io.IOException;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.config.util.TestUtil;
+
+/**
+ * Created by ARR on 10/13/2016.
+ * Scenario 1
+ * Validate configuration with Java Properties file format with mode
+ */
+public class JavaPropertiesConfigTest {
+
+    private static final String NAMESPACE = "javaProperties";
+
+    @Before
+    public void setUp() throws IOException {
+        String data = "{name:\"SCM\"}";
+        writeFile(data);
+    }
+
+    @Test
+    public void testConfigurationWithPropertiesFileFormat() {
+        validateConfiguration(NAMESPACE);
+    }
+
+
+    @After
+    public void tearDown() throws Exception {
+        TestUtil.cleanUp();
+    }
+}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JsonConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/JsonConfigTest.java
new file mode 100644 (file)
index 0000000..cd3eb6a
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.config.test;
+
+import static org.onap.config.util.TestUtil.validateConfiguration;
+import static org.onap.config.util.TestUtil.writeFile;
+
+import java.io.IOException;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.config.util.TestUtil;
+
+/**
+ * Created by ARR on 10/14/2016.
+ * Scenario 3 Validate configuration with JSON file format with mode.
+ */
+public class JsonConfigTest {
+
+    private static final String NAMESPACE = "JSONConfig";
+
+    @Before
+    public void setUp() throws IOException {
+        String data = "{name:\"SCM\"}";
+        writeFile(data);
+    }
+
+    @Test
+    public void testConfigurationWithJsonFileFormat() {
+        validateConfiguration(NAMESPACE);
+    }
+
+
+    @After
+    public void tearDown() throws Exception {
+        TestUtil.cleanUp();
+    }
+}
index d179edf..6d189a0 100644 (file)
@@ -1,5 +1,24 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.test;
 
+import static org.onap.config.util.TestUtil.writeFile;
+
+import java.io.IOException;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -9,18 +28,14 @@ import org.onap.config.api.ConfigurationManager;
 import org.onap.config.util.ConfigTestConstant;
 import org.onap.config.util.TestUtil;
 
-import java.io.IOException;
-
-import static org.onap.config.util.TestUtil.writeFile;
-
 /**
  * Scenario
- * Check loadorder for merge and overide. Higher loadorder takes precedence for override
- * LoWer loadorder takes precedence for merge.
+ * Check load order for merge and override. Higher load order takes precedence for override
+ * Lower load order takes precedence for merge.
  */
 public class LoadOrderMergeAndOverrideTest {
 
-    public static final String NAMESPACE = "LoadOrderConfiguration";
+    private static final String NAMESPACE = "LoadOrderConfiguration";
 
     @Before
     public void setUp() throws IOException {
@@ -29,16 +44,15 @@ public class LoadOrderMergeAndOverrideTest {
     }
 
     @Test
-    public void testConfigurationWithPropertiesFileFormat(){
+    public void testConfigurationWithPropertiesFileFormat() {
         Configuration config = ConfigurationManager.lookup();
 
-        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH ), "14");
+        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH), "14");
         Assert.assertEquals("5", config.getAsString(NAMESPACE, "artifact.length"));
         Assert.assertEquals("56", config.getAsString(NAMESPACE, "artifact.size"));
     }
 
 
-
     @After
     public void tearDown() throws Exception {
         TestUtil.cleanUp();
index e8fe363..57f632a 100644 (file)
@@ -1,5 +1,24 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.test;
 
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -9,79 +28,72 @@ import org.onap.config.api.ConfigurationManager;
 import org.onap.config.util.ConfigTestConstant;
 import org.onap.config.util.TestUtil;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
 /**
- * Scenario 8
- * Validate configuration with mode specified as a configuration property
+ * Scenario 8 Validate configuration with mode specified as a configuration property.
  */
-
 public class ModeAsConfigPropTest {
 
-       String newValue = null;
-       
-       public final static String NAMESPACE = "ModeAsConfigProp";
-       
-       @Before
-       public void setUp() throws IOException {
-               String data = "{name:\"SCM\"}";
-               TestUtil.writeFile(data);
-       }
+    private static final String NAMESPACE = "ModeAsConfigProp";
+
+    @Before
+    public void setUp() throws IOException {
+        String data = "{name:\"SCM\"}";
+        TestUtil.writeFile(data);
+    }
 
-       @Test
-       public void testMergeStrategyInConfig() throws IOException, InterruptedException {
-               Configuration config = ConfigurationManager.lookup();
+    @Test
+    public void testMergeStrategyInConfig() {
+        Configuration config = ConfigurationManager.lookup();
 
-               Assert.assertEquals("14",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH));
+        Assert.assertEquals("14", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH));
 
-               Assert.assertEquals("1048",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_MAXSIZE));
+        Assert.assertEquals("1048", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_MAXSIZE));
 
-               List<String> expectedExtList = new ArrayList<String>();
-               expectedExtList.add("pdf");
-               expectedExtList.add("zip");
-               expectedExtList.add("xml");
-               expectedExtList.add("pdf");
-               expectedExtList.add("tgz");
-               expectedExtList.add("xls");
-               List<String> extList = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_EXT);
-               Assert.assertEquals(expectedExtList, extList);
+        List<String> expectedExtList = new ArrayList<>();
+        expectedExtList.add("pdf");
+        expectedExtList.add("zip");
+        expectedExtList.add("xml");
+        expectedExtList.add("pdf");
+        expectedExtList.add("tgz");
+        expectedExtList.add("xls");
+        List<String> extList = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_EXT);
+        Assert.assertEquals(expectedExtList, extList);
 
-               List<String> expectedEncList = new ArrayList<String>();
-               expectedEncList.add("Base64");
-               expectedEncList.add("MD5");
-               List<String> encList = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_ENC);
-               Assert.assertEquals(expectedEncList, encList);
+        List<String> expectedEncList = new ArrayList<>();
+        expectedEncList.add("Base64");
+        expectedEncList.add("MD5");
+        List<String> encList = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_ENC);
+        Assert.assertEquals(expectedEncList, encList);
 
-               String newValue = config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_JSON_SCHEMA);
-               Assert.assertEquals("{name:\"SCM\"}",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_JSON_SCHEMA));
+        Assert.assertEquals("{name:\"SCM\"}", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_JSON_SCHEMA));
 
-               Assert.assertEquals("a-zA-Z_0-9",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_UPPER ));
+        Assert.assertEquals("a-zA-Z_0-9", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_UPPER));
 
-               Assert.assertEquals("Deleted",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_STATUS) );
+        Assert.assertEquals("Deleted", config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_STATUS));
 
-               List<String> expectedLocList = new ArrayList<String>();
-               expectedLocList.add("/opt/spool");
-               expectedLocList.add(System.getProperty("user.home")+"/asdc");
-               List<String> locList = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_LOC);
-               Assert.assertEquals(expectedLocList, locList);
+        List<String> expectedLocList = new ArrayList<>();
+        expectedLocList.add("/opt/spool");
+        expectedLocList.add(System.getProperty("user.home") + "/asdc");
+        List<String> locList = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_LOC);
+        Assert.assertEquals(expectedLocList, locList);
 
-               Assert.assertEquals("@"+TestUtil.getenv(ConfigTestConstant.PATH)+"/myschema.json",config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_XML_SCHEMA));
+        Assert.assertEquals("@" + TestUtil.getenv(ConfigTestConstant.PATH) + "/myschema.json",
+                config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_XML_SCHEMA));
 
-               List<String> artifactConsumer = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_CONSUMER );
-               Assert.assertEquals(config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_CONSUMER_APPC ), artifactConsumer);
+        List<String> artifactConsumer = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_CONSUMER);
+        Assert.assertEquals(config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_CONSUMER_APPC),
+                artifactConsumer);
 
-               Assert.assertEquals(config.getAsBooleanValue(NAMESPACE, ConfigTestConstant.ARTIFACT_MANDATORY_NAME ), true);
+        Assert.assertEquals(config.getAsBooleanValue(NAMESPACE, ConfigTestConstant.ARTIFACT_MANDATORY_NAME), true);
 
-               Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MINLENGTH ), "6");
+        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MINLENGTH), "6");
 
-               Assert.assertEquals(config.getAsBooleanValue(NAMESPACE, ConfigTestConstant.ARTIFACT_ENCODED ), true);
-       }
+        Assert.assertEquals(config.getAsBooleanValue(NAMESPACE, ConfigTestConstant.ARTIFACT_ENCODED), true);
+    }
 
-       @After
-       public void tearDown() throws Exception {
-               TestUtil.cleanUp();
-       }
+    @After
+    public void tearDown() throws Exception {
+        TestUtil.cleanUp();
+    }
 
 }
index 5765c4d..03c6356 100644 (file)
@@ -1,5 +1,22 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.test;
 
+import java.io.IOException;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -9,17 +26,13 @@ import org.onap.config.api.ConfigurationManager;
 import org.onap.config.util.ConfigTestConstant;
 import org.onap.config.util.TestUtil;
 
-import java.io.IOException;
-
 /**
  * Created by ARR on 10/14/2016.
- *
- * Scenario 17
- * Verify Configuration management System - Support for Multi-Tenancy
+ * Scenario 17 - Verify Configuration management System - Support for Multi-Tenancy.
  */
 public class MultiTenancyConfigTest {
 
-    public static final String NAMESPACE = "tenancy";
+    private static final String NAMESPACE = "tenancy";
 
     @Before
     public void setUp() throws IOException {
@@ -28,14 +41,15 @@ public class MultiTenancyConfigTest {
     }
 
     @Test
-    public void testConfigurationWithMultiTenancyFileFormat(){
+    public void testConfigurationWithMultiTenancyFileFormat() {
         Configuration config = ConfigurationManager.lookup();
 
-        Assert.assertEquals(config.getAsString("OPENECOMP",NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH ), "20");
+        Assert.assertEquals(config.getAsString("OPENECOMP", NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH),
+                "20");
 
-        Assert.assertEquals(config.getAsString("Telefonica",NAMESPACE, ConfigTestConstant.ARTIFACT_STATUS ), "Deleted");
+        Assert.assertEquals(config.getAsString("Telefonica", NAMESPACE, ConfigTestConstant.ARTIFACT_STATUS), "Deleted");
 
-        Assert.assertEquals(config.getAsString("TID",NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH ), "14");
+        Assert.assertEquals(config.getAsString("TID", NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH), "14");
 
     }
 
index 3711322..d53bf27 100644 (file)
@@ -1,5 +1,26 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.test;
 
+import static org.onap.config.util.TestUtil.writeFile;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -8,21 +29,13 @@ import org.onap.config.api.Configuration;
 import org.onap.config.api.ConfigurationManager;
 import org.onap.config.util.ConfigTestConstant;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.onap.config.util.TestUtil.writeFile;
-
 /**
  * Created by ARR on 10/17/2016.
- *
- * Scenario 22
- * Validate the default mode if the mode is not set
+ * Scenario 22 - Validate the default mode if the mode is not set
  */
 public class ValidateDefaultModeTest {
 
-    public static final String NAMESPACE = "defaultmode";
+    private static final String NAMESPACE = "defaultmode";
 
     @Before
     public void setUp() throws IOException {
@@ -31,21 +44,21 @@ public class ValidateDefaultModeTest {
     }
 
     @Test
-    public void testConfigurationWithValidateDefaultMode(){
+    public void testConfigurationWithValidateDefaultMode() {
         Configuration config = ConfigurationManager.lookup();
 
-        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH ), "14");
+        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH), "14");
 
-        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_MAXSIZE ), "1048");
+        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_MAXSIZE), "1048");
 
-        List<String> expectedExtList = new ArrayList<String>();
+        List<String> expectedExtList = new ArrayList<>();
         expectedExtList.add("pdf");
         expectedExtList.add("tgz");
         expectedExtList.add("xls");
         List<String> extList = config.getAsStringValues(NAMESPACE, ConfigTestConstant.ARTIFACT_EXT);
         Assert.assertEquals(expectedExtList, extList);
 
-        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MINLENGTH ), "6");
+        Assert.assertEquals(config.getAsString(NAMESPACE, ConfigTestConstant.ARTIFACT_NAME_MINLENGTH), "6");
 
     }
 
@@ -53,6 +66,5 @@ public class ValidateDefaultModeTest {
     public void tearDown() throws Exception {
         String data = "{name:\"SCM\"}";
         writeFile(data);
-       // ConfigurationUtils.executeDDLSQL("truncate dox.configuration");
     }
 }
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/XMLConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/XMLConfigTest.java
deleted file mode 100644 (file)
index 22832d3..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-package org.onap.config.test;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.config.util.TestUtil;
-
-import java.io.IOException;
-
-import static org.onap.config.util.TestUtil.validateConfiguraton;
-import static org.onap.config.util.TestUtil.writeFile;
-
-/**
- * Created by ARR on 10/14/2016.
- *
- * Scenario 2
- * Validate configuration with XML file format with mode
- */
-public class XMLConfigTest {
-
-    public static final String NAMESPACE = "XMLConfig";
-
-    @Before
-    public void setUp() throws IOException {
-        String data = "{name:\"SCM\"}";
-        writeFile(data);
-    }
-
-    @Test
-    public void testConfigurationWithXMLFileFormat(){
-        validateConfiguraton(NAMESPACE);
-    }
-
-
-
-    @After
-    public void tearDown() throws Exception {
-        TestUtil.cleanUp();
-    }
-}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/XmlConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/XmlConfigTest.java
new file mode 100644 (file)
index 0000000..79a917d
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.config.test;
+
+import static org.onap.config.util.TestUtil.validateConfiguration;
+import static org.onap.config.util.TestUtil.writeFile;
+
+import java.io.IOException;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.config.util.TestUtil;
+
+/**
+ * Created by ARR on 10/14/2016.
+ * Scenario 2 - Validate configuration with XML file format with mode
+ */
+public class XmlConfigTest {
+
+    private static final String NAMESPACE = "XMLConfig";
+
+    @Before
+    public void setUp() throws IOException {
+        String data = "{name:\"SCM\"}";
+        writeFile(data);
+    }
+
+    @Test
+    public void testConfigurationWithXmlFileFormat() {
+        validateConfiguration(NAMESPACE);
+    }
+
+
+    @After
+    public void tearDown() throws Exception {
+        TestUtil.cleanUp();
+    }
+}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/YAMLConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/YAMLConfigTest.java
deleted file mode 100644 (file)
index f0e7ec5..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-package org.onap.config.test;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.config.util.TestUtil;
-
-import java.io.IOException;
-
-import static org.onap.config.util.TestUtil.validateConfiguraton;
-import static org.onap.config.util.TestUtil.writeFile;
-
-/**
- * Created by ARR on 10/14/2016.
- *
- * Scenario 4
- * Validate configuration with YAML file format with mode
- */
-public class YAMLConfigTest {
-
-    public static final String NAMESPACE = "YAMLConfig";
-
-    @Before
-    public void setUp() throws IOException {
-        String data = "{name:\"SCM\"}";
-        writeFile(data);
-    }
-
-    @Test
-    public void testConfigurationWithYAMLFileFormat(){
-        validateConfiguraton(NAMESPACE);
-    }
-
-
-
-    @After
-    public void tearDown() throws Exception {
-        TestUtil.cleanUp();
-    }
-}
diff --git a/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/YamlConfigTest.java b/common/onap-common-configuration-management/onap-configuration-management-core/src/test/java/org/onap/config/test/YamlConfigTest.java
new file mode 100644 (file)
index 0000000..b2954f1
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.config.test;
+
+import static org.onap.config.util.TestUtil.validateConfiguration;
+import static org.onap.config.util.TestUtil.writeFile;
+
+import java.io.IOException;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.config.util.TestUtil;
+
+/**
+ * Created by ARR on 10/14/2016.
+ * Scenario 4 - Validate configuration with YAML file format with mode
+ */
+public class YamlConfigTest {
+
+    private static final String NAMESPACE = "YAMLConfig";
+
+    @Before
+    public void setUp() throws IOException {
+        String data = "{name:\"SCM\"}";
+        writeFile(data);
+    }
+
+    @Test
+    public void testConfigurationWithYamlFileFormat() {
+        validateConfiguration(NAMESPACE);
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        TestUtil.cleanUp();
+    }
+}
index 828c92e..434c7d3 100644 (file)
@@ -1,24 +1,44 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package org.onap.config.util;
 
 public class ConfigTestConstant {
-       
-       public static final String ARTIFACT_NAME_MAXLENGTH = "artifact.name.maxlength";
-       public static final String ARTIFACT_MAXSIZE = "artifact.maxsize";
-       public static final String ARTIFACT_EXT = "artifact.extension";
-       public static final String ARTIFACT_ENC = "artifact.supportedEncryption";
-       public static final String ARTIFACT_NAME_UPPER = "artifact.name.allowedChar";
-       public static final String ARTIFACT_NAME_LOWER = "artifact.name.allowedchar";
-       public static final String ARTIFACT_STATUS = "artifact.status";
-       public static final String ARTIFACT_LOC = "artifact.persistLocation";
-       public static final String ARTIFACT_JSON_SCHEMA = "artifact.jsonSchema";
-       public static final String ARTIFACT_XML_SCHEMA = "artifact.xmlSchema";
-       public static final String ARTIFACT_CONSUMER_APPC = "artifact.consumerAPPC";
-       public static final String ARTIFACT_CONSUMER = "artifact.consumer";
-       public static final String ARTIFACT_MANDATORY_NAME = "artifact.mandatory.name";
-       public static final String ARTIFACT_NAME_MINLENGTH = "artifact.name.minlength";
-       public static final String ARTIFACT_ENCODED = "artifact.encoded";
 
-       public static final String PATH = "PATH";
-       public static final String ONBOARDING_NAMESPACE = "onboarding";
+    public static final String ARTIFACT_NAME_MAXLENGTH = "artifact.name.maxlength";
+    public static final String ARTIFACT_MAXSIZE = "artifact.maxsize";
+    public static final String ARTIFACT_EXT = "artifact.extension";
+    public static final String ARTIFACT_ENC = "artifact.supportedEncryption";
+    public static final String ARTIFACT_NAME_UPPER = "artifact.name.allowedChar";
+    public static final String ARTIFACT_NAME_LOWER = "artifact.name.allowedchar";
+    public static final String ARTIFACT_STATUS = "artifact.status";
+    public static final String ARTIFACT_LOC = "artifact.persistLocation";
+    public static final String ARTIFACT_JSON_SCHEMA = "artifact.jsonSchema";
+    public static final String ARTIFACT_XML_SCHEMA = "artifact.xmlSchema";
+    public static final String ARTIFACT_CONSUMER_APPC = "artifact.consumerAPPC";
+    public static final String ARTIFACT_CONSUMER = "artifact.consumer";
+    public static final String ARTIFACT_MANDATORY_NAME = "artifact.mandatory.name";
+    public static final String ARTIFACT_NAME_MINLENGTH = "artifact.name.minlength";
+    public static final String ARTIFACT_ENCODED = "artifact.encoded";
+
+    public static final String PATH = "PATH";
+    public static final String ONBOARDING_NAMESPACE = "onboarding";
+
+    private ConfigTestConstant() {
+        // prevent instantiation
+    }
 
 }
index 514f528..87ff4ba 100644 (file)
@@ -30,33 +30,32 @@ import org.onap.config.api.ConfigurationManager;
  */
 public class TestUtil {
 
-    public final static String jsonSchemaLoc = System.getProperty("user.home")+"/TestResources/";
-    public static FileWriter fileWriter ;
+    public static final String jsonSchemaLoc = System.getProperty("user.home") + "/TestResources/";
+
+    public static void cleanUp() throws Exception {
+        String data = "{name:\"SCM\"}";
+        TestUtil.writeFile(data);
+    }
 
     public static void writeFile(String data) throws IOException {
         File dir = new File(jsonSchemaLoc);
         dir.mkdirs();
-        File file = new File(jsonSchemaLoc+"/GeneratorsList.json");
+        File file = new File(jsonSchemaLoc + "/GeneratorsList.json");
         file.createNewFile();
-        fileWriter = new FileWriter(file);
+        FileWriter fileWriter = new FileWriter(file);
         fileWriter.write(data);
         fileWriter.close();
     }
 
-    public static void cleanUp() throws Exception {
-        String data = "{name:\"SCM\"}";
-        TestUtil.writeFile(data);
-    }
-
-    public static void validateConfiguraton(String nameSpace) {
+    public static void validateConfiguration(String nameSpace) {
         Configuration config = ConfigurationManager.lookup();
 
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH ), "14");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_NAME_MAXLENGTH), "14");
 
         // First value from list is picked from Merge properties
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_MAXSIZE ), "1048576");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_MAXSIZE), "1048576");
 
-        List<String> expectedExtList = new ArrayList<String>();
+        List<String> expectedExtList = new ArrayList<>();
         expectedExtList.add("pdf");
         expectedExtList.add("zip");
         expectedExtList.add("xml");
@@ -66,32 +65,35 @@ public class TestUtil {
         List<String> extList = config.getAsStringValues(nameSpace, ConfigTestConstant.ARTIFACT_EXT);
         Assert.assertEquals(expectedExtList, extList);
 
-        List<String> expectedEncList = new ArrayList<String>();
+        List<String> expectedEncList = new ArrayList<>();
         expectedEncList.add("Base64");
         expectedEncList.add("MD5");
         List<String> encList = config.getAsStringValues(nameSpace, ConfigTestConstant.ARTIFACT_ENC);
         Assert.assertEquals(expectedEncList, encList);
 
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_NAME_UPPER ), "a-zA-Z_0-9");
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_NAME_LOWER ), "a-zA-Z");
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_STATUS ), "deleted");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_NAME_UPPER), "a-zA-Z_0-9");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_NAME_LOWER), "a-zA-Z");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_STATUS), "deleted");
 
-        List<String> expectedLocList = new ArrayList<String>();
+        List<String> expectedLocList = new ArrayList<>();
         expectedLocList.add("/opt/spool");
-        expectedLocList.add(System.getProperty("user.home")+"/asdc");
+        expectedLocList.add(System.getProperty("user.home") + "/asdc");
         List<String> locList = config.getAsStringValues(nameSpace, ConfigTestConstant.ARTIFACT_LOC);
         Assert.assertEquals(expectedLocList, locList);
 
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_JSON_SCHEMA ), "@GeneratorList.json");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_JSON_SCHEMA),
+                "@GeneratorList.json");
 
-        Assert.assertEquals("@"+getenv(ConfigTestConstant.PATH)+"/myschema.json",config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_XML_SCHEMA));
+        Assert.assertEquals("@" + getenv(ConfigTestConstant.PATH) + "/myschema.json",
+                config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_XML_SCHEMA));
 
-        List<String> artifactConsumer = config.getAsStringValues(nameSpace, ConfigTestConstant.ARTIFACT_CONSUMER );
-        Assert.assertEquals(config.getAsStringValues(nameSpace, ConfigTestConstant.ARTIFACT_CONSUMER_APPC ), artifactConsumer);
+        List<String> artifactConsumer = config.getAsStringValues(nameSpace, ConfigTestConstant.ARTIFACT_CONSUMER);
+        Assert.assertEquals(config.getAsStringValues(nameSpace, ConfigTestConstant.ARTIFACT_CONSUMER_APPC),
+                artifactConsumer);
 
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_NAME_MINLENGTH ), "6");
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_MANDATORY_NAME ), "true");
-        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_ENCODED ), "true");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_NAME_MINLENGTH), "6");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_MANDATORY_NAME), "true");
+        Assert.assertEquals(config.getAsString(nameSpace, ConfigTestConstant.ARTIFACT_ENCODED), "true");
     }
 
     /**
index cfe91e6..f8222a3 100644 (file)
@@ -1,22 +1,3 @@
-driverClassName=com.github.adejanovski.cassandra.jdbc.CassandraDriver
-jdbcURL=jdbc:${dbname}://${dbhost}:${dbport}/${configdb}
-dbuser=
-dbpassword=
-config.Table=configuration
-config.monitor.Table=configuration_change
-configKey=key
-configValue=value
-configNameColumn=name
-configdb=dox
-dbhost=
-dbport=9042
-dbname=cassandra
-createtablecql=create table if not exists ${configdb}.${config.Table} (name text\, key text\, value text\, PRIMARY KEY (name\, key)) with clustering order by (key asc)
-createmonitoringtablecql=create table if not exists ${configdb}.${config.monitor.Table} (name text\, changed_when bigint\, key text\, old_value text\, new_value text\, PRIMARY KEY (name\, changed_when)) with clustering order by (changed_when desc)
-insertconfigurationchangecql=insert into ${configdb}.${config.monitor.Table} (name\, changed_when\, key\, old_value\, new_value) values(?\, ?\, ?\, ?\, ?)
-fetchkeysql=select ${configKey} from ${config.Table} where ${configNameColumn}=?
-fetchlastchangecql=select changed_when from ${configdb}.${config.monitor.Table} where name=? limit 1
-fetchnamescql=select distinct name from ${configdb}.${config.Table}
 config.size.max=100
 config.refresh.interval=30000
 event.fetch.delay=5000
\ No newline at end of file
index b89b8fa..95ad665 100755 (executable)
@@ -1,21 +1,21 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-       <modelVersion>4.0.0</modelVersion>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xmlns="http://maven.apache.org/POM/4.0.0"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
 
-       <name>onap-common-configuration-management</name>
-       <artifactId>onap-common-configuration-management</artifactId>
-       <packaging>pom</packaging>
+    <name>onap-common-configuration-management</name>
+    <artifactId>onap-common-configuration-management</artifactId>
+    <packaging>pom</packaging>
 
-       <parent>
-               <groupId>org.onap.sdc.common</groupId>
-               <artifactId>onap-common-lib</artifactId>
-               <version>1.3.1-SNAPSHOT</version>
-       </parent>
+    <parent>
+        <groupId>org.onap.sdc.common</groupId>
+        <artifactId>onap-common-lib</artifactId>
+        <version>1.3.1-SNAPSHOT</version>
+    </parent>
 
-       <modules>
-               <module>onap-configuration-management-api</module>
-               <module>onap-configuration-management-core</module>
-       </modules>
+    <modules>
+        <module>onap-configuration-management-api</module>
+        <module>onap-configuration-management-core</module>
+    </modules>
 
 </project>