2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
21 package org.oransc.policyagent.configuration;
23 import com.google.gson.GsonBuilder;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27 import com.google.gson.JsonSyntaxException;
28 import com.google.gson.TypeAdapterFactory;
30 import java.io.BufferedInputStream;
31 import java.io.FileInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.time.Duration;
36 import java.util.Optional;
37 import java.util.Properties;
38 import java.util.ServiceLoader;
39 import java.util.Vector;
41 import javax.validation.constraints.NotEmpty;
42 import javax.validation.constraints.NotNull;
44 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
45 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;
46 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
47 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
48 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;
49 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
50 import org.oransc.policyagent.exceptions.ServiceException;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.beans.factory.annotation.Value;
55 import org.springframework.boot.context.properties.ConfigurationProperties;
56 import org.springframework.boot.context.properties.EnableConfigurationProperties;
58 import reactor.core.Disposable;
59 import reactor.core.publisher.Flux;
60 import reactor.core.publisher.Mono;
62 @EnableConfigurationProperties
63 @ConfigurationProperties("app")
64 public class ApplicationConfig {
65 private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);
67 @Value("#{systemEnvironment}")
68 Properties systemEnvironment;
70 private Disposable refreshConfigTask = null;
73 private String filepath;
75 private Vector<RicConfig> ricConfigs;
78 public ApplicationConfig() {
81 public synchronized void setFilepath(String filepath) {
82 this.filepath = filepath;
85 public Vector<RicConfig> getRicConfigs() {
86 return this.ricConfigs;
89 public Optional<RicConfig> lookupRicConfigForManagedElement(String managedElementId) {
90 for (RicConfig ricConfig : getRicConfigs()) {
91 if (ricConfig.managedElementIds().contains(managedElementId)) {
92 return Optional.of(ricConfig);
95 return Optional.empty();
98 public RicConfig getRic(String ricName) throws ServiceException {
99 for (RicConfig ricConfig : getRicConfigs()) {
100 if (ricConfig.name().equals(ricName)) {
104 throw new ServiceException("Could not find ric: " + ricName);
107 public void initialize() {
109 loadConfigurationFromFile(this.filepath);
111 refreshConfigTask = createRefreshTask() //
112 .subscribe(notUsed -> logger.info("Refreshed configuration data"),
113 throwable -> logger.error("Configuration refresh terminated due to exception", throwable),
114 () -> logger.error("Configuration refresh terminated"));
117 Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
118 return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment);
121 Flux<ApplicationConfig> createRefreshTask() {
122 return getEnvironment(systemEnvironment) //
123 .flatMap(this::createCbsClient) //
124 .flatMapMany(this::periodicConfigurationUpdates) //
125 .map(this::parseRicConfigurationfromConsul) //
126 .onErrorResume(this::onErrorResume);
129 Mono<CbsClient> createCbsClient(EnvProperties env) {
130 return CbsClientFactory.createCbsClient(env);
133 private Flux<JsonObject> periodicConfigurationUpdates(CbsClient cbsClient) {
134 final Duration initialDelay = Duration.ZERO;
135 final Duration refreshPeriod = Duration.ofMinutes(1);
136 final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
137 return cbsClient.updates(getConfigRequest, initialDelay, refreshPeriod);
140 private <R> Mono<R> onErrorResume(Throwable trowable) {
141 logger.error("Could not refresh application configuration {}", trowable.toString());
145 private ApplicationConfig parseRicConfigurationfromConsul(JsonObject jsonObject) {
147 ApplicationConfigParser parser = new ApplicationConfigParser();
148 parser.parse(jsonObject);
149 setConfiguration(parser.getRicConfigs());
151 } catch (ServiceException e) {
152 logger.error("Could not parse configuration {}", e.toString(), e);
157 private synchronized void setConfiguration(@NotNull Vector<RicConfig> ricConfigs) {
158 this.ricConfigs = ricConfigs;
162 if (refreshConfigTask != null) {
163 refreshConfigTask.dispose();
164 refreshConfigTask = null;
169 * Reads the configuration from file.
171 protected void loadConfigurationFromFile(String filepath) {
172 GsonBuilder gsonBuilder = new GsonBuilder();
173 ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
175 try (InputStream inputStream = createInputStream(filepath)) {
176 JsonParser parser = new JsonParser();
177 JsonObject rootObject = getJsonElement(parser, inputStream).getAsJsonObject();
178 if (rootObject == null) {
179 throw new JsonSyntaxException("Root is not a json object");
181 ApplicationConfigParser appParser = new ApplicationConfigParser();
182 appParser.parse(rootObject);
183 this.ricConfigs = appParser.getRicConfigs();
184 logger.info("Local configuration file loaded: {}", filepath);
185 } catch (JsonSyntaxException | ServiceException | IOException e) {
186 logger.trace("Local configuration file not loaded: {}", filepath, e);
190 JsonElement getJsonElement(JsonParser parser, InputStream inputStream) {
191 return parser.parse(new InputStreamReader(inputStream));
194 InputStream createInputStream(@NotNull String filepath) throws IOException {
195 return new BufferedInputStream(new FileInputStream(filepath));