6ea94ab5b5f26b45dfb9f37305bd523da2b34a53
[dcaegen2/collectors/ves.git] / src / test / java / org / onap / dcae / ApplicationSettingsTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dcaegen2.collectors.ves
4  * ================================================================================
5  * Copyright (C) 2018 - 2020 Nokia. All rights reserved.
6  * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
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 com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.networknt.schema.JsonSchema;
27 import io.vavr.collection.HashMap;
28 import io.vavr.collection.Map;
29 import org.junit.Test;
30
31 import java.io.File;
32 import java.io.IOException;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.util.Arrays;
37 import java.util.Objects;
38
39 import static java.util.Collections.singletonList;
40 import static org.junit.Assert.assertArrayEquals;
41 import static org.junit.Assert.assertEquals;
42 import static org.junit.Assert.assertFalse;
43 import static org.junit.Assert.assertNull;
44 import static org.junit.Assert.assertTrue;
45 import static org.onap.dcae.CLIUtils.processCmdLine;
46 import static org.onap.dcae.TestingUtilities.createTemporaryFile;
47
48 public class ApplicationSettingsTest {
49
50     private static final String SAMPLE_JSON_SCHEMA = "{"
51             + "  \"type\": \"object\","
52             + "  \"properties\": {"
53             + "     \"state\": { \"type\": \"string\" }"
54             + "  }"
55             + "}";
56
57     @Test
58     public void shouldMakeApplicationSettingsOutOfCLIArguments() {
59         // given
60         String[] cliArguments = {"-param1", "param1value", "-param2", "param2value"};
61
62         // when
63         ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
64         String param1value = configurationAccessor.getStringDirectly("param1");
65         String param2value = configurationAccessor.getStringDirectly("param2");
66
67         // then
68         assertEquals("param1value", param1value);
69         assertEquals("param2value", param2value);
70     }
71
72     @Test
73     public void shouldMakeApplicationSettingsOutOfCLIArgumentsAndAConfigurationFile()
74             throws IOException {
75         // given
76         File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
77         Files.write(tempConfFile.toPath(), Arrays.asList("section.subSection1=abc", "section.subSection2=zxc"));
78         tempConfFile.deleteOnExit();
79         String[] cliArguments = {"-param1", "param1value", "-param2", "param2value", "-c", tempConfFile.toString()};
80
81         // when
82         ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
83         String param1value = configurationAccessor.getStringDirectly("param1");
84         String param2value = configurationAccessor.getStringDirectly("param2");
85         String fromFileParam1Value = configurationAccessor.getStringDirectly("section.subSection1");
86         String fromFileParam2Value = configurationAccessor.getStringDirectly("section.subSection2");
87
88         // then
89         assertEquals("param1value", param1value);
90         assertEquals("param2value", param2value);
91         assertEquals("abc", fromFileParam1Value);
92         assertEquals("zxc", fromFileParam2Value);
93     }
94
95     @Test
96     public void shouldCLIArgumentsOverrideConfigFileParameters() throws IOException {
97         // given
98         String[] cliArguments = {"-section.subSection1", "abc"};
99         File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
100         Files.write(tempConfFile.toPath(), singletonList("section.subSection1=zxc"));
101         tempConfFile.deleteOnExit();
102
103         // when
104         ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
105         String actuallyOverridenByCLIParam = configurationAccessor.getStringDirectly("section.subSection1");
106
107         // then
108         assertEquals("abc", actuallyOverridenByCLIParam);
109     }
110
111     @Test
112     public void shouldReturnHTTPPort() throws IOException {
113         // when
114         int applicationPort = fromTemporaryConfiguration("collector.service.port=8090")
115                 .httpPort();
116
117         // then
118         assertEquals(8090, applicationPort);
119     }
120
121     @Test
122     public void shouldReturnDefaultHTTPPort() throws IOException {
123         // when
124         int applicationPort = fromTemporaryConfiguration().httpPort();
125
126         // then
127         assertEquals(8080, applicationPort);
128     }
129
130     @Test
131     public void shouldReturnIfHTTPSIsEnabled() throws IOException {
132         // when
133         boolean httpsEnabled = fromTemporaryConfiguration("collector.service.secure.port=8443")
134                 .httpsEnabled();
135
136         // then
137         assertTrue(httpsEnabled);
138     }
139
140     @Test
141     public void shouldReturnIfHTTPIsEnabled() throws IOException {
142         // when
143         boolean httpsEnabled = fromTemporaryConfiguration("collector.service.port=8080").httpsEnabled();
144         // then
145         assertTrue(httpsEnabled);
146     }
147
148     @Test
149     public void shouldByDefaultHTTPSBeDisabled() throws IOException {
150         // when
151         boolean httpsEnabled = fromTemporaryConfiguration().httpsEnabled();
152
153         // then
154         assertTrue(httpsEnabled);
155     }
156
157     @Test
158     public void shouldReturnHTTPSPort() throws IOException {
159         // when
160         int httpsPort = fromTemporaryConfiguration("collector.service.secure.port=8443")
161                 .httpsPort();
162
163         // then
164         assertEquals(8443, httpsPort);
165     }
166
167     @Test
168     public void shouldReturnConfigurationUpdateInterval() throws IOException {
169         // when
170         int updateFrequency = fromTemporaryConfiguration("collector.dynamic.config.update.frequency=10")
171                 .configurationUpdateFrequency();
172
173         // then
174         assertEquals(10, updateFrequency);
175     }
176
177     @Test
178     public void shouldReturnDefaultConfigurationUpdateInterval() throws IOException {
179         // when
180         int updateFrequency = fromTemporaryConfiguration()
181                 .configurationUpdateFrequency();
182
183         // then
184         assertEquals(5, updateFrequency);
185     }
186
187     @Test
188     public void shouldReturnLocationOfThePasswordFile() throws IOException {
189         // when
190         String passwordFileLocation = fromTemporaryConfiguration("collector.keystore.passwordfile=/somewhere/password")
191                 .keystorePasswordFileLocation();
192
193         // then
194         assertEquals(sanitizePath("/somewhere/password"), passwordFileLocation);
195     }
196
197     @Test
198     public void shouldReturnDefaultLocationOfThePasswordFile() throws IOException {
199         // when
200         String passwordFileLocation = fromTemporaryConfiguration().keystorePasswordFileLocation();
201
202         // then
203         assertEquals(sanitizePath("etc/passwordfile"), passwordFileLocation);
204     }
205
206     @Test
207     public void shouldReturnLocationOfTheKeystoreFile() throws IOException {
208         // when
209         String keystoreFileLocation = fromTemporaryConfiguration("collector.keystore.file.location=/somewhere/keystore")
210                 .keystoreFileLocation();
211
212         // then
213         assertEquals(sanitizePath("/somewhere/keystore"), keystoreFileLocation);
214     }
215
216     @Test
217     public void shouldReturnLocationOfTheDefaultKeystoreFile() throws IOException {
218         // when
219         String keystoreFileLocation = fromTemporaryConfiguration().keystoreFileLocation();
220
221         // then
222         assertEquals(sanitizePath("etc/keystore"), keystoreFileLocation);
223     }
224
225     @Test
226     public void shouldReturnDMAAPConfigFileLocation() throws IOException {
227         // when
228         String dmaapConfigFileLocation = fromTemporaryConfiguration("collector.dmaapfile=/somewhere/dmaapFile")
229                 .dMaaPConfigurationFileLocation();
230
231         // then
232         assertEquals(sanitizePath("/somewhere/dmaapFile"), dmaapConfigFileLocation);
233     }
234
235     @Test
236     public void shouldReturnDefaultDMAAPConfigFileLocation() throws IOException {
237         // when
238         String dmaapConfigFileLocation = fromTemporaryConfiguration().dMaaPConfigurationFileLocation();
239
240         // then
241         assertEquals(sanitizePath("etc/DmaapConfig.json"), dmaapConfigFileLocation);
242     }
243
244     @Test
245     public void shouldTellIfSchemaValidationIsEnabled() throws IOException {
246         // when
247         boolean jsonSchemaValidationEnabled = fromTemporaryConfiguration("collector.schema.checkflag=1")
248                 .eventSchemaValidationEnabled();
249
250         // then
251         assertTrue(jsonSchemaValidationEnabled);
252     }
253
254     @Test
255     public void shouldByDefaultSchemaValidationBeDisabled() throws IOException {
256         // when
257         boolean jsonSchemaValidationEnabled = fromTemporaryConfiguration().eventSchemaValidationEnabled();
258
259         // then
260         assertFalse(jsonSchemaValidationEnabled);
261     }
262
263     @Test
264     public void shouldReportValidateJSONSchemaErrorWhenJsonContainsIntegerValueNotString() throws IOException {
265         // when
266         Path temporarySchemaFile = createTemporaryFile(SAMPLE_JSON_SCHEMA);
267
268         // when
269         JsonSchema schema = fromTemporaryConfiguration(
270                 String.format("collector.schema.file={\"v1\": \"%s\"}", temporarySchemaFile))
271                 .jsonSchema("v1");
272
273         // then
274         JsonNode incorrectTestObject = new ObjectMapper().readTree("{ \"state\": 1 }");
275
276         assertFalse(schema.validate(incorrectTestObject).isEmpty());
277
278     }
279
280     @Test
281     public void shouldDoNotReportAnyValidateJSONSchemaError() throws IOException {
282         // when
283         Path temporarySchemaFile = createTemporaryFile(SAMPLE_JSON_SCHEMA);
284
285         // when
286         JsonSchema schema = fromTemporaryConfiguration(
287                 String.format("collector.schema.file={\"v1\": \"%s\"}", temporarySchemaFile))
288                 .jsonSchema("v1");
289
290         // then
291         JsonNode correctTestObject = new ObjectMapper().readTree("{ \"state\": \"hi\" }");
292         assertTrue(schema.validate(correctTestObject).isEmpty());
293     }
294
295     @Test
296     public void shouldReturnExceptionConfigFileLocation() throws IOException {
297         // when
298         String exceptionConfigFileLocation = fromTemporaryConfiguration("exceptionConfig=/somewhere/exceptionFile")
299                 .exceptionConfigFileLocation();
300
301         // then
302         assertEquals("/somewhere/exceptionFile", exceptionConfigFileLocation);
303     }
304
305     @Test
306     public void shouldReturnDefaultExceptionConfigFileLocation() throws IOException {
307         // when
308         String exceptionConfigFileLocation = fromTemporaryConfiguration().exceptionConfigFileLocation();
309
310         // then
311         assertNull(exceptionConfigFileLocation);
312     }
313
314
315     @Test
316     public void shouldReturnDMAAPStreamId() throws IOException {
317         // given
318         Map<String, String[]> expected = HashMap.of(
319                 "log", new String[]{"ves-syslog", "ves-auditlog"},
320                 "fault", new String[]{"ves-fault"}
321         );
322
323         // when
324         Map<String, String[]> dmaapStreamID = fromTemporaryConfiguration(
325                 "collector.dmaap.streamid=fault=ves-fault|log=ves-syslog,ves-auditlog")
326                 .getDmaapStreamIds();
327
328         // then
329         assertArrayEquals(expected.get("log").get(), Objects.requireNonNull(dmaapStreamID).get("log").get());
330         assertArrayEquals(expected.get("fault").get(), Objects.requireNonNull(dmaapStreamID).get("fault").get());
331         assertEquals(expected.keySet(), dmaapStreamID.keySet());
332     }
333
334     @Test
335     public void shouldReturnDefaultDMAAPStreamId() throws IOException {
336         // when
337         Map<String, String[]> dmaapStreamID = fromTemporaryConfiguration().getDmaapStreamIds();
338
339         // then
340         assertEquals(dmaapStreamID, HashMap.empty());
341     }
342
343     @Test
344     public void shouldAuthorizationBeDisabledByDefault() throws IOException {
345         // when
346         boolean authorizationEnabled = fromTemporaryConfiguration().authMethod().contains("noAuth");
347
348         // then
349         assertTrue(authorizationEnabled);
350     }
351
352     @Test
353     public void shouldReturnValidCredentials() throws IOException {
354         // when
355         Map<String, String> allowedUsers = fromTemporaryConfiguration(
356                 "header.authlist=pasza,c2ltcGxlcGFzc3dvcmQNCg==|someoneelse,c2ltcGxlcGFzc3dvcmQNCg=="
357         ).validAuthorizationCredentials();
358
359         // then
360         assertEquals("c2ltcGxlcGFzc3dvcmQNCg==", allowedUsers.get("pasza").get());
361         assertEquals("c2ltcGxlcGFzc3dvcmQNCg==", allowedUsers.get("someoneelse").get());
362     }
363
364     @Test
365     public void shouldbyDefaultThereShouldBeNoValidCredentials() throws IOException {
366         // when
367         Map<String, String> userToBase64PasswordDelimitedByCommaSeparatedByPipes = fromTemporaryConfiguration().
368                 validAuthorizationCredentials();
369
370         // then
371         assertTrue(userToBase64PasswordDelimitedByCommaSeparatedByPipes.isEmpty());
372     }
373
374     @Test
375     public void shouldReturnIfEventTransformingIsEnabled() throws IOException {
376         // when
377         boolean isEventTransformingEnabled = fromTemporaryConfiguration("event.transform.flag=0")
378                 .eventTransformingEnabled();
379
380         // then
381         assertFalse(isEventTransformingEnabled);
382     }
383
384     @Test
385     public void shouldEventTransformingBeEnabledByDefault() throws IOException {
386         // when
387         boolean isEventTransformingEnabled = fromTemporaryConfiguration().eventTransformingEnabled();
388
389         // then
390         assertTrue(isEventTransformingEnabled);
391     }
392
393     @Test
394     public void shouldReturnCambriaConfigurationFileLocation() throws IOException {
395         // when
396         String cambriaConfigurationFileLocation = fromTemporaryConfiguration(
397                 "collector.dmaapfile=/somewhere/dmaapConfig")
398                 .dMaaPConfigurationFileLocation();
399
400         // then
401         assertEquals(sanitizePath("/somewhere/dmaapConfig"), cambriaConfigurationFileLocation);
402     }
403
404     @Test
405     public void shouldReturnDefaultCambriaConfigurationFileLocation() throws IOException {
406         // when
407         String cambriaConfigurationFileLocation = fromTemporaryConfiguration()
408                 .dMaaPConfigurationFileLocation();
409
410         // then
411         assertEquals(sanitizePath("etc/DmaapConfig.json"), cambriaConfigurationFileLocation);
412     }
413
414     @Test
415     public void shouldReturnDefaultExternalSchemaSchemasLocation() throws IOException {
416         //when
417         String externalSchemaSchemasLocation = fromTemporaryConfiguration()
418                 .getExternalSchemaSchemasLocation();
419
420         //then
421         assertEquals(sanitizePath("./etc/externalRepo"), externalSchemaSchemasLocation);
422     }
423
424     @Test
425     public void shouldReturnDefaultExternalSchemaMappingFileLocation() throws IOException {
426         //when
427         String externalSchemaMappingFileLocation = fromTemporaryConfiguration()
428                 .getExternalSchemaMappingFileLocation();
429
430         //then
431         assertEquals(sanitizePath("./etc/externalRepo/schema-map.json"), externalSchemaMappingFileLocation);
432     }
433
434     @Test
435     public void shouldReturnDefaultExternalSchemaSchemaRefPath() throws IOException {
436         //when
437         String externalSchemaSchemaRefPath = fromTemporaryConfiguration()
438                 .getExternalSchemaSchemaRefPath();
439
440         //then
441         assertEquals(sanitizePath("/event/stndDefinedFields/schemaReference"), externalSchemaSchemaRefPath);
442     }
443
444     @Test
445     public void shouldReturnDefaultExternalSchemaStndDefinedDataPath() throws IOException {
446         //when
447         String externalSchemaStndDefinedDataPath = fromTemporaryConfiguration()
448                 .getExternalSchemaStndDefinedDataPath();
449
450         //then
451         assertEquals(sanitizePath("/event/stndDefinedFields/data"), externalSchemaStndDefinedDataPath);
452     }
453
454     @Test
455     public void shouldReturnEnabledExternalSchema2ndStageValidation() throws IOException {
456         //when
457         boolean externalSchema2ndStageValidation = fromTemporaryConfiguration("collector.externalSchema.2ndStageValidation=-1")
458                 .getExternalSchemaValidationCheckflag();
459
460         //then
461         assertFalse(externalSchema2ndStageValidation);
462     }
463
464     private static ApplicationSettings fromTemporaryConfiguration(String... fileLines)
465             throws IOException {
466         File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
467         Files.write(tempConfFile.toPath(), Arrays.asList(fileLines));
468         tempConfFile.deleteOnExit();
469         return new ApplicationSettings(new String[]{"-c", tempConfFile.toString()}, args -> processCmdLine(args), "");
470     }
471
472     private String sanitizePath(String path) {
473         return Paths.get(path).toString();
474     }
475 }