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;
57 import reactor.core.Disposable;
58 import reactor.core.publisher.Flux;
59 import reactor.core.publisher.Mono;
61 @EnableConfigurationProperties
62 @ConfigurationProperties("app")
63 public class ApplicationConfig {
64 private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);
66 @Value("#{systemEnvironment}")
67 Properties systemEnvironment;
69 private Disposable refreshConfigTask = null;
72 private String filepath;
74 private Vector<RicConfig> ricConfigs;
77 public ApplicationConfig() {
80 public synchronized void setFilepath(String filepath) {
81 this.filepath = filepath;
84 public Vector<RicConfig> getRicConfigs() {
85 return this.ricConfigs;
88 public Optional<RicConfig> lookupRicConfigForManagedElement(String managedElementId) {
89 for (RicConfig ricConfig : getRicConfigs()) {
90 if (ricConfig.managedElementIds().contains(managedElementId)) {
91 return Optional.of(ricConfig);
94 return Optional.empty();
97 public RicConfig getRic(String ricName) throws ServiceException {
98 for (RicConfig ricConfig : getRicConfigs()) {
99 if (ricConfig.name().equals(ricName)) {
103 throw new ServiceException("Could not find ric: " + ricName);
106 public void initialize() {
108 loadConfigurationFromFile(this.filepath);
110 refreshConfigTask = createRefreshTask() //
111 .subscribe(e -> logger.info("Refreshed configuration data"),
112 throwable -> logger.error("Configuration refresh terminated due to exception", throwable),
113 () -> logger.error("Configuration refresh terminated"));
116 Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
117 return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment);
120 Flux<ApplicationConfig> createRefreshTask() {
121 return getEnvironment(systemEnvironment) //
122 .flatMap(this::createCbsClient) //
123 .flatMapMany(this::periodicConfigurationUpdates) //
124 .map(this::parseRicConfigurationfromConsul) //
125 .onErrorResume(this::onErrorResume);
128 Mono<CbsClient> createCbsClient(EnvProperties env) {
129 return CbsClientFactory.createCbsClient(env);
132 private Flux<JsonObject> periodicConfigurationUpdates(CbsClient cbsClient) {
133 final Duration initialDelay = Duration.ZERO;
134 final Duration refreshPeriod = Duration.ofMinutes(1);
135 final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
136 return cbsClient.updates(getConfigRequest, initialDelay, refreshPeriod);
139 private <R> Mono<R> onErrorResume(Throwable trowable) {
140 logger.error("Could not refresh application configuration {}", trowable.toString());
144 private ApplicationConfig parseRicConfigurationfromConsul(JsonObject jsonObject) {
146 ApplicationConfigParser parser = new ApplicationConfigParser();
147 parser.parse(jsonObject);
148 setConfiguration(parser.getRicConfigs());
150 } catch (ServiceException e) {
151 logger.error("Could not parse configuration {}", e.toString(), e);
156 private synchronized void setConfiguration(@NotNull Vector<RicConfig> ricConfigs) {
157 this.ricConfigs = ricConfigs;
161 if (refreshConfigTask != null) {
162 refreshConfigTask.dispose();
163 refreshConfigTask = null;
168 * Reads the configuration from file.
170 protected void loadConfigurationFromFile(String filepath) {
171 GsonBuilder gsonBuilder = new GsonBuilder();
172 ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
174 try (InputStream inputStream = createInputStream(filepath)) {
175 JsonParser parser = new JsonParser();
176 JsonObject rootObject = getJsonElement(parser, inputStream).getAsJsonObject();
177 if (rootObject == null) {
178 throw new JsonSyntaxException("Root is not a json object");
180 ApplicationConfigParser appParser = new ApplicationConfigParser();
181 appParser.parse(rootObject);
182 this.ricConfigs = appParser.getRicConfigs();
183 logger.info("Local configuration file loaded: {}", filepath);
184 } catch (JsonSyntaxException | ServiceException | IOException e) {
185 logger.trace("Local configuration file not loaded: {}", filepath, e);
189 JsonElement getJsonElement(JsonParser parser, InputStream inputStream) {
190 return parser.parse(new InputStreamReader(inputStream));
193 InputStream createInputStream(@NotNull String filepath) throws IOException {
194 return new BufferedInputStream(new FileInputStream(filepath));