Merge "Added STD sim 2.0.0 tests"
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / configuration / ApplicationConfig.java
index 7e52284..5e02098 100644 (file)
 
 package org.oransc.policyagent.configuration;
 
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-import com.google.gson.TypeAdapterFactory;
-
-import java.io.BufferedInputStream;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.time.Duration;
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.Optional;
-import java.util.Properties;
-import java.util.ServiceLoader;
-import java.util.Vector;
 
 import javax.validation.constraints.NotEmpty;
-import javax.validation.constraints.NotNull;
 
-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.CbsRequest;
-import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;
-import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
+import lombok.Getter;
+
 import org.oransc.policyagent.exceptions.ServiceException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.context.properties.ConfigurationProperties;
 import org.springframework.boot.context.properties.EnableConfigurationProperties;
-
-import reactor.core.Disposable;
 import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
 
 @EnableConfigurationProperties
-@ConfigurationProperties("app")
+@ConfigurationProperties()
 public class ApplicationConfig {
-    private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);
-
-    @Value("#{systemEnvironment}")
-    Properties systemEnvironment;
-
-    private Disposable refreshConfigTask = null;
-    private Collection<Observer> observers = new Vector<>();
-
-    private Map<String, RicConfig> ricConfigs = new HashMap<>();
-
     @NotEmpty
-    private String filepath;
-
-    @Autowired
-    public ApplicationConfig() {
-    }
-
-    protected String getLocalConfigurationFilePath() {
-        return this.filepath;
-    }
+    @Getter
+    @Value("${app.filepath}")
+    private String localConfigurationFilePath;
 
-    public synchronized void setFilepath(String filepath) {
-        this.filepath = filepath;
-    }
-
-    public synchronized Collection<RicConfig> getRicConfigs() {
-        return this.ricConfigs.values();
-    }
+    @Value("${server.ssl.key-store-type}")
+    private String sslKeyStoreType = "";
 
-    public synchronized Optional<RicConfig> lookupRicConfigForManagedElement(String managedElementId) {
-        for (RicConfig ricConfig : getRicConfigs()) {
-            if (ricConfig.managedElementIds().contains(managedElementId)) {
-                return Optional.of(ricConfig);
-            }
-        }
-        return Optional.empty();
-    }
+    @Value("${server.ssl.key-store-password}")
+    private String sslKeyStorePassword = "";
 
-    public RicConfig getRic(String ricName) throws ServiceException {
-        for (RicConfig ricConfig : getRicConfigs()) {
-            if (ricConfig.name().equals(ricName)) {
-                return ricConfig;
-            }
-        }
-        throw new ServiceException("Could not find ric: " + ricName);
-    }
+    @Value("${server.ssl.key-store}")
+    private String sslKeyStore = "";
 
-    public void initialize() {
-        stop();
-        loadConfigurationFromFile();
+    @Value("${server.ssl.key-password}")
+    private String sslKeyPassword = "";
 
-        refreshConfigTask = createRefreshTask() //
-            .subscribe(notUsed -> logger.info("Refreshed configuration data"),
-                throwable -> logger.error("Configuration refresh terminated due to exception", throwable),
-                () -> logger.error("Configuration refresh terminated"));
-    }
+    @Value("${app.webclient.trust-store-used}")
+    private boolean sslTrustStoreUsed = false;
 
-    public static enum RicConfigUpdate {
-        ADDED, CHANGED, REMOVED
-    }
+    @Value("${app.webclient.trust-store-password}")
+    private String sslTrustStorePassword = "";
 
-    public interface Observer {
-        void onRicConfigUpdate(RicConfig ric, RicConfigUpdate event);
-    }
+    @Value("${app.webclient.trust-store}")
+    private String sslTrustStore = "";
 
-    public void addObserver(Observer o) {
-        this.observers.add(o);
-    }
+    private Map<String, RicConfig> ricConfigs = new HashMap<>();
 
-    Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
-        return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment);
-    }
+    @Getter
+    private String dmaapConsumerTopicUrl;
 
-    Flux<ApplicationConfig> createRefreshTask() {
-        return getEnvironment(systemEnvironment) //
-            .flatMap(this::createCbsClient) //
-            .flatMapMany(this::periodicConfigurationUpdates) //
-            .map(this::parseRicConfigurationfromConsul) //
-            .onErrorResume(this::onErrorResume);
-    }
+    @Getter
+    private String dmaapProducerTopicUrl;
 
-    Mono<CbsClient> createCbsClient(EnvProperties env) {
-        return CbsClientFactory.createCbsClient(env);
-    }
+    private Map<String, ControllerConfig> controllerConfigs = new HashMap<>();
 
-    private Flux<JsonObject> periodicConfigurationUpdates(CbsClient cbsClient) {
-        final Duration initialDelay = Duration.ZERO;
-        final Duration refreshPeriod = Duration.ofMinutes(1);
-        final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
-        return cbsClient.updates(getConfigRequest, initialDelay, refreshPeriod);
+    public synchronized Collection<RicConfig> getRicConfigs() {
+        return this.ricConfigs.values();
     }
 
-    private <R> Mono<R> onErrorResume(Throwable trowable) {
-        logger.error("Could not refresh application configuration {}", trowable.toString());
-        return Mono.empty();
+    public WebClientConfig getWebClientConfig() {
+        return ImmutableWebClientConfig.builder() //
+            .keyStoreType(this.sslKeyStoreType) //
+            .keyStorePassword(this.sslKeyStorePassword) //
+            .keyStore(this.sslKeyStore) //
+            .keyPassword(this.sslKeyPassword) //
+            .isTrustStoreUsed(this.sslTrustStoreUsed) //
+            .trustStore(this.sslTrustStore) //
+            .trustStorePassword(this.sslTrustStorePassword) //
+            .build();
     }
 
-    private ApplicationConfig parseRicConfigurationfromConsul(JsonObject jsonObject) {
-        try {
-            ApplicationConfigParser parser = new ApplicationConfigParser();
-            parser.parse(jsonObject);
-            setConfiguration(parser.getRicConfigs());
-
-        } catch (ServiceException e) {
-            logger.error("Could not parse configuration {}", e.toString(), e);
+    public synchronized ControllerConfig getControllerConfig(String name) throws ServiceException {
+        ControllerConfig controllerConfig = this.controllerConfigs.get(name);
+        if (controllerConfig == null) {
+            throw new ServiceException("Could not find controller config: " + name);
         }
-        return this;
+        return controllerConfig;
     }
 
-    private class Notification {
-        final RicConfig ric;
-        final RicConfigUpdate event;
-
-        Notification(RicConfig ric, RicConfigUpdate event) {
-            this.ric = ric;
-            this.event = event;
+    public synchronized RicConfig getRic(String ricName) throws ServiceException {
+        RicConfig ricConfig = this.ricConfigs.get(ricName);
+        if (ricConfig == null) {
+            throw new ServiceException("Could not find ric configuration: " + ricName);
         }
+        return ricConfig;
     }
 
-    private void setConfiguration(@NotNull Collection<RicConfig> ricConfigs) {
-        Collection<Notification> notifications = new Vector<>();
-        synchronized (this) {
-            Map<String, RicConfig> newRicConfigs = new HashMap<>();
-            for (RicConfig newConfig : ricConfigs) {
-                RicConfig oldConfig = this.ricConfigs.get(newConfig.name());
-                if (oldConfig == null) {
-                    newRicConfigs.put(newConfig.name(), newConfig);
-                    notifications.add(new Notification(newConfig, RicConfigUpdate.ADDED));
-                    this.ricConfigs.remove(newConfig.name());
-                } else if (!newConfig.equals(newConfig)) {
-                    notifications.add(new Notification(newConfig, RicConfigUpdate.CHANGED));
-                    newRicConfigs.put(newConfig.name(), newConfig);
-                    this.ricConfigs.remove(newConfig.name());
-                } else {
-                    newRicConfigs.put(oldConfig.name(), oldConfig);
-                }
-            }
-            for (RicConfig deletedConfig : this.ricConfigs.values()) {
-                notifications.add(new Notification(deletedConfig, RicConfigUpdate.REMOVED));
-            }
-            this.ricConfigs = newRicConfigs;
+    public static class RicConfigUpdate {
+        public enum Type {
+            ADDED, CHANGED, REMOVED
         }
-        notifyObservers(notifications);
-    }
 
-    private void notifyObservers(Collection<Notification> notifications) {
-        for (Observer observer : this.observers) {
-            for (Notification notif : notifications) {
-                observer.onRicConfigUpdate(notif.ric, notif.event);
-            }
-        }
-    }
+        @Getter
+        private final RicConfig ricConfig;
+        @Getter
+        private final Type type;
 
-    public void stop() {
-        if (refreshConfigTask != null) {
-            refreshConfigTask.dispose();
-            refreshConfigTask = null;
+        RicConfigUpdate(RicConfig ric, Type event) {
+            this.ricConfig = ric;
+            this.type = event;
         }
     }
 
-    /**
-     * Reads the configuration from file.
-     */
-    public void loadConfigurationFromFile() {
-        String filepath = getLocalConfigurationFilePath();
-        if (filepath == null) {
-            logger.debug("No localconfiguration file used");
-            return;
-        }
-        GsonBuilder gsonBuilder = new GsonBuilder();
-        ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
+    public synchronized Flux<RicConfigUpdate> setConfiguration(
+        ApplicationConfigParser.ConfigParserResult parserResult) {
 
-        try (InputStream inputStream = createInputStream(filepath)) {
-            JsonParser parser = new JsonParser();
-            JsonObject rootObject = getJsonElement(parser, inputStream).getAsJsonObject();
-            if (rootObject == null) {
-                throw new JsonSyntaxException("Root is not a json object");
+        Collection<RicConfigUpdate> modifications = new ArrayList<>();
+        this.controllerConfigs = parserResult.controllerConfigs();
+
+        this.dmaapConsumerTopicUrl = parserResult.dmaapConsumerTopicUrl();
+        this.dmaapProducerTopicUrl = parserResult.dmaapProducerTopicUrl();
+
+        Map<String, RicConfig> newRicConfigs = new HashMap<>();
+        for (RicConfig newConfig : parserResult.ricConfigs()) {
+            RicConfig oldConfig = this.ricConfigs.get(newConfig.name());
+            this.ricConfigs.remove(newConfig.name());
+            if (oldConfig == null) {
+                newRicConfigs.put(newConfig.name(), newConfig);
+                modifications.add(new RicConfigUpdate(newConfig, RicConfigUpdate.Type.ADDED));
+            } else if (!newConfig.equals(oldConfig)) {
+                modifications.add(new RicConfigUpdate(newConfig, RicConfigUpdate.Type.CHANGED));
+                newRicConfigs.put(newConfig.name(), newConfig);
+            } else {
+                newRicConfigs.put(oldConfig.name(), oldConfig);
             }
-            ApplicationConfigParser appParser = new ApplicationConfigParser();
-            appParser.parse(rootObject);
-            setConfiguration(appParser.getRicConfigs());
-            logger.info("Local configuration file loaded: {}", filepath);
-        } catch (JsonSyntaxException | ServiceException | IOException e) {
-            logger.trace("Local configuration file not loaded: {}", filepath, e);
         }
-    }
-
-    JsonElement getJsonElement(JsonParser parser, InputStream inputStream) {
-        return parser.parse(new InputStreamReader(inputStream));
-    }
+        for (RicConfig deletedConfig : this.ricConfigs.values()) {
+            modifications.add(new RicConfigUpdate(deletedConfig, RicConfigUpdate.Type.REMOVED));
+        }
+        this.ricConfigs = newRicConfigs;
 
-    InputStream createInputStream(@NotNull String filepath) throws IOException {
-        return new BufferedInputStream(new FileInputStream(filepath));
+        return Flux.fromIterable(modifications);
     }
 }