summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/dcae/configuration
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/org/onap/dcae/configuration')
-rwxr-xr-xsrc/main/java/org/onap/dcae/configuration/ConfigFilesFacade.java142
-rwxr-xr-xsrc/main/java/org/onap/dcae/configuration/ConfigParsing.java56
-rwxr-xr-xsrc/main/java/org/onap/dcae/configuration/ConfigUpdater.java118
-rwxr-xr-xsrc/main/java/org/onap/dcae/configuration/ConfigUpdaterFactory.java45
-rwxr-xr-xsrc/main/java/org/onap/dcae/configuration/ConfigurationHandler.java114
-rwxr-xr-xsrc/main/java/org/onap/dcae/configuration/Conversions.java47
-rwxr-xr-xsrc/main/java/org/onap/dcae/configuration/cbs/CbsClientConfigurationProvider.java85
7 files changed, 607 insertions, 0 deletions
diff --git a/src/main/java/org/onap/dcae/configuration/ConfigFilesFacade.java b/src/main/java/org/onap/dcae/configuration/ConfigFilesFacade.java
new file mode 100755
index 0000000..0a8c089
--- /dev/null
+++ b/src/main/java/org/onap/dcae/configuration/ConfigFilesFacade.java
@@ -0,0 +1,142 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.restconfcollector
+ * ================================================================================
+ * Copyright (C) 2022 Huawei. All rights reserved.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.configuration;
+
+import static io.vavr.API.Try;
+import static org.onap.dcae.common.publishing.VavrUtils.enhanceError;
+import static org.onap.dcae.common.publishing.VavrUtils.f;
+import static org.onap.dcae.common.publishing.VavrUtils.logError;
+import static org.onap.dcae.configuration.Conversions.toList;
+
+import io.vavr.CheckedRunnable;
+import io.vavr.Tuple2;
+import io.vavr.collection.Map;
+import io.vavr.control.Try;
+import java.io.FileNotFoundException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.apache.commons.configuration.ConfigurationException;
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * ConfigFilesFacade is used for reading and writing application properties and dmaap configuration.
+ */
+public class ConfigFilesFacade {
+
+ private static final Logger log = LoggerFactory.getLogger(ConfigFilesFacade.class);
+
+ private Path dmaapConfigPath;
+ private Path propertiesPath;
+
+ ConfigFilesFacade(Path propertiesPath, Path dMaaPConfigPath) {
+ this.propertiesPath = propertiesPath;
+ this.dmaapConfigPath = dMaaPConfigPath;
+ }
+
+ /**
+ * Set new paths
+ * @param propertiesFile application property file
+ * @param dmaapConfigFile dmaap configuration file
+ */
+ public void setPaths(Path propertiesFile, Path dmaapConfigFile) {
+ this.propertiesPath = propertiesFile;
+ this.dmaapConfigPath = dmaapConfigFile;
+ }
+
+ Try<Map<String, String>> readCollectorProperties() {
+ log.info(f("Reading collector properties from path: '%s'", propertiesPath));
+ return Try(this::readProperties)
+ .map(prop -> toList(prop.getKeys()).toMap(k -> k, k -> (String) prop.getProperty(k)))
+ .mapFailure(enhanceError("Unable to read properties configuration from path '%s'", propertiesPath))
+ .onFailure(logError(log))
+ .peek(props -> log.info(f("Read following collector properties: '%s'", props)));
+ }
+
+ Try<JSONObject> readDMaaPConfiguration() {
+ log.info(f("Reading DMaaP configuration from file: '%s'", dmaapConfigPath));
+ return readFile(dmaapConfigPath)
+ .recover(FileNotFoundException.class, __ -> "{}")
+ .mapFailure(enhanceError("Unable to read DMaaP configuration from file '%s'", dmaapConfigPath))
+ .flatMap(Conversions::toJson)
+ .onFailure(logError(log))
+ .peek(props -> log.info(f("Read following DMaaP properties: '%s'", props)));
+ }
+
+ Try<Void> writeDMaaPConfiguration(JSONObject dMaaPConfiguration) {
+ log.info(f("Writing DMaaP configuration '%s' into file '%s'", dMaaPConfiguration, dmaapConfigPath));
+ return writeFile(dmaapConfigPath, indentConfiguration(dMaaPConfiguration.toString()))
+ .mapFailure(enhanceError("Could not save new DMaaP configuration to path '%s'", dmaapConfigPath))
+ .onFailure(logError(log))
+ .peek(__ -> log.info("Written successfully"));
+ }
+
+
+ Try<Void> writeProperties(Map<String, String> properties) {
+ log.info(f("Writing properties configuration '%s' into file '%s'", properties, propertiesPath));
+ return Try.run(saveProperties(properties))
+ .mapFailure(enhanceError("Could not save properties to path '%s'", properties))
+ .onFailure(logError(log))
+ .peek(__ -> log.info("Written successfully"));
+ }
+
+ private Try<String> readFile(Path path) {
+ return Try(() -> new String(Files.readAllBytes(path), StandardCharsets.UTF_8))
+ .mapFailure(enhanceError("Could not read content from path: '%s'", path));
+ }
+
+ private Try<Void> writeFile(Path path, String content) {
+ return Try.run(() -> Files.write(path, content.getBytes()))
+ .mapFailure(enhanceError("Could not write content to path: '%s'", path));
+ }
+
+ private PropertiesConfiguration readProperties() throws ConfigurationException {
+ PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
+ propertiesConfiguration.setDelimiterParsingDisabled(true);
+ propertiesConfiguration.load(propertiesPath.toFile());
+ return propertiesConfiguration;
+ }
+
+ private CheckedRunnable saveProperties(Map<String, String> properties) {
+ return () -> {
+ PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration(propertiesPath.toFile());
+ propertiesConfiguration.setEncoding(null);
+ for (Tuple2<String, String> property : properties) {
+ updateProperty(propertiesConfiguration, property);
+ }
+ propertiesConfiguration.save();
+ };
+ }
+
+ private void updateProperty(PropertiesConfiguration propertiesConfiguration, Tuple2<String, String> property) {
+ if (propertiesConfiguration.containsKey(property._1)) {
+ propertiesConfiguration.setProperty(property._1, property._2);
+ } else {
+ propertiesConfiguration.addProperty(property._1, property._2);
+ }
+ }
+
+ private String indentConfiguration(String configuration) {
+ return new JSONObject(configuration).toString(4);
+ }
+}
diff --git a/src/main/java/org/onap/dcae/configuration/ConfigParsing.java b/src/main/java/org/onap/dcae/configuration/ConfigParsing.java
new file mode 100755
index 0000000..7b2a656
--- /dev/null
+++ b/src/main/java/org/onap/dcae/configuration/ConfigParsing.java
@@ -0,0 +1,56 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.restconfcollector
+ * ================================================================================
+ * Copyright (C) 2022 Huawei. All rights reserved.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.configuration;
+
+import static io.vavr.API.Try;
+import static io.vavr.API.Tuple;
+import static org.onap.dcae.common.publishing.VavrUtils.f;
+import static org.onap.dcae.configuration.Conversions.toList;
+
+import io.vavr.collection.Map;
+import io.vavr.control.Option;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+interface ConfigParsing {
+
+ Logger log = LoggerFactory.getLogger(ConfigParsing.class);
+
+ static Option<JSONObject> getDMaaPConfig(JSONObject configuration) {
+ log.info(f("Getting DMaaP configuration from app configuration: '%s'", configuration));
+ return toList(configuration.toMap().entrySet().iterator())
+ .filter(t -> t.getKey().startsWith("streams_publishes"))
+ .headOption()
+ .flatMap(e -> Try(() -> configuration.getJSONObject(e.getKey())).toOption())
+ .onEmpty(() -> log.warn(f("App configuration '%s' is missing DMaaP configuration ('streams_publishes' key) "
+ + "or DMaaP configuration is not a valid json document", configuration)))
+ .peek(dMaaPConf -> log.info(f("Found following DMaaP configuration: '%s'", dMaaPConf)));
+ }
+
+ static Map<String, String> getProperties(JSONObject configuration) {
+ log.debug(f("Getting properties configuration from app configuration: '%s'", configuration));
+ Map<String, String> confEntries = toList(configuration.toMap().entrySet().iterator())
+ .toMap(e -> Tuple(e.getKey(), String.valueOf(e.getValue())))
+ .filterKeys(e -> !e.startsWith("streams_publishes"));
+ log.debug(f("Found following app properties: '%s'", confEntries));
+ return confEntries;
+ }
+}
diff --git a/src/main/java/org/onap/dcae/configuration/ConfigUpdater.java b/src/main/java/org/onap/dcae/configuration/ConfigUpdater.java
new file mode 100755
index 0000000..0d9e660
--- /dev/null
+++ b/src/main/java/org/onap/dcae/configuration/ConfigUpdater.java
@@ -0,0 +1,118 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.restconfcollector
+ * ================================================================================
+ * Copyright (C) 2022 Huawei. All rights reserved.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.configuration;
+
+import io.vavr.collection.Map;
+import io.vavr.control.Option;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.file.Path;
+
+/**
+ * ConfigUpdater is responsible for receiving configuration updates from config file.
+ */
+public class ConfigUpdater {
+
+ private static final Logger log = LoggerFactory.getLogger(ConfigUpdater.class);
+ private final ConfigFilesFacade configFilesFacade;
+ private final Runnable applicationRestarter;
+ private boolean isApplicationRestartNeeded;
+
+ /**
+ * Constructor
+ * @param configFilesFacade provides configuration files facade
+ * @param applicationRestarter for restart application
+ */
+ public ConfigUpdater(ConfigFilesFacade configFilesFacade, Runnable applicationRestarter) {
+ this.configFilesFacade = configFilesFacade;
+ this.applicationRestarter = applicationRestarter;
+ this.isApplicationRestartNeeded = false;
+ }
+
+ /**
+ * Set new paths
+ * @param propertiesFile application property file
+ * @param dmaapConfigFile dmaap configuration file
+ */
+ public void setPaths(Path propertiesFile, Path dmaapConfigFile){
+ this.configFilesFacade.setPaths(propertiesFile, dmaapConfigFile);
+
+ }
+ /**
+ * update configuration
+ * @param appConfig JSON object list
+ */
+ public synchronized void updateConfig(Option<JSONObject> appConfig) {
+ appConfig.peek(this::handleUpdate).onEmpty(logSkipMessage());
+ }
+
+ private Runnable logSkipMessage() {
+ return () -> log.info("Skipping dynamic configuration");
+ }
+
+ private void handleUpdate(JSONObject appConfig) {
+ updatePropertiesIfChanged(appConfig);
+ updateDmaapConfigIfChanged(appConfig);
+ restartApplicationIfNeeded();
+ }
+
+ private void updatePropertiesIfChanged(JSONObject appConfig) {
+ Map<String, String> newProperties = ConfigParsing.getProperties(appConfig);
+ Map<String, String> oldProperties = configFilesFacade.readCollectorProperties().get();
+
+ if (!areCommonPropertiesSame(oldProperties, newProperties)) {
+ configFilesFacade.writeProperties(newProperties);
+ isApplicationRestartNeeded = true;
+ }
+ }
+
+ private boolean areCommonPropertiesSame(Map<String, String> oldProperties, Map<String, String> newProperties) {
+ Map<String, String> filteredOldProperties = filterIntersectingKeys(oldProperties, newProperties);
+ return filteredOldProperties.equals(newProperties);
+ }
+
+ private Map<String, String> filterIntersectingKeys(Map<String, String> primaryProperties,
+ Map<String, String> otherProperties) {
+ return primaryProperties.filterKeys(key -> containsKey(key, otherProperties));
+ }
+
+ private boolean containsKey(String key, Map<String, String> properties) {
+ return properties.keySet().contains(key);
+ }
+
+ private void updateDmaapConfigIfChanged(JSONObject appConfig) {
+ JSONObject oldDmaapConfig = configFilesFacade.readDMaaPConfiguration().get();
+ JSONObject newDmaapConfig = ConfigParsing.getDMaaPConfig(appConfig).get();
+
+ if (!oldDmaapConfig.similar(newDmaapConfig)) {
+ configFilesFacade.writeDMaaPConfiguration(newDmaapConfig);
+ isApplicationRestartNeeded = true;
+ }
+ }
+
+ private void restartApplicationIfNeeded() {
+ if (isApplicationRestartNeeded) {
+ applicationRestarter.run();
+ isApplicationRestartNeeded = false;
+ }
+ }
+}
diff --git a/src/main/java/org/onap/dcae/configuration/ConfigUpdaterFactory.java b/src/main/java/org/onap/dcae/configuration/ConfigUpdaterFactory.java
new file mode 100755
index 0000000..7fc4532
--- /dev/null
+++ b/src/main/java/org/onap/dcae/configuration/ConfigUpdaterFactory.java
@@ -0,0 +1,45 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.restconfcollector
+ * ================================================================================
+ * Copyright (C) 2022 Huawei. All rights reserved.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.configuration;
+
+import java.nio.file.Path;
+
+import org.onap.dcae.RestConfCollector;
+
+/**
+ * ConfigUpdaterFactory is responsible for receiving configuration from config file or Consul (if config file doesn't exist).
+ */
+public class ConfigUpdaterFactory {
+
+ private ConfigUpdaterFactory() {
+ }
+
+ /**
+ * create configuration updater based on property file and dmaap configuration files
+ * @param propertiesFile application property file
+ * @param dmaapConfigFile dmaap configuration file
+ */
+ public static ConfigUpdater create(Path propertiesFile, Path dmaapConfigFile) {
+ ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(propertiesFile, dmaapConfigFile);
+ return new ConfigUpdater(
+ configFilesFacade,
+ RestConfCollector::restartApplication);
+ }
+}
diff --git a/src/main/java/org/onap/dcae/configuration/ConfigurationHandler.java b/src/main/java/org/onap/dcae/configuration/ConfigurationHandler.java
new file mode 100755
index 0000000..9495308
--- /dev/null
+++ b/src/main/java/org/onap/dcae/configuration/ConfigurationHandler.java
@@ -0,0 +1,114 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.restconfcollector
+ * ================================================================================
+ * Copyright (C) 2022 Huawei. All rights reserved.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.configuration;
+
+import com.google.gson.JsonObject;
+import io.vavr.control.Option;
+import org.json.JSONObject;
+import org.onap.dcae.configuration.cbs.CbsClientConfigurationProvider;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsClientConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
+import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import reactor.core.Disposable;
+import reactor.core.publisher.Mono;
+
+import java.time.Duration;
+
+/**
+ * ConfigurationHandler is responsible for receiving configuration updates from config file or Consul (if config file doesn't exist).
+ * Any change made in the configuration will be reported as a notification.
+ */
+public class ConfigurationHandler {
+
+ private static Logger log = LoggerFactory.getLogger(ConfigurationHandler.class);
+ private static final String CONFIG_DICT = "config";
+
+ private final CbsClientConfigurationProvider cbsClientConfigurationProvider;
+ private final ConfigUpdater configUpdater;
+
+ /**
+ * Constructor
+ * @param cbsClientConfigurationProvider provides configuration to connect with Consul
+ * @param configUpdater for updating application configuration
+ */
+ public ConfigurationHandler(CbsClientConfigurationProvider cbsClientConfigurationProvider, ConfigUpdater configUpdater) {
+ this.cbsClientConfigurationProvider = cbsClientConfigurationProvider;
+ this.configUpdater = configUpdater;
+ }
+
+ /**
+ * Start listen for application configuration notifications with configuration changes
+ * @param interval defines period of time when notification can come
+ * @return {@link Disposable} handler to close configuration listener at the end
+ */
+ public Disposable startListen(Duration interval) {
+
+ log.info("Start listening for configuration ...");
+ log.info(String.format("Configuration will be fetched in %s period.", interval));
+
+ // Polling properties
+ final Duration initialDelay = Duration.ofSeconds(5);
+ final Duration period = interval;
+
+ final CbsRequest request = createCbsRequest();
+ final CbsClientConfiguration cbsClientConfiguration = cbsClientConfigurationProvider.get();
+
+ return createCbsClient(cbsClientConfiguration)
+ .flatMapMany(cbsClient -> cbsClient.updates(request, initialDelay, period))
+ .subscribe(
+ this::handleConfiguration,
+ this::handleError
+ );
+ }
+
+ /**
+ * Create CBS Client configuration
+ * @param accept cbsClientConfiguration
+ * @return return cbs client
+ */
+ Mono<CbsClient> createCbsClient(CbsClientConfiguration cbsClientConfiguration) {
+ return CbsClientFactory.createCbsClient(cbsClientConfiguration);
+ }
+
+ void handleConfiguration(JsonObject jsonObject) {
+ log.info("Configuration update {}", jsonObject);
+ if(jsonObject.has(CONFIG_DICT)) {
+ JsonObject config = jsonObject.getAsJsonObject(CONFIG_DICT);
+ JSONObject jObject = new JSONObject(config.toString());
+ configUpdater.updateConfig(Option.of(jObject));
+ } else {
+ throw new IllegalArgumentException(String.format("Invalid application configuration: %s ", jsonObject));
+ }
+ }
+
+ private void handleError(Throwable throwable) {
+ log.error("Unexpected error occurred during fetching configuration", throwable);
+ }
+
+ private CbsRequest createCbsRequest() {
+ RequestDiagnosticContext diagnosticContext = RequestDiagnosticContext.create();
+ return CbsRequests.getAll(diagnosticContext);
+ }
+}
diff --git a/src/main/java/org/onap/dcae/configuration/Conversions.java b/src/main/java/org/onap/dcae/configuration/Conversions.java
new file mode 100755
index 0000000..98f632c
--- /dev/null
+++ b/src/main/java/org/onap/dcae/configuration/Conversions.java
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.restconfcollector
+ * ================================================================================
+ * Copyright (C) 2022 Huawei. All rights reserved.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.configuration;
+
+import static org.onap.dcae.common.publishing.VavrUtils.enhanceError;
+
+import io.vavr.API;
+import io.vavr.collection.List;
+import io.vavr.control.Try;
+import java.util.Iterator;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.stream.StreamSupport;
+import org.json.JSONObject;
+
+/**
+ * Conversions is used to convert to JSON Object.
+ */
+interface Conversions {
+
+ static Try<JSONObject> toJson(String strBody) {
+ return API.Try(() -> new JSONObject(strBody))
+ .mapFailure(enhanceError("Value '%s' is not a valid JSON document", strBody));
+ }
+
+ static <T> List<T> toList(Iterator<T> iterator) {
+ return List
+ .ofAll(StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false));
+ }
+}
diff --git a/src/main/java/org/onap/dcae/configuration/cbs/CbsClientConfigurationProvider.java b/src/main/java/org/onap/dcae/configuration/cbs/CbsClientConfigurationProvider.java
new file mode 100755
index 0000000..b808004
--- /dev/null
+++ b/src/main/java/org/onap/dcae/configuration/cbs/CbsClientConfigurationProvider.java
@@ -0,0 +1,85 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.restconfcollector
+ * ================================================================================
+ * Copyright (C) 2022 Huawei. All rights reserved.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.configuration.cbs;
+
+import org.jetbrains.annotations.NotNull;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsClientConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.ImmutableCbsClientConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * CbsClientConfigurationProvider is used to provide production or dev configuration for CBS client.
+ */
+public class CbsClientConfigurationProvider {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(CbsClientConfigurationProvider.class);
+
+ private static final String DEFAULT_PROTOCOL = "http";
+ private static final String DEFAULT_HOSTNAME = "config-binding-service";
+ private static final int DEFAULT_PORT = 10000;
+ private static final String DEFAULT_APP_NAME = "dcae-ves-collector";
+ private static final String DEV_MODE_PROPERTY = "devMode";
+ private static final String CBS_PORT_PROPERTY = "cbsPort";
+
+ /**
+ * Returns configuration for CBS client.
+ * @return Production or dev configuration for CBS client, depends on application run arguments.
+ */
+ public CbsClientConfiguration get() {
+ try {
+ if (isDevModeEnabled()) {
+ return getDevConfiguration();
+ } else {
+ return CbsClientConfiguration.fromEnvironment();
+ }
+ } catch (Exception e) {
+ LOGGER.warn(String.format("Failed resolving CBS client configuration from system environments: %s", e));
+ }
+ return getFallbackConfiguration();
+ }
+
+ @NotNull
+ private ImmutableCbsClientConfiguration getDevConfiguration() {
+ return createCbsClientConfiguration(
+ DEFAULT_PROTOCOL, DEFAULT_HOSTNAME, DEFAULT_APP_NAME,
+ Integer.parseInt(System.getProperty(CBS_PORT_PROPERTY, String.valueOf(DEFAULT_PORT)))
+ );
+ }
+
+ private boolean isDevModeEnabled() {
+ return System.getProperty(DEV_MODE_PROPERTY) != null;
+ }
+
+ private ImmutableCbsClientConfiguration getFallbackConfiguration() {
+ LOGGER.info("Falling back to use default CBS client configuration");
+ return createCbsClientConfiguration(DEFAULT_PROTOCOL, DEFAULT_HOSTNAME, DEFAULT_APP_NAME, DEFAULT_PORT);
+ }
+
+ private ImmutableCbsClientConfiguration createCbsClientConfiguration(String protocol, String hostname,
+ String appName, Integer port) {
+ return ImmutableCbsClientConfiguration.builder()
+ .protocol(protocol)
+ .hostname(hostname)
+ .port(port)
+ .appName(appName)
+ .build();
+ }
+}