Fix bug throwing exception when first event is collected
[dcaegen2/collectors/ves.git] / src / main / java / org / onap / dcae / ApplicationSettings.java
1 /*
2  * ============LICENSE_START=======================================================
3  * PROJECT
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.dcae;
23
24 import static java.lang.String.format;
25
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;
46
47 /**
48  * Abstraction over application configuration.
49  * Its job is to provide easily discoverable (by method names lookup) and type safe access to configuration properties.
50  */
51 public class ApplicationSettings {
52
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;
55
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;
65
66     public ApplicationSettings(String[] args, Function1<String[], Map<String, String>> argsParser) {
67         this(args, argsParser, System.getProperty("user.dir"));
68     }
69
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();
81     }
82
83     public void reloadProperties() {
84         try {
85             properties.load(configurationFileLocation);
86             properties.refresh();
87         } catch (ConfigurationException ex) {
88             log.error("Cannot load properties cause:", ex);
89             throw new ApplicationException(ex);
90         }
91     }
92
93     public Map<String, String> validAuthorizationCredentials() {
94         return prepareUsersMap(properties.getString("header.authlist", null));
95     }
96     public Path configurationFileLocation() {
97         return Paths.get(configurationFileLocation);
98     }
99
100     public boolean eventSchemaValidationEnabled() {
101         return properties.getInt("collector.schema.checkflag", DISABLED) > 0;
102     }
103
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."));
108     }
109
110     public boolean isVersionSupported(String version){
111        return loadedJsonSchemas.containsKey(version);
112     }
113
114     public int httpPort() {
115         return properties.getInt("collector.service.port", 8080);
116     }
117
118     public int httpsPort() {
119         return properties.getInt("collector.service.secure.port", 8443);
120     }
121
122     public int configurationUpdateFrequency() {
123         return properties.getInt("collector.dynamic.config.update.frequency", 5);
124     }
125
126     public boolean httpsEnabled() {
127         return httpsPort() > 0;
128     }
129
130     public boolean eventTransformingEnabled() {
131         return properties.getInt("event.transform.flag", ENABLED) > 0;
132     }
133
134     public String keystorePasswordFileLocation() {
135         return prependWithUserDirOnRelative(properties.getString("collector.keystore.passwordfile", "etc/passwordfile"));
136     }
137
138     public String keystoreFileLocation() {
139         return prependWithUserDirOnRelative(properties.getString("collector.keystore.file.location", "etc/keystore"));
140     }
141
142     public String truststorePasswordFileLocation() {
143         return prependWithUserDirOnRelative(properties.getString("collector.truststore.passwordfile", "etc/trustpasswordfile"));
144     }
145
146     public String truststoreFileLocation() {
147         return prependWithUserDirOnRelative(properties.getString("collector.truststore.file.location", "etc/truststore"));
148     }
149
150     public String exceptionConfigFileLocation() {
151         return properties.getString("exceptionConfig", null);
152     }
153
154     public String dMaaPConfigurationFileLocation() {
155         return prependWithUserDirOnRelative(properties.getString("collector.dmaapfile", "etc/DmaapConfig.json"));
156     }
157
158     public String certSubjectMatcher(){
159         return prependWithUserDirOnRelative(properties.getString("collector.cert.subject.matcher", "etc/certSubjectMatcher.properties"));
160     }
161
162     public String authMethod(){
163         return properties.getString("auth.method", AuthMethodType.NO_AUTH.value());
164     }
165
166     public Map<String, String[]> getDmaapStreamIds() {
167         String streamIdsProperty = properties.getString("collector.dmaap.streamid", null);
168         if (streamIdsProperty == null) {
169             return HashMap.empty();
170         } else {
171             return convertDMaaPStreamsPropertyToMap(streamIdsProperty);
172         }
173     }
174
175     public boolean getExternalSchemaValidationCheckflag() {
176         return properties.getInt("collector.externalSchema.checkflag", DISABLED) > 0;
177     }
178
179     public String getExternalSchemaSchemasLocation() {
180         return properties.getString("collector.externalSchema.schemasLocation", "./etc/externalRepo");
181     }
182
183     public String getExternalSchemaMappingFileLocation() {
184         return properties.getString("collector.externalSchema.mappingFileLocation", "./etc/externalRepo/schema-map.json");
185     }
186
187     public String getExternalSchemaSchemaRefPath() {
188         return properties.getString("event.externalSchema.schemaRefPath", "/event/stndDefinedFields/schemaReference");
189     }
190
191     public String getExternalSchemaStndDefinedDataPath() {
192         return properties.getString("event.externalSchema.stndDefinedDataPath", "/event/stndDefinedFields/data");
193     }
194
195     public List<EventTransformation> getEventTransformations() {
196         return eventTransformations;
197     }
198
199     public String getApiVersionDescriptionFilepath() {
200         return properties.getString("collector.description.api.version.location", "etc/api_version_description.json");
201     }
202
203     private void loadPropertiesFromFile() {
204         try {
205             properties.load(configurationFileLocation);
206         } catch (ConfigurationException ex) {
207             log.error("Cannot load properties cause:", ex);
208             throw new ApplicationException(ex);
209         }
210     }
211
212     private void addOrUpdate(String key, String value) {
213         if (properties.containsKey(key)) {
214             properties.setProperty(key, value);
215         } else {
216             properties.addProperty(key, value);
217         }
218     }
219
220     private String findOutConfigurationFileLocation(Map<String, String> parsedArgs) {
221         return prependWithUserDirOnRelative(parsedArgs.get("c").getOrElse("etc/collector.properties"));
222     }
223
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());
229     }
230
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);
238         }
239         return HashMap.ofAll(domainToStreamIdsMapping);
240     }
241
242     private String prependWithUserDirOnRelative(String filePath) {
243         if (!Paths.get(filePath).isAbsolute()) {
244             filePath = Paths.get(appInvocationDir, filePath).toString();
245         }
246         return filePath;
247     }
248
249     private List<EventTransformation> loadEventTransformations() {
250         Type EVENT_TRANSFORM_LIST_TYPE = new TypeToken<List<EventTransformation>>() {}.getType();
251
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);
258         }
259     }
260
261     @VisibleForTesting
262     String getStringDirectly(String key) {
263         return properties.getString(key);
264     }
265 }
266