2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2018 - 2020 Nokia. All rights reserved.s
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.dcae;
24 import static java.lang.String.format;
26 import com.google.common.annotations.VisibleForTesting;
27 import com.google.common.reflect.TypeToken;
28 import com.google.gson.Gson;
29 import com.networknt.schema.JsonSchema;
30 import io.vavr.Function1;
31 import io.vavr.collection.HashMap;
32 import io.vavr.collection.Map;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.lang.reflect.Type;
36 import java.nio.file.Path;
37 import java.nio.file.Paths;
38 import java.util.List;
39 import javax.annotation.Nullable;
40 import org.apache.commons.configuration.ConfigurationException;
41 import org.apache.commons.configuration.PropertiesConfiguration;
42 import org.onap.dcae.common.EventTransformation;
43 import org.onap.dcae.common.configuration.AuthMethodType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * Abstraction over application configuration.
49 * Its job is to provide easily discoverable (by method names lookup) and type safe access to configuration properties.
51 public class ApplicationSettings {
53 private static final String EVENT_TRANSFORM_FILE_PATH = "./etc/eventTransform.json";
54 private static final String COULD_NOT_FIND_FILE = "Couldn't find file " + EVENT_TRANSFORM_FILE_PATH;
56 private static final Logger log = LoggerFactory.getLogger(ApplicationSettings.class);
57 private static final String FALLBACK_VES_VERSION = "v5";
58 private static final int DISABLED = -1;
59 private static final int ENABLED = 1;
60 private final String appInvocationDir;
61 private final String configurationFileLocation;
62 private final PropertiesConfiguration properties = new PropertiesConfiguration();
63 private final Map<String, JsonSchema> loadedJsonSchemas;
64 private final List<EventTransformation> eventTransformations;
66 public ApplicationSettings(String[] args, Function1<String[], Map<String, String>> argsParser) {
67 this(args, argsParser, System.getProperty("user.dir"));
70 public ApplicationSettings(String[] args, Function1<String[], Map<String, String>> argsParser, String appInvocationDir) {
71 this.appInvocationDir = appInvocationDir;
72 properties.setDelimiterParsingDisabled(true);
73 Map<String, String> parsedArgs = argsParser.apply(args);
74 configurationFileLocation = findOutConfigurationFileLocation(parsedArgs);
75 loadPropertiesFromFile();
76 parsedArgs.filterKeys(k -> !"c".equals(k)).forEach(this::addOrUpdate);
77 String collectorSchemaFile = properties.getString("collector.schema.file",
78 format("{\"%s\":\"etc/CommonEventFormat_28.4.1.json\"}", FALLBACK_VES_VERSION));
79 loadedJsonSchemas = new JSonSchemasSupplier().loadJsonSchemas(collectorSchemaFile);
80 eventTransformations = loadEventTransformations();
83 public void reloadProperties() {
85 properties.load(configurationFileLocation);
87 } catch (ConfigurationException ex) {
88 log.error("Cannot load properties cause:", ex);
89 throw new ApplicationException(ex);
93 public Map<String, String> validAuthorizationCredentials() {
94 return prepareUsersMap(properties.getString("header.authlist", null));
96 public Path configurationFileLocation() {
97 return Paths.get(configurationFileLocation);
100 public boolean eventSchemaValidationEnabled() {
101 return properties.getInt("collector.schema.checkflag", DISABLED) > 0;
104 public JsonSchema jsonSchema(String version) {
105 return loadedJsonSchemas.get(version)
106 .orElse(loadedJsonSchemas.get(FALLBACK_VES_VERSION))
107 .getOrElseThrow(() -> new IllegalStateException("No fallback schema present in application."));
110 public boolean isVersionSupported(String version){
111 return loadedJsonSchemas.containsKey(version);
114 public int httpPort() {
115 return properties.getInt("collector.service.port", 8080);
118 public int httpsPort() {
119 return properties.getInt("collector.service.secure.port", 8443);
122 public int configurationUpdateFrequency() {
123 return properties.getInt("collector.dynamic.config.update.frequency", 5);
126 public boolean httpsEnabled() {
127 return httpsPort() > 0;
130 public boolean eventTransformingEnabled() {
131 return properties.getInt("event.transform.flag", ENABLED) > 0;
134 public String keystorePasswordFileLocation() {
135 return prependWithUserDirOnRelative(properties.getString("collector.keystore.passwordfile", "etc/passwordfile"));
138 public String keystoreFileLocation() {
139 return prependWithUserDirOnRelative(properties.getString("collector.keystore.file.location", "etc/keystore"));
142 public String truststorePasswordFileLocation() {
143 return prependWithUserDirOnRelative(properties.getString("collector.truststore.passwordfile", "etc/trustpasswordfile"));
146 public String truststoreFileLocation() {
147 return prependWithUserDirOnRelative(properties.getString("collector.truststore.file.location", "etc/truststore"));
150 public String exceptionConfigFileLocation() {
151 return properties.getString("exceptionConfig", null);
154 public String dMaaPConfigurationFileLocation() {
155 return prependWithUserDirOnRelative(properties.getString("collector.dmaapfile", "etc/DmaapConfig.json"));
158 public String certSubjectMatcher(){
159 return prependWithUserDirOnRelative(properties.getString("collector.cert.subject.matcher", "etc/certSubjectMatcher.properties"));
162 public String authMethod(){
163 return properties.getString("auth.method", AuthMethodType.NO_AUTH.value());
166 public Map<String, String[]> getDmaapStreamIds() {
167 String streamIdsProperty = properties.getString("collector.dmaap.streamid", null);
168 if (streamIdsProperty == null) {
169 return HashMap.empty();
171 return convertDMaaPStreamsPropertyToMap(streamIdsProperty);
175 public boolean getExternalSchemaValidationCheckflag() {
176 return properties.getInt("collector.externalSchema.checkflag", DISABLED) > 0;
179 public String getExternalSchemaSchemasLocation() {
180 return properties.getString("collector.externalSchema.schemasLocation", "./etc/externalRepo");
183 public String getExternalSchemaMappingFileLocation() {
184 return properties.getString("collector.externalSchema.mappingFileLocation", "./etc/externalRepo/schema-map.json");
187 public String getExternalSchemaSchemaRefPath() {
188 return properties.getString("event.externalSchema.schemaRefPath", "/event/stndDefinedFields/schemaReference");
191 public String getExternalSchemaStndDefinedDataPath() {
192 return properties.getString("event.externalSchema.stndDefinedDataPath", "/event/stndDefinedFields/data");
195 public List<EventTransformation> getEventTransformations() {
196 return eventTransformations;
199 public String getApiVersionDescriptionFilepath() {
200 return properties.getString("collector.description.api.version.location", "etc/api_version_description.json");
203 private void loadPropertiesFromFile() {
205 properties.load(configurationFileLocation);
206 } catch (ConfigurationException ex) {
207 log.error("Cannot load properties cause:", ex);
208 throw new ApplicationException(ex);
212 private void addOrUpdate(String key, String value) {
213 if (properties.containsKey(key)) {
214 properties.setProperty(key, value);
216 properties.addProperty(key, value);
220 private String findOutConfigurationFileLocation(Map<String, String> parsedArgs) {
221 return prependWithUserDirOnRelative(parsedArgs.get("c").getOrElse("etc/collector.properties"));
224 private Map<String, String> prepareUsersMap(@Nullable String allowedUsers) {
225 return allowedUsers == null ? HashMap.empty()
226 : io.vavr.collection.List.of(allowedUsers.split("\\|"))
227 .map(t->t.split(","))
228 .toMap(t-> t[0].trim(), t -> t[1].trim());
231 private Map<String, String[]> convertDMaaPStreamsPropertyToMap(String streamIdsProperty) {
232 java.util.HashMap<String, String[]> domainToStreamIdsMapping = new java.util.HashMap<>();
233 String[] topics = streamIdsProperty.split("\\|");
234 for (String t : topics) {
235 String domain = t.split("=")[0];
236 String[] streamIds = t.split("=")[1].split(",");
237 domainToStreamIdsMapping.put(domain, streamIds);
239 return HashMap.ofAll(domainToStreamIdsMapping);
242 private String prependWithUserDirOnRelative(String filePath) {
243 if (!Paths.get(filePath).isAbsolute()) {
244 filePath = Paths.get(appInvocationDir, filePath).toString();
249 private List<EventTransformation> loadEventTransformations() {
250 Type EVENT_TRANSFORM_LIST_TYPE = new TypeToken<List<EventTransformation>>() {}.getType();
252 try (FileReader fr = new FileReader(EVENT_TRANSFORM_FILE_PATH)) {
253 log.info("parse " + EVENT_TRANSFORM_FILE_PATH + " file");
254 return new Gson().fromJson(fr, EVENT_TRANSFORM_LIST_TYPE);
255 } catch (IOException e) {
256 log.error(COULD_NOT_FIND_FILE, e);
257 throw new ApplicationException(COULD_NOT_FIND_FILE, e);
262 String getStringDirectly(String key) {
263 return properties.getString(key);