summaryrefslogtreecommitdiffstats
path: root/src/test
diff options
context:
space:
mode:
Diffstat (limited to 'src/test')
-rw-r--r--src/test/java/org/onap/dcae/ApplicationSettingsTest.java417
-rw-r--r--src/test/java/org/onap/dcae/commonFunction/ApiExceptionTest.java59
-rw-r--r--src/test/java/org/onap/dcae/commonFunction/CommonStartupTest.java127
-rw-r--r--src/test/java/org/onap/dcae/commonFunction/ConfigProcessorAdapterTest.java66
-rw-r--r--src/test/java/org/onap/dcae/commonFunction/EventProcessorTest.java90
-rw-r--r--src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPConfigurationParserTest.java114
-rw-r--r--src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPEventPublisherTest.java89
-rw-r--r--src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPPublishersCacheTest.java126
-rw-r--r--src/test/java/org/onap/dcae/vestest/AnyNodeTest.java63
-rw-r--r--src/test/java/org/onap/dcae/vestest/EventTransformTest.java181
-rw-r--r--src/test/java/org/onap/dcae/vestest/InputJsonValidation.java151
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestCommonStartup.java171
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestConfigProcessor.java309
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestCustomExceptionLoader.java72
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestDefaultConfiguration.java (renamed from src/test/java/org/onap/dcae/vestest/TestDmaapPropertyReader.java)58
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestEventProcessor.java104
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestEventReceipt.java46
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestFetchConfig.java81
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestJsonSchemaValidation.java57
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestLoadDynamicConfig.java82
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestSchemaValidation.java136
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestVESLogger.java75
-rw-r--r--src/test/java/org/onap/dcae/vestest/TestingUtilities.java93
-rw-r--r--src/test/java/org/onap/dcae/vestest/VesCollectorJunitTest.java95
-rw-r--r--src/test/java/org/onap/dcae/vestest/VesCollectorJunitTestRunner.java56
-rw-r--r--src/test/resources/controller-config.json17
-rw-r--r--src/test/resources/controller-config_dmaap_ip.json239
-rw-r--r--src/test/resources/controller-config_singleline_ip.json1
-rw-r--r--src/test/resources/testDmaapConfig_ip.json (renamed from src/test/resources/testDmaapConfig.json)0
-rw-r--r--src/test/resources/testFullDmaapConfig_gen2.json24
-rw-r--r--src/test/resources/testParseDMaaPCredentialsGen2.json21
-rw-r--r--src/test/resources/testParseDMaaPCredentialsLegacy.json26
-rw-r--r--src/test/resources/testParseDMaaPGen2.json12
-rw-r--r--src/test/resources/testParseDMaaPLegacy.json21
-rw-r--r--src/test/resources/test_anynode_class.json9
-rw-r--r--src/test/resources/test_collector_ip_op.properties16
-rw-r--r--src/test/resources/testcollector.properties89
37 files changed, 2262 insertions, 1131 deletions
diff --git a/src/test/java/org/onap/dcae/ApplicationSettingsTest.java b/src/test/java/org/onap/dcae/ApplicationSettingsTest.java
new file mode 100644
index 00000000..b162cef2
--- /dev/null
+++ b/src/test/java/org/onap/dcae/ApplicationSettingsTest.java
@@ -0,0 +1,417 @@
+package org.onap.dcae;
+
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+import io.vavr.collection.HashMap;
+import io.vavr.collection.Map;
+import org.json.JSONObject;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.Arrays;
+import java.util.Objects;
+
+import static java.util.Collections.singletonList;
+import static org.junit.Assert.*;
+import static org.onap.dcae.CLIUtils.processCmdLine;
+
+public class ApplicationSettingsTest {
+
+ @Test
+ public void shouldMakeApplicationSettingsOutOfCLIArguments() {
+ // given
+ String[] cliArguments = {"-param1", "param1value", "-param2", "param2value"};
+
+ // when
+ ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
+ String param1value = configurationAccessor.getStringDirectly("param1");
+ String param2value = configurationAccessor.getStringDirectly("param2");
+
+ // then
+ assertEquals("param1value", param1value);
+ assertEquals("param2value", param2value);
+ }
+
+ @Test
+ public void shouldMakeApplicationSettingsOutOfCLIArgumentsAndAConfigurationFile()
+ throws IOException {
+ // given
+ File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
+ Files.write(tempConfFile.toPath(), Arrays.asList("section.subSection1=abc", "section.subSection2=zxc"));
+ tempConfFile.deleteOnExit();
+ String[] cliArguments = {"-param1", "param1value", "-param2", "param2value", "-c", tempConfFile.toString()};
+
+ // when
+ ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
+ String param1value = configurationAccessor.getStringDirectly("param1");
+ String param2value = configurationAccessor.getStringDirectly("param2");
+ String fromFileParam1Value = configurationAccessor.getStringDirectly("section.subSection1");
+ String fromFileParam2Value = configurationAccessor.getStringDirectly("section.subSection2");
+
+ // then
+ assertEquals("param1value", param1value);
+ assertEquals("param2value", param2value);
+ assertEquals("abc", fromFileParam1Value);
+ assertEquals("zxc", fromFileParam2Value);
+ }
+
+ @Test
+ public void shouldCLIArgumentsOverrideConfigFileParameters() throws IOException {
+ // given
+ String[] cliArguments = {"-section.subSection1", "abc"};
+ File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
+ Files.write(tempConfFile.toPath(), singletonList("section.subSection1=zxc"));
+ tempConfFile.deleteOnExit();
+
+ // when
+ ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
+ String actuallyOverridenByCLIParam = configurationAccessor.getStringDirectly("section.subSection1");
+
+ // then
+ assertEquals("abc", actuallyOverridenByCLIParam);
+ }
+
+ @Test
+ public void shouldReturnHTTPPort() throws IOException {
+ // when
+ int applicationPort = fromTemporaryConfiguration("collector.service.port=8090")
+ .httpPort();
+
+ // then
+ assertEquals(8090, applicationPort);
+ }
+
+ @Test
+ public void shouldReturnDefaultHTTPPort() throws IOException {
+ // when
+ int applicationPort = fromTemporaryConfiguration().httpPort();
+
+ // then
+ assertEquals(8080, applicationPort);
+ }
+
+ @Test
+ public void shouldReturnIfHTTPSIsEnabled() throws IOException {
+ // when
+ boolean httpsEnabled = fromTemporaryConfiguration("collector.service.secure.port=8443")
+ .httpsEnabled();
+
+ // then
+ assertTrue(httpsEnabled);
+ }
+
+ @Test
+ public void shouldReturnIfHTTPIsEnabled() throws IOException {
+ // when
+ boolean httpsEnabled = fromTemporaryConfiguration("collector.service.port=8080").httpsEnabled();
+ // then
+ assertTrue(httpsEnabled);
+ }
+
+ @Test
+ public void shouldByDefaultHTTPSBeDisabled() throws IOException {
+ // when
+ boolean httpsEnabled = fromTemporaryConfiguration().httpsEnabled();
+
+ // then
+ assertTrue(httpsEnabled);
+ }
+
+ @Test
+ public void shouldReturnHTTPSPort() throws IOException {
+ // when
+ int httpsPort = fromTemporaryConfiguration("collector.service.secure.port=8443")
+ .httpsPort();
+
+ // then
+ assertEquals(8443, httpsPort);
+ }
+
+ @Test
+ public void shouldReturnLocationOfThePasswordFile() throws IOException {
+ // when
+ String passwordFileLocation = fromTemporaryConfiguration("collector.keystore.passwordfile=/somewhere/password").keystorePasswordFileLocation();
+
+ // then
+ assertEquals("/somewhere/password", passwordFileLocation);
+ }
+
+ @Test
+ public void shouldReturnDefaultLocationOfThePasswordFile() throws IOException {
+ // when
+ String passwordFileLocation = fromTemporaryConfiguration().keystorePasswordFileLocation();
+
+ // then
+ assertEquals("./etc/passwordfile", passwordFileLocation);
+ }
+
+ @Test
+ public void shouldReturnLocationOfTheKeystoreFile() throws IOException {
+ // when
+ String keystoreFileLocation = fromTemporaryConfiguration("collector.keystore.file.location=/somewhere/keystore")
+ .keystoreFileLocation();
+
+ // then
+ assertEquals("/somewhere/keystore", keystoreFileLocation);
+ }
+
+ @Test
+ public void shouldReturnLocationOfTheDefaultKeystoreFile() throws IOException {
+ // when
+ String keystoreFileLocation = fromTemporaryConfiguration().keystoreFileLocation();
+
+ // then
+ assertEquals("../etc/keystore", keystoreFileLocation);
+ }
+
+
+ @Test
+ public void shouldReturnKeystoreAlias() throws IOException {
+ // when
+ String keystoreAlias = fromTemporaryConfiguration("collector.keystore.alias=alias").keystoreAlias();
+
+ // then
+ assertEquals("alias", keystoreAlias);
+ }
+
+ @Test
+ public void shouldReturnDefaultKeystoreAlias() throws IOException {
+ // when
+ String keystoreAlias = fromTemporaryConfiguration().keystoreAlias();
+
+ // then
+ assertEquals("tomcat", keystoreAlias);
+ }
+
+ @Test
+ public void shouldReturnDMAAPConfigFileLocation() throws IOException {
+ // when
+ String dmaapConfigFileLocation = fromTemporaryConfiguration("collector.dmaapfile=/somewhere/dmaapFile").cambriaConfigurationFileLocation();
+
+ // then
+ assertEquals("/somewhere/dmaapFile", dmaapConfigFileLocation);
+ }
+
+ @Test
+ public void shouldReturnDefaultDMAAPConfigFileLocation() throws IOException {
+ // when
+ String dmaapConfigFileLocation = fromTemporaryConfiguration().cambriaConfigurationFileLocation();
+
+ // then
+ assertEquals("./etc/DmaapConfig.json", dmaapConfigFileLocation);
+ }
+
+ @Test
+ public void shouldReturnMaximumAllowedQueuedEvents() throws IOException {
+ // when
+ int maximumAllowedQueuedEvents = fromTemporaryConfiguration("collector.inputQueue.maxPending=10000")
+ .maximumAllowedQueuedEvents();
+
+ // then
+ assertEquals(10000, maximumAllowedQueuedEvents);
+ }
+
+ @Test
+ public void shouldReturnDefaultMaximumAllowedQueuedEvents() throws IOException {
+ // when
+ int maximumAllowedQueuedEvents = fromTemporaryConfiguration().maximumAllowedQueuedEvents();
+
+ // then
+ assertEquals(1024 * 4, maximumAllowedQueuedEvents);
+ }
+
+ @Test
+ public void shouldTellIfSchemaValidationIsEnabled() throws IOException {
+ // when
+ boolean jsonSchemaValidationEnabled = fromTemporaryConfiguration("collector.schema.checkflag=1")
+ .jsonSchemaValidationEnabled();
+
+ // then
+ assertTrue(jsonSchemaValidationEnabled);
+ }
+
+ @Test
+ public void shouldByDefaultSchemaValidationBeDisabled() throws IOException {
+ // when
+ boolean jsonSchemaValidationEnabled = fromTemporaryConfiguration().jsonSchemaValidationEnabled();
+
+ // then
+ assertFalse(jsonSchemaValidationEnabled);
+ }
+
+ @Test
+ public void shouldReturnJSONSchema() throws IOException {
+ // when
+ JSONObject jsonSchema = fromTemporaryConfiguration("collector.schema.file={\"v1\": {}}")
+ .jsonSchema();
+
+ // then
+ assertEquals(new JSONObject("{\"v1\": {}}").toMap(), jsonSchema.toMap());
+ }
+
+ @Test
+ public void shouldReturnDefaultJSONSchema() throws IOException {
+ // when
+ JSONObject jsonSchema = fromTemporaryConfiguration().jsonSchema();
+
+ // then
+ assertEquals(new JSONObject("{\"v5\":\"./etc/CommonEventFormat_28.3.json\"}").toMap(), jsonSchema.toMap());
+ }
+
+ @Test
+ public void shouldReturnExceptionConfigFileLocation() throws IOException {
+ // when
+ String exceptionConfigFileLocation = fromTemporaryConfiguration("exceptionConfig=/somewhere/exceptionFile")
+ .exceptionConfigFileLocation();
+
+ // then
+ assertEquals("/somewhere/exceptionFile", exceptionConfigFileLocation);
+ }
+
+ @Test
+ public void shouldReturnDefaultExceptionConfigFileLocation() throws IOException {
+ // when
+ String exceptionConfigFileLocation = fromTemporaryConfiguration().exceptionConfigFileLocation();
+
+ // then
+ assertNull(exceptionConfigFileLocation);
+ }
+
+
+ @Test
+ public void shouldReturnDMAAPStreamId() throws IOException {
+ // given
+ Map<String, String[]> expected = HashMap.of(
+ "s", new String[]{"something", "something2"},
+ "s2", new String[]{"something3"}
+ );
+
+ // when
+ Map<String, String[]> dmaapStreamID = fromTemporaryConfiguration("collector.dmaap.streamid=s=something,something2|s2=something3")
+ .dMaaPStreamsMapping();
+
+ // then
+ assertArrayEquals(expected.get("s").get(), Objects.requireNonNull(dmaapStreamID).get("s").get());
+ assertArrayEquals(expected.get("s2").get(), Objects.requireNonNull(dmaapStreamID).get("s2").get());
+ assertEquals(expected.keySet(), dmaapStreamID.keySet());
+ }
+
+ @Test
+ public void shouldReturnDefaultDMAAPStreamId() throws IOException {
+ // when
+ Map<String, String[]> dmaapStreamID = fromTemporaryConfiguration().dMaaPStreamsMapping();
+
+ // then
+ assertEquals(dmaapStreamID, HashMap.empty());
+ }
+
+ @Test
+ public void shouldReturnIfAuthorizationIsEnabled() throws IOException {
+ // when
+ boolean authorizationEnabled = fromTemporaryConfiguration("header.authflag=1")
+ .authorizationEnabled();
+
+ // then
+ assertTrue(authorizationEnabled);
+ }
+
+ @Test
+ public void shouldAuthorizationBeDisabledByDefault() throws IOException {
+ // when
+ boolean authorizationEnabled = fromTemporaryConfiguration().authorizationEnabled();
+
+ // then
+ assertFalse(authorizationEnabled);
+ }
+
+ @Test
+ public void shouldReturnValidCredentials() throws IOException {
+ // when
+ String userToBase64PasswordDelimitedByCommaSeparatedByPipes = fromTemporaryConfiguration(
+ "header.authlist=pasza,123jsad1|someoneelse,12asd31"
+ ).validAuthorizationCredentials();
+
+ // then
+ assertEquals("pasza,123jsad1|someoneelse,12asd31", userToBase64PasswordDelimitedByCommaSeparatedByPipes);
+ }
+
+ @Test
+ public void shouldbyDefaultThereShouldBeNoValidCredentials() throws IOException {
+ // when
+ String userToBase64PasswordDelimitedByCommaSeparatedByPipes = fromTemporaryConfiguration().
+ validAuthorizationCredentials();
+
+ // then
+ assertNull(userToBase64PasswordDelimitedByCommaSeparatedByPipes);
+ }
+
+
+ @Test
+ public void shouldReturnIfEventTransformingIsEnabled() throws IOException {
+ // when
+ boolean isEventTransformingEnabled = fromTemporaryConfiguration("event.transform.flag=0")
+ .eventTransformingEnabled();
+
+ // then
+ assertFalse(isEventTransformingEnabled);
+ }
+
+ @Test
+ public void shouldEventTransformingBeEnabledByDefault() throws IOException {
+ // when
+ boolean isEventTransformingEnabled = fromTemporaryConfiguration().eventTransformingEnabled();
+
+ // then
+ assertTrue(isEventTransformingEnabled);
+ }
+
+ @Test
+ public void shouldReturnCambriaConfigurationFileLocation() throws IOException {
+ // when
+ String cambriaConfigurationFileLocation = fromTemporaryConfiguration("collector.dmaapfile=/somewhere/dmaapConfig")
+ .cambriaConfigurationFileLocation();
+
+ // then
+ assertEquals("/somewhere/dmaapConfig", cambriaConfigurationFileLocation);
+ }
+
+ @Test
+ public void shouldReturnDefaultCambriaConfigurationFileLocation() throws IOException {
+ // when
+ String cambriaConfigurationFileLocation = fromTemporaryConfiguration()
+ .cambriaConfigurationFileLocation();
+
+ // then
+ assertEquals("./etc/DmaapConfig.json", cambriaConfigurationFileLocation);
+ }
+
+ private static ApplicationSettings fromTemporaryConfiguration(String... fileLines)
+ throws IOException {
+ File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
+ Files.write(tempConfFile.toPath(), Arrays.asList(fileLines));
+ tempConfFile.deleteOnExit();
+ return new ApplicationSettings(new String[]{"-c", tempConfFile.toString()}, args -> processCmdLine(args));
+ }
+
+
+} \ No newline at end of file
diff --git a/src/test/java/org/onap/dcae/commonFunction/ApiExceptionTest.java b/src/test/java/org/onap/dcae/commonFunction/ApiExceptionTest.java
new file mode 100644
index 00000000..ef5b477c
--- /dev/null
+++ b/src/test/java/org/onap/dcae/commonFunction/ApiExceptionTest.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.commonFunction;
+
+import static org.junit.Assert.assertEquals;
+
+import org.json.JSONObject;
+import org.junit.Test;
+import org.onap.dcae.restapi.ApiException;
+import org.onap.dcae.restapi.ApiException.ExceptionType;
+
+/**
+ * @author Pawel Szalapski (pawel.szalapski@nokia.com)
+ */
+public class ApiExceptionTest {
+
+ @Test
+ public void shouldStringifyServiceExceptionTypeAccordingToSpecification() {
+ assertEquals(ExceptionType.SERVICE_EXCEPTION.toString(), "ServiceException");
+ }
+
+ @Test
+ public void shouldStringifyPolicyExceptionTypeAccordingToSpecification() {
+ assertEquals(ExceptionType.POLICY_EXCEPTION.toString(), "PolicyException");
+ }
+
+ @Test
+ public void shouldConvertExceptionToBackwardCompatibleFormat() {
+ JSONObject responseBody = ApiException.UNAUTHORIZED_USER.toJSON();
+ assertEquals(responseBody.toString(), new JSONObject(""
+ + "{ "
+ + " 'requestError': { "
+ + " 'PolicyException': { "
+ + " 'messageId': 'POL2000', "
+ + " 'text': 'Unauthorized user' "
+ + " } "
+ + " } "
+ + "} "
+ .replace("'", "\"")
+ ).toString());
+ }
+}
diff --git a/src/test/java/org/onap/dcae/commonFunction/CommonStartupTest.java b/src/test/java/org/onap/dcae/commonFunction/CommonStartupTest.java
new file mode 100644
index 00000000..5a171484
--- /dev/null
+++ b/src/test/java/org/onap/dcae/commonFunction/CommonStartupTest.java
@@ -0,0 +1,127 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.commonFunction;
+
+import static java.util.Base64.getDecoder;
+import static java.util.Base64.getEncoder;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.att.nsa.cmdLine.NsaCommandLineUtil;
+import com.att.nsa.drumlin.service.framework.context.DrumlinRequest;
+import com.att.nsa.drumlin.till.nv.impl.nvReadableStack;
+import com.att.nsa.drumlin.till.nv.impl.nvReadableTable;
+import com.att.nsa.drumlin.till.nv.rrNvReadable.loadException;
+import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;
+import com.att.nsa.security.authenticators.SimpleAuthenticator;
+import com.att.nsa.security.db.simple.NsaSimpleApiKey;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.dcae.ApplicationSettings;
+import org.onap.dcae.CLIUtils;
+import org.onap.dcae.commonFunction.CommonStartup.QueueFullException;
+import org.onap.dcae.commonFunction.event.publishing.EventPublisher;
+import org.onap.dcae.restapi.RestfulCollectorServlet;
+import org.onap.dcae.vestest.TestingUtilities;
+
+
+public class CommonStartupTest {
+
+ @Test
+ public void testParseCLIArguments() {
+ // given
+ String args[] = {"-a", "aa"};
+ Map<String, String> argMap = NsaCommandLineUtil.processCmdLine(args, true);
+ // when
+ nvReadableStack settings = new nvReadableStack();
+ settings.push(new nvReadableTable(argMap));
+
+ // then
+ assertEquals(settings.getString("a", "default"), "aa");
+ }
+
+ @Test
+ public void shouldPutValidVESEventOnProcessingQueueWithoutExceptions() throws IOException, QueueFullException {
+ // given
+ CommonStartup.fProcessingInputQueue = new LinkedBlockingQueue<>(
+ CommonStartup.maxQueueEvent);
+ JsonElement vesEvent = new JsonParser().parse(new FileReader("src/test/resources/VES_valid.txt"));
+ JSONObject validVESEvent = new JSONObject(vesEvent.toString());
+ JSONArray jsonArrayMod = new JSONArray().put(validVESEvent);
+
+ // then
+ CommonStartup.handleEvents(jsonArrayMod);
+ }
+
+
+ @Test
+ public void testParseStreamIdToStreamHashMapping() {
+ // given
+
+ CommonStartup.streamID = TestingUtilities.convertDMaaPStreamsPropertyToMap("fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling");
+ EventProcessor eventProcessor = new EventProcessor(mock(EventPublisher.class));
+ // when
+ Map<String, String[]> streamHashMapping = EventProcessor.streamidHash;
+
+ // then
+ assertEquals(streamHashMapping.get("fault")[0], "sec_fault");
+ assertEquals(streamHashMapping.get("measurementsForVfScaling")[0], "sec_measurement");
+ }
+
+ @Test
+ public void testAuthListHandler() throws loadException, missingReqdSetting {
+ // given
+ ApplicationSettings settings = new ApplicationSettings(new String[]{}, CLIUtils::processCmdLine);
+
+ String user1 = "secureid";
+ String password1Hashed = "IWRjYWVSb2FkbTEyMyEt";
+ String password1UnHashed = new String(getDecoder().decode("IWRjYWVSb2FkbTEyMyEt"));
+ String user2 = "sample1";
+ String password2Hashed = "c2FtcGxlMQ";
+
+ String authlist = user1 + "," + password1Hashed + "|" + user2 + "," + password2Hashed;
+
+ RestfulCollectorServlet rsv = new RestfulCollectorServlet(settings);
+
+ DrumlinRequest drumlinRequestMock = Mockito.mock(DrumlinRequest.class);
+
+ String basicHeaderForUser1 = "Basic " + getEncoder().encodeToString((user1 + ":" + password1UnHashed).getBytes());
+ when(drumlinRequestMock.getFirstHeader("Authorization")).thenReturn(basicHeaderForUser1);
+
+ // when
+ SimpleAuthenticator simpleAuthenticator = (SimpleAuthenticator) rsv.createAuthenticator(authlist);
+ NsaSimpleApiKey authentic = simpleAuthenticator.isAuthentic(drumlinRequestMock);
+
+ // then
+ assertEquals(authentic.getSecret(), password1UnHashed);
+ }
+}
+
+
diff --git a/src/test/java/org/onap/dcae/commonFunction/ConfigProcessorAdapterTest.java b/src/test/java/org/onap/dcae/commonFunction/ConfigProcessorAdapterTest.java
new file mode 100644
index 00000000..180dfcf1
--- /dev/null
+++ b/src/test/java/org/onap/dcae/commonFunction/ConfigProcessorAdapterTest.java
@@ -0,0 +1,66 @@
+//
+// ================================================================================
+// Copyright (c) 2017-2018 AT&T Intellectual Property. All rights reserved.
+// Copyright (c) 2018 Nokia. All rights reserved.
+// ================================================================================
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// ============LICENSE_END=========================================================
+//
+//
+package org.onap.dcae.commonFunction;
+
+import org.json.JSONObject;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ConfigProcessorAdapterTest {
+
+ @Mock
+ private ConfigProcessors configProcessors;
+
+ @InjectMocks
+ private EventProcessor.ConfigProcessorAdapter configProcessorAdapter;
+
+
+ @Test
+ public void shouldCallIsFilterMetOnAdapter() {
+ //given
+ JSONObject parameter = new JSONObject();
+ when(configProcessors.isFilterMet(parameter)).thenReturn(true);
+ //when
+ boolean actualReturn = configProcessorAdapter.isFilterMet(parameter);
+ //then
+ assertTrue(actualReturn);
+ verify(configProcessors, times(1)).isFilterMet(parameter);
+ }
+
+ @Test
+ public void shouldCallGivenMethodFromConfigProcessor() throws Exception {
+ JSONObject parameter = new JSONObject();
+ String exampleFunction = "concatenateValue";
+ //when
+ configProcessorAdapter.runConfigProcessorFunctionByName(exampleFunction, parameter);
+ //then
+ verify(configProcessors, times(1)).concatenateValue(parameter);
+ }
+
+} \ No newline at end of file
diff --git a/src/test/java/org/onap/dcae/commonFunction/EventProcessorTest.java b/src/test/java/org/onap/dcae/commonFunction/EventProcessorTest.java
new file mode 100644
index 00000000..77ef005f
--- /dev/null
+++ b/src/test/java/org/onap/dcae/commonFunction/EventProcessorTest.java
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.commonFunction;
+
+import com.google.gson.Gson;
+import java.util.concurrent.atomic.AtomicReference;
+
+import io.vavr.collection.HashMap;
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.List;
+import org.onap.dcae.commonFunction.event.publishing.EventPublisher;
+import org.onap.dcae.vestest.TestingUtilities;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.onap.dcae.commonFunction.EventProcessor.EVENT_LIST_TYPE;
+
+public class EventProcessorTest {
+
+ private final String ev = "{\"event\": {\"commonEventHeader\": { \"reportingEntityName\": \"VM name will be provided by ECOMP\", \"startEpochMicrosec\": 1477012779802988,\"lastEpochMicrosec\": 1477012789802988,\"eventId\": \"83\",\"sourceName\": \"Dummy VM name - No Metadata available\",\"sequence\": 83,\"priority\": \"Normal\",\"functionalRole\": \"vFirewall\",\"domain\": \"measurementsForVfScaling\",\"reportingEntityId\": \"VM UUID will be provided by ECOMP\",\"sourceId\": \"Dummy VM UUID - No Metadata available\",\"version\": 1.1},\"measurementsForVfScalingFields\": {\"measurementInterval\": 10,\"measurementsForVfScalingVersion\": 1.1,\"vNicUsageArray\": [{\"multicastPacketsIn\": 0,\"bytesIn\": 3896,\"unicastPacketsIn\": 0, \"multicastPacketsOut\": 0,\"broadcastPacketsOut\": 0, \"packetsOut\": 28,\"bytesOut\": 12178,\"broadcastPacketsIn\": 0,\"packetsIn\": 58,\"unicastPacketsOut\": 0,\"vNicIdentifier\": \"eth0\"}]}}}";
+
+ @Before
+ public void setUp() {
+ CommonStartup.streamID = TestingUtilities.convertDMaaPStreamsPropertyToMap("fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling");
+ }
+
+ @Test
+ public void testLoad() {
+ //given
+ EventProcessor ec = new EventProcessor(mock(EventPublisher.class));
+ ec.event = new org.json.JSONObject(ev);
+ //when
+ ec.overrideEvent();
+
+ //then
+ Boolean hasSourceNameNode = ec.event.getJSONObject("event").getJSONObject("commonEventHeader").has("sourceName");
+ assertTrue(hasSourceNameNode);
+ }
+
+ @Test
+ public void shouldParseJsonEvents() throws ReflectiveOperationException {
+ //given
+ EventProcessor eventProcessor = new EventProcessor(mock(EventPublisher.class));
+ String event_json = "[{ \"filter\": {\"event.commonEventHeader.domain\":\"heartbeat\",\"VESversion\":\"v4\"},\"processors\":[" +
+ "{\"functionName\": \"concatenateValue\",\"args\":{\"field\":\"event.commonEventHeader.eventName\",\"concatenate\": [\"$event.commonEventHeader.domain\",\"$event.commonEventHeader.eventType\",\"$event.faultFields.alarmCondition\"], \"delimiter\":\"_\"}}" +
+ ",{\"functionName\": \"addAttribute\",\"args\":{\"field\": \"event.heartbeatFields.heartbeatFieldsVersion\",\"value\": \"1.0\",\"fieldType\": \"number\"}}" +
+ ",{\"functionName\": \"map\",\"args\":{\"field\": \"event.commonEventHeader.nfNamingCode\",\"oldField\": \"event.commonEventHeader.functionalRole\"}}]}]";
+ List<Event> events = new Gson().fromJson(event_json, EVENT_LIST_TYPE);
+ EventProcessor.ConfigProcessorAdapter configProcessorAdapter = mock(EventProcessor.ConfigProcessorAdapter.class);
+
+ when(configProcessorAdapter.isFilterMet(any(JSONObject.class))).thenReturn(true);
+ ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class);
+ ArgumentCaptor<JSONObject> jsonObjectArgumentCaptor = ArgumentCaptor.forClass(JSONObject.class);
+ //when
+ eventProcessor.parseEventsJson(events, configProcessorAdapter);
+
+ //then
+ verify(configProcessorAdapter, times(3)).runConfigProcessorFunctionByName(stringArgumentCaptor.capture(), jsonObjectArgumentCaptor.capture());
+ assertThat(stringArgumentCaptor.getAllValues()).contains("concatenateValue", "addAttribute", "map");
+ }
+
+}
+
diff --git a/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPConfigurationParserTest.java b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPConfigurationParserTest.java
new file mode 100644
index 00000000..5a94c662
--- /dev/null
+++ b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPConfigurationParserTest.java
@@ -0,0 +1,114 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.commonFunction.event.publishing;
+
+import static io.vavr.API.List;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.onap.dcae.commonFunction.event.publishing.DMaaPConfigurationParser.parseToDomainMapping;
+
+import io.vavr.collection.Map;
+import io.vavr.control.Try;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.junit.Test;
+
+/**
+ * @author Pawel Szalapski (pawel.szalapski@nokia.com)
+ */
+public class DMaaPConfigurationParserTest {
+
+ @Test
+ public void testParseCredentialsForGen2() {
+ Path path = Paths.get("src/test/resources/testParseDMaaPCredentialsGen2.json");
+ Try<Map<String, PublisherConfig>> publisherConfigs = parseToDomainMapping(path);
+
+ PublisherConfig authCredentialsNulls = publisherConfigs.get().get("auth-credentials-null").getOrNull();
+ assertThat(authCredentialsNulls.userName().isEmpty()).isTrue();
+ assertThat(authCredentialsNulls.password().isEmpty()).isTrue();
+ assertThat(authCredentialsNulls.isSecured()).isFalse();
+
+ PublisherConfig authCredentialsPresent = publisherConfigs.get().get("auth-credentials-present").getOrNull();
+ assertThat(authCredentialsPresent.userName().getOrNull()).isEqualTo("sampleUser");
+ assertThat(authCredentialsPresent.password().getOrNull()).isEqualTo("samplePassword");
+ assertThat(authCredentialsPresent.isSecured()).isTrue();
+
+ PublisherConfig authCredentialsKeysMissing = publisherConfigs.get().get("auth-credentials-missing").getOrNull();
+ assertThat(authCredentialsKeysMissing.userName().isEmpty()).isTrue();
+ assertThat(authCredentialsKeysMissing.password().isEmpty()).isTrue();
+ assertThat(authCredentialsKeysMissing.isSecured()).isFalse();
+ }
+
+
+ @Test
+ public void testParseCredentialsForLegacy() {
+ Path path = Paths.get("src/test/resources/testParseDMaaPCredentialsLegacy.json");
+ Try<Map<String, PublisherConfig>> publisherConfigs = parseToDomainMapping(path);
+
+ PublisherConfig authCredentialsNull = publisherConfigs.get().get("auth-credentials-null").getOrNull();
+ assertThat(authCredentialsNull.userName().isEmpty()).isTrue();
+ assertThat(authCredentialsNull.password().isEmpty()).isTrue();
+ assertThat(authCredentialsNull.isSecured()).isFalse();
+
+ PublisherConfig authCredentialsPresent = publisherConfigs.get().get("auth-credentials-present").getOrNull();
+ assertThat(authCredentialsPresent.userName().getOrNull()).isEqualTo("sampleUser");
+ assertThat(authCredentialsPresent.password().getOrNull()).isEqualTo("samplePassword");
+ assertThat(authCredentialsPresent.isSecured()).isTrue();
+
+ PublisherConfig authCredentialsMissing = publisherConfigs.get().get("auth-credentials-missing").getOrNull();
+ assertThat(authCredentialsMissing.userName().isEmpty()).isTrue();
+ assertThat(authCredentialsMissing.password().isEmpty()).isTrue();
+ assertThat(authCredentialsMissing.isSecured()).isFalse();
+ }
+
+
+ @Test
+ public void testParseGen2() {
+ Path path = Paths.get("src/test/resources/testParseDMaaPGen2.json");
+ Try<Map<String, PublisherConfig>> publisherConfigs = parseToDomainMapping(path);
+
+ PublisherConfig withEventsSegment = publisherConfigs.get().get("event-segments-with-port").getOrNull();
+ assertThat(withEventsSegment.destinations()).isEqualTo(List("UEBHOST:3904"));
+ assertThat(withEventsSegment.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV");
+
+ PublisherConfig withOtherSegment = publisherConfigs.get().get("other-segments-without-ports").getOrNull();
+ assertThat(withOtherSegment.destinations()).isEqualTo(List("UEBHOST"));
+ assertThat(withOtherSegment.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV");
+ }
+
+ @Test
+ public void testParseLegacy() {
+ Path exemplaryConfig = Paths.get("src/test/resources/testParseDMaaPLegacy.json");
+ Try<Map<String, PublisherConfig>> publisherConfigs = DMaaPConfigurationParser
+ .parseToDomainMapping(exemplaryConfig);
+
+ PublisherConfig urlFirstThenHosts = publisherConfigs.get().get("url-precedes-hosts").getOrNull();
+ assertThat(urlFirstThenHosts.destinations()).isEqualTo(List("127.0.0.1:3904"));
+ assertThat(urlFirstThenHosts.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV");
+
+ PublisherConfig urlKeyMissing = publisherConfigs.get().get("url-key-missing").getOrNull();
+ assertThat(urlKeyMissing.destinations()).isEqualTo(List("h1.att.com", "h2.att.com"));
+ assertThat(urlKeyMissing.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV");
+
+ PublisherConfig urlIsMissing = publisherConfigs.get().get("url-is-null").getOrNull();
+ assertThat(urlIsMissing.destinations()).isEqualTo(List("h1.att.com", "h2.att.com"));
+ assertThat(urlIsMissing.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV");
+ }
+} \ No newline at end of file
diff --git a/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPEventPublisherTest.java b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPEventPublisherTest.java
new file mode 100644
index 00000000..bbe5079e
--- /dev/null
+++ b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPEventPublisherTest.java
@@ -0,0 +1,89 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.commonFunction.event.publishing;
+
+import static io.vavr.API.Option;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.att.nsa.cambria.client.CambriaBatchingPublisher;
+import java.io.IOException;
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+
+public class DMaaPEventPublisherTest {
+
+ private static final String STREAM_ID = "sampleStreamId";
+
+ private DMaaPEventPublisher eventPublisher;
+ private CambriaBatchingPublisher cambriaPublisher;
+ private DMaaPPublishersCache DMaaPPublishersCache;
+
+ @Before
+ public void setUp() {
+ cambriaPublisher = mock(CambriaBatchingPublisher.class);
+ DMaaPPublishersCache = mock(DMaaPPublishersCache.class);
+ when(DMaaPPublishersCache.getPublisher(anyString())).thenReturn(Option(cambriaPublisher));
+ eventPublisher = new DMaaPEventPublisher(DMaaPPublishersCache, mock(Logger.class));
+ }
+
+ @Test
+ public void shouldSendEventToTopic() throws Exception {
+ // given
+ JSONObject event = new JSONObject("{}");
+
+ // when
+ eventPublisher.sendEvent(event, STREAM_ID);
+
+ // then
+ verify(cambriaPublisher).send("MyPartitionKey", event.toString());
+ }
+
+ @Test
+ public void shouldRemoveInternalVESUIDBeforeSending() throws Exception {
+ // given
+ JSONObject event = new JSONObject(
+ "{\"VESuniqueId\": \"362e0146-ec5f-45f3-8d8f-bfe877c3f58e\", \"another\": 8}");
+
+ // when
+ eventPublisher.sendEvent(event, STREAM_ID);
+
+ // then
+ verify(cambriaPublisher).send("MyPartitionKey", new JSONObject("{\"another\": 8}").toString());
+ }
+
+ @Test
+ public void shouldCloseConnectionWhenExceptionOccurred() throws Exception {
+ // given
+ JSONObject event = new JSONObject("{}");
+ given(cambriaPublisher.send(anyString(), anyString())).willThrow(new IOException("epic fail"));
+
+ // when
+ eventPublisher.sendEvent(event, STREAM_ID);
+
+ // then
+ verify(DMaaPPublishersCache).closePublisherFor(STREAM_ID);
+ }
+} \ No newline at end of file
diff --git a/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPPublishersCacheTest.java b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPPublishersCacheTest.java
new file mode 100644
index 00000000..8dc69f62
--- /dev/null
+++ b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPPublishersCacheTest.java
@@ -0,0 +1,126 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.commonFunction.event.publishing;
+
+import static io.vavr.API.List;
+import static io.vavr.API.Map;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+import com.att.nsa.cambria.client.CambriaBatchingPublisher;
+import io.vavr.collection.Map;
+import io.vavr.control.Option;
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.dcae.commonFunction.event.publishing.DMaaPPublishersCache.CambriaPublishersCacheLoader;
+import org.onap.dcae.commonFunction.event.publishing.DMaaPPublishersCache.OnPublisherRemovalListener;
+
+
+public class DMaaPPublishersCacheTest {
+
+ private String streamId1;
+ private Map<String, PublisherConfig> dMaaPConfigs;
+
+ @Before
+ public void setUp() {
+ streamId1 = "sampleStream1";
+ dMaaPConfigs = Map("sampleStream1", new PublisherConfig(List("destination1"), "topic1"));
+ }
+
+ @Test
+ public void shouldReturnTheSameCachedInstanceOnConsecutiveRetrievals() {
+ // given
+ DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs);
+
+ // when
+ Option<CambriaBatchingPublisher> firstPublisher = dMaaPPublishersCache.getPublisher(streamId1);
+ Option<CambriaBatchingPublisher> secondPublisher = dMaaPPublishersCache.getPublisher(streamId1);
+
+ // then
+ assertSame("should return same instance", firstPublisher.get(), secondPublisher.get());
+ }
+
+ @Test
+ public void shouldCloseCambriaPublisherOnCacheInvalidate() throws IOException, InterruptedException {
+ // given
+ CambriaBatchingPublisher cambriaPublisherMock1 = mock(CambriaBatchingPublisher.class);
+ CambriaPublishersCacheLoader cacheLoaderMock = mock(CambriaPublishersCacheLoader.class);
+ DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(cacheLoaderMock,
+ new OnPublisherRemovalListener(),
+ dMaaPConfigs);
+ when(cacheLoaderMock.load(streamId1)).thenReturn(cambriaPublisherMock1);
+
+ // when
+ dMaaPPublishersCache.getPublisher(streamId1);
+ dMaaPPublishersCache.closePublisherFor(streamId1);
+
+ // then
+ verify(cambriaPublisherMock1).close(20, TimeUnit.SECONDS);
+
+ }
+
+ @Test
+ public void shouldReturnNoneIfThereIsNoDMaaPConfigurationForGivenStreamID() {
+ // given
+ DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs);
+
+ // then
+ assertTrue("should not exist", dMaaPPublishersCache.getPublisher("non-existing").isEmpty());
+ }
+
+
+ @Test
+ public void shouldCloseOnlyChangedPublishers() throws IOException, InterruptedException {
+ // given
+ CambriaBatchingPublisher cambriaPublisherMock1 = mock(CambriaBatchingPublisher.class);
+ CambriaBatchingPublisher cambriaPublisherMock2 = mock(CambriaBatchingPublisher.class);
+ CambriaPublishersCacheLoader cacheLoaderMock = mock(CambriaPublishersCacheLoader.class);
+ String firstDomain = "domain1";
+ String secondDomain = "domain2";
+ Map<String, PublisherConfig> oldConfig = Map(firstDomain,
+ new PublisherConfig(List("destination1"), "topic1"),
+ secondDomain,
+ new PublisherConfig(List("destination2"), "topic2",
+ "user", "pass"));
+ Map<String, PublisherConfig> newConfig = Map(firstDomain, new PublisherConfig(List("destination1"), "topic1"),
+ secondDomain, new PublisherConfig(List("destination2"), "topic2"));
+ DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(cacheLoaderMock,
+ new OnPublisherRemovalListener(),
+ oldConfig);
+ when(cacheLoaderMock.load(firstDomain)).thenReturn(cambriaPublisherMock1);
+ when(cacheLoaderMock.load(secondDomain)).thenReturn(cambriaPublisherMock2);
+
+ dMaaPPublishersCache.getPublisher(firstDomain);
+ dMaaPPublishersCache.getPublisher(secondDomain);
+
+ // when
+ dMaaPPublishersCache.reconfigure(newConfig);
+
+ // then
+ verify(cambriaPublisherMock2).close(20, TimeUnit.SECONDS);
+ verifyZeroInteractions(cambriaPublisherMock1);
+ }
+} \ No newline at end of file
diff --git a/src/test/java/org/onap/dcae/vestest/AnyNodeTest.java b/src/test/java/org/onap/dcae/vestest/AnyNodeTest.java
new file mode 100644
index 00000000..9400e46d
--- /dev/null
+++ b/src/test/java/org/onap/dcae/vestest/AnyNodeTest.java
@@ -0,0 +1,63 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2018 Nokia Networks Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.vestest;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.google.common.collect.Sets;
+import java.util.Set;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.dcae.commonFunction.AnyNode;
+
+/**
+ * Created by koblosz on 07.06.18.
+ */
+public class AnyNodeTest {
+
+ private static final String SAMPLE_JSON_FILEPATH = "{\n"
+ + " \"channels\": [{\n"
+ + " \"one\": \"number1\", \"two\": \"number2\", \"three\": \"number3\"}],\n"
+ + " \"sampleStrList\": [\"1\", \"2\", \"3\", \"4\", \"5\"],\n"
+ + " \"sampleNestedObject\": {\"a\": 1, \"b\": 2},\n"
+ + " \"sampleInt\": 1,\n"
+ + " \"sampleString\": \"str\",\n"
+ + " \"sampleNull\": null\n"
+ + "}\n";
+ private static final Set<String> EXPECTED_JSON_KEYS = Sets
+ .newHashSet("channels", "sampleStrList", "sampleNestedObject", "sampleInt", "sampleString", "sampleNull");
+ private static AnyNode node;
+
+
+ @BeforeClass
+ public static void setUpClass() {
+ node = AnyNode.fromString(SAMPLE_JSON_FILEPATH);
+ }
+
+ @Test
+ public void testShouldReturnJsonObjectKeySet() {
+ assertThat(node.keys()).containsOnlyElementsOf(EXPECTED_JSON_KEYS);
+ }
+
+ @Test(expected = ClassCastException.class)
+ public void whenInvokedOnJsonObjInsteadOfJsonArrShouldRaiseRuntimeEx() {
+ node.toList();
+ }
+} \ No newline at end of file
diff --git a/src/test/java/org/onap/dcae/vestest/EventTransformTest.java b/src/test/java/org/onap/dcae/vestest/EventTransformTest.java
deleted file mode 100644
index 96e965cf..00000000
--- a/src/test/java/org/onap/dcae/vestest/EventTransformTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcae.vestest;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.FileReader;
-import java.io.IOException;
-import org.json.JSONObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonObject;
-import org.junit.Test;
-
-import org.onap.dcae.commonFunction.ConfigProcessors;
-
-
-
-public class EventTransformTest {
- public JSONObject getFileAsJsonObject()
- {
- JSONObject jsonObject = null;
- FileReader fr = null;
- final JsonParser parser = new JsonParser();
- String jsonfilepath="src/test/resources/event4xjson.txt";
- try{
- fr = new FileReader ( jsonfilepath );
- final JsonObject jo = (JsonObject) parser.parse (fr);
- final String jsonText = jo.toString ();
- jsonObject = new JSONObject ( jsonText );
- }
- catch(Exception e){
- System.out.println("Exception while opening the file");
- e.printStackTrace();
- }
- finally {
- //close the file
- if (fr != null) {
- try {
- fr.close();
- } catch (IOException e) {
- System.out.println("Error closing file reader stream : " +e.toString());
- }
- }
- }
- return jsonObject;
- }
- @Test
- public void testAttrMap(){
-
- final JSONObject jsonObject = getFileAsJsonObject();
- final String functionRole = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("functionalRole").toString();
- System.out.println("event==" + jsonObject.toString());
- System.out.println("functionRole==" + functionRole);
- final JSONObject jsonArgs = new JSONObject ( "{\"field\": \"event.commonEventHeader.nfNamingCode\",\"oldField\": \"event.commonEventHeader.functionalRole\"}" );
- ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
- cpEvent.map(jsonArgs);
- final String responseData = cpEvent.getEventObjectVal("event.commonEventHeader.nfNamingCode").toString();
- System.out.println("modified event==" + jsonObject.toString());
- System.out.println("responseData==" + responseData);
- assertEquals (functionRole, responseData);
- }
-
- @Test
- public void testArrayMap(){
-
- final JSONObject jsonObject = getFileAsJsonObject();
- final String alarmAdditionalInformation = (jsonObject.getJSONObject("event")).getJSONObject("faultFields").get("alarmAdditionalInformation").toString();
- System.out.println("event==" + jsonObject.toString());
- System.out.println("alarmAdditionalInformation==" + alarmAdditionalInformation);
- final JSONObject jsonArgs = new JSONObject ( "{\"field\": \"event.faultFields.eventAdditionalInformation\",\"oldField\": \"event.faultFields.alarmAdditionalInformation\"}" );
- ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
- cpEvent.map(jsonArgs);
- final String responseData = cpEvent.getEventObjectVal("event.faultFields.eventAdditionalInformation").toString();
- System.out.println("modified event==" + jsonObject.toString());
- System.out.println("responseData==" + responseData);
- assertEquals (alarmAdditionalInformation, responseData);
- }
- @Test
- public void testJobjMaptoArray(){
-
- final JSONObject jsonObject = getFileAsJsonObject();
- //final String receiveDiscards = (((jsonObject.getJSONObject("event")).getJSONObject("faultFields")).get("errors")).get("receiveDiscards").toString();
- System.out.println("event==" + jsonObject.toString());
- //System.out.println("alarmAdditionalInformation==" + alarmAdditionalInformation);
- final JSONObject jsonArgs = new JSONObject ( "{\"field\": \"event.faultFields.vNicPerformanceArray[]\",\"oldField\": \"event.faultFields.errors\",\"attrMap\":{\"receiveDiscards\":\"receivedDiscardedPacketsAccumulated\"}}" );
- ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
- final String receiveDiscards = cpEvent.getEventObjectVal("event.faultFields.errors.receiveDiscards").toString();
- System.out.println("receiveDiscards==" + receiveDiscards);
- cpEvent.map(jsonArgs);
- final String responseData = cpEvent.getEventObjectVal("event.faultFields.vNicPerformanceArray[0].receivedDiscardedPacketsAccumulated").toString();
- System.out.println("modified event==" + jsonObject.toString());
- System.out.println("responseData==" + responseData);
- assertEquals (receiveDiscards, responseData);
- }
- @Test
- public void testAttrAdd(){
-
- final JSONObject jsonObject = getFileAsJsonObject();
- //final String functionRole = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("functionalRole").toString();
- System.out.println("event==" + jsonObject.toString());
- //System.out.println("functionRole==" + functionRole);
- final JSONObject jsonArgs = new JSONObject ( "{\"field\": \"event.faultFields.version\",\"value\": \"2.0\",\"fieldType\": \"number\"}" );
- ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
- cpEvent.addAttribute(jsonArgs);
- final String responseData = cpEvent.getEventObjectVal("event.faultFields.version").toString();
- System.out.println("modified event==" + jsonObject.toString());
- System.out.println("responseData==" + responseData);
- assertEquals ("2.0", responseData);
- }
-
- @Test
- public void testAttrUpdate(){
-
- final JSONObject jsonObject = getFileAsJsonObject();
- //final String functionRole = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("functionalRole").toString();
- System.out.println("event==" + jsonObject.toString());
- //System.out.println("functionRole==" + functionRole);
- final JSONObject jsonArgs = new JSONObject ( "{\"field\": \"event.faultFields.version\",\"value\": \"2.0\",\"fieldType\": \"number\"}" );
- ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
- cpEvent.updateAttribute(jsonArgs);
- final String responseData = cpEvent.getEventObjectVal("event.faultFields.version").toString();
- System.out.println("modified event==" + jsonObject.toString());
- System.out.println("responseData==" + responseData);
- assertEquals ("2.0", responseData);
- }
-
- @Test
- public void testAttrConcatenate(){
-
- final JSONObject jsonObject = getFileAsJsonObject();
- final String eventType = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("eventType").toString();
- final String domain = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("domain").toString();
- final String alarmCondition = (jsonObject.getJSONObject("event")).getJSONObject("faultFields").get("alarmCondition").toString();
- System.out.println("event==" + jsonObject.toString());
- final String eventName = domain + "_" + eventType + "_" + alarmCondition;
- System.out.println("eventName==" + eventName);
- final JSONObject jsonArgs = new JSONObject ( "{\"field\":\"event.commonEventHeader.eventName\",\"concatenate\": [\"$event.commonEventHeader.domain\",\"$event.commonEventHeader.eventType\",\"$event.faultFields.alarmCondition\"],\"delimiter\":\"_\"}");
- ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
- cpEvent.concatenateValue(jsonArgs);
- final String responseData = cpEvent.getEventObjectVal("event.commonEventHeader.eventName").toString();
- System.out.println("modified event==" + jsonObject.toString());
- System.out.println("responseData==" + responseData);
- assertEquals (eventName, responseData);
- }
-
- @Test
- public void testAttrSubtract(){
-
- final JSONObject jsonObject = getFileAsJsonObject();
- final String memoryConfigured = (jsonObject.getJSONObject("event")).getJSONObject("faultFields").get("memoryConfigured").toString();
- final String memoryUsed = (jsonObject.getJSONObject("event")).getJSONObject("faultFields").get("memoryUsed").toString();
- System.out.println("event==" + jsonObject.toString());
- System.out.println("memoryConfigured==" + memoryConfigured);
- System.out.println("memoryUsed==" + memoryUsed);
- final JSONObject jsonArgs = new JSONObject ( "{\"field\": \"event.faultFields.memoryFree\",\"subtract\": [\"$event.faultFields.memoryConfigured\",\"$event.faultFields.memoryUsed\"]}" );
- ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
- cpEvent.subtractValue(jsonArgs);
- final String responseData = cpEvent.getEventObjectVal("event.faultFields.memoryFree").toString();
- System.out.println("modified event==" + jsonObject.toString());
- System.out.println("responseData==" + responseData);
- assertEquals ("1980.0", responseData);
- }
-}
-
diff --git a/src/test/java/org/onap/dcae/vestest/InputJsonValidation.java b/src/test/java/org/onap/dcae/vestest/InputJsonValidation.java
deleted file mode 100644
index 72ebdea3..00000000
--- a/src/test/java/org/onap/dcae/vestest/InputJsonValidation.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.dcae.vestest;
-
-import com.google.gson.JsonIOException;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class InputJsonValidation {
-
- private static final Logger log = LoggerFactory.getLogger(InputJsonValidation.class);
- static String valresult;
-
-
- @Test
- public void nonValidJsonValidation() {
-
- JSONObject jsonObject;
- JSONParser parser = new JSONParser();
- Object obj = null;
- //String jsonfilepath="C:/Users/vv770d/git/restfulcollector/src/test/resources/fujistu_non_valid_json.txt";
- String jsonfilepath = "src/test/resources/VES_invalid.txt";
- String retValue = "false";
- try {
-
- obj = parser.parse(new FileReader(jsonfilepath));
- } catch (Exception e) {
-
- log.info("Exception while opening the file");
- }
- jsonObject = (JSONObject) obj;
-
- String schema = null;
- try {
- schema = new JsonParser().parse(new FileReader("etc/CommonEventFormat_27.2.json"))
- .toString();
- //log.info("Schema value: " + schema.toString());
- } catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
- // TODO Auto-generated catch block
- log.error(e.getLocalizedMessage(), e);
- }
-
- if (schema != null) {
- retValue = CommonStartup.schemavalidate(jsonObject.toString(), schema);
- }
- //return retValue;
- VesCollectorJunitTest.output = retValue;
- }
-
-
- // The below test case meant for verifying json schema on provided json file
- @Test
- public void validJsonValidation() {
-
- JSONObject jsonObject;
- JSONParser parser = new JSONParser();
- Object obj = null;
-
- String jsonfilepath = "src/test/resources/VES_valid.txt";
- String retValue = "false";
- try {
-
- obj = parser.parse(new FileReader(jsonfilepath));
- } catch (Exception e) {
- log.info("Exception while opening the file");
- }
- jsonObject = (JSONObject) obj;
- String schema = null;
- try {
-
- log.info("XX debug" + VesCollectorJunitTest.schemaFile);
- schema = new JsonParser().parse(new FileReader("etc/CommonEventFormat_27.2.json"))
- .toString();
- } catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
- // TODO Auto-generated catch block
- log.error(e.getLocalizedMessage(), e);
- }
-
- if (schema != null) {
- retValue = CommonStartup.schemavalidate(jsonObject.toString(), schema);
- }
- VesCollectorJunitTest.output = retValue;
- //return retValue;
- }
-
-
- //validating valid json reception and its posting to DMAP.
- @Test
- public void eventReception() {
-
- String testCurlCommand = "curl -i -X POST -d @C:/Users/vv770d/git/restfulcollector/src/test/resources/fujistu-3.txt --header \"Content-Type: application/json\" http://localhost:8080/eventListener/v1";
-
- //final Process terminal = curlCommand.start();
- try {
- Process process = Runtime.getRuntime().exec(testCurlCommand);
- BufferedReader stdInput = new BufferedReader(new
- InputStreamReader(process.getInputStream()));
-
- BufferedReader stdError = new BufferedReader(new
- InputStreamReader(process.getErrorStream()));
-
- // read the output from the command
-
- String str;
- while ((str = stdInput.readLine()) != null) {
- if (str.contains("HTTP/1.1 200 OK")) {
-
- //return "true";
- VesCollectorJunitTest.output = "true";
- }
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- log.error(e.getLocalizedMessage(), e);
- }
-
- //return "false";
- }
-}
-
diff --git a/src/test/java/org/onap/dcae/vestest/TestCommonStartup.java b/src/test/java/org/onap/dcae/vestest/TestCommonStartup.java
deleted file mode 100644
index 0cf90759..00000000
--- a/src/test/java/org/onap/dcae/vestest/TestCommonStartup.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcae.vestest;
-
-import java.io.FileReader;
-import java.io.IOException;
-import java.net.URL;
-import java.util.Map;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.onap.dcae.commonFunction.EventProcessor;
-import org.onap.dcae.commonFunction.CommonStartup.QueueFullException;
-import org.onap.dcae.restapi.RestfulCollectorServlet;
-
-import com.att.nsa.cmdLine.NsaCommandLineUtil;
-import com.att.nsa.drumlin.service.framework.DrumlinServlet;
-import com.att.nsa.drumlin.till.nv.rrNvReadable.loadException;
-import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;
-import com.att.nsa.security.NsaAuthenticator;
-import com.att.nsa.security.authenticators.SimpleAuthenticator;
-import com.att.nsa.security.db.simple.NsaSimpleApiKey;
-import com.google.gson.JsonParser;
-import com.att.nsa.drumlin.till.nv.impl.nvPropertiesFile;
-import com.att.nsa.drumlin.till.nv.impl.nvReadableStack;
-import com.att.nsa.drumlin.till.nv.impl.nvReadableTable;
-
-
-public class TestCommonStartup {
-
- String payload = null;
- @Before
- public void setUp() throws Exception {
-
- // process command line arguments
- payload = new JsonParser().parse(new FileReader("src/test/resources/VES_valid.txt")).toString();
- CommonStartup.fProcessingInputQueue = new LinkedBlockingQueue<JSONObject> (CommonStartup.KDEFAULT_MAXQUEUEDEVENTS);
- }
-
- @After
- public void tearDown() throws Exception {
-
- }
-
- @Test
- public void testCommonStartupload() {
-
- String args[] = { "junittest" };
- final Map<String, String> argMap = NsaCommandLineUtil.processCmdLine(args, true);
- final String config = NsaCommandLineUtil.getSetting(argMap, "c", "collector.properties");
- final URL settingStream = DrumlinServlet.findStream(config, CommonStartup.class);
-
- final nvReadableStack settings = new nvReadableStack();
- try {
- settings.push(new nvPropertiesFile(settingStream));
- } catch (loadException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- settings.push(new nvReadableTable(argMap));
- Assert.assertEquals("true", "true");
- }
-
- @Test
- public void testhandleevent() {
- JSONArray jsonArrayMod = new JSONArray().put(new JSONObject(payload));
- try {
-
-
- CommonStartup.handleEvents (jsonArrayMod);
- } catch ( JSONException | QueueFullException | IOException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- System.out.println("junit reported:" + e.getMessage());
- }
- Assert.assertEquals("true", "true");
- }
-
-
-/*
- @Test
- public void testServlet() {
- try
- {
- RestfulCollectorServlet rsv = new RestfulCollectorServlet(null);
- }
- catch (NullPointerException|loadException| missingReqdSetting e){
- System.out.println("junit reported:" + e.getMessage());
- }
- Assert.assertEquals("true", "true");
- }
-*/
-
-
- @Test
- public void testEventProcessorinstantiation()
- {
- CommonStartup.streamid="fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling";
- EventProcessor ep = new EventProcessor ();
- Thread epThread=new Thread(ep);
- epThread.start();
- Assert.assertEquals("true", "true");
- epThread.stop();
-
- }
-
- @Test
- public void testAuthListHandler()
- {
-
- final Map<String, String> argMap = NsaCommandLineUtil.processCmdLine ( new String[0], true );
- final String config = NsaCommandLineUtil.getSetting ( argMap, "c", "collector.properties" );
- final URL settingStream = DrumlinServlet.findStream ( config, CommonStartup.class );
-
- final nvReadableStack settings = new nvReadableStack ();
- try {
- settings.push ( new nvPropertiesFile ( settingStream ) );
- settings.push ( new nvReadableTable ( argMap ) );
- } catch (loadException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
-
-
- RestfulCollectorServlet rsv = null;
- NsaAuthenticator<NsaSimpleApiKey> NsaAuth = null;
- Boolean flag = false;
- try
- {
- rsv = new RestfulCollectorServlet(settings);
- }
- catch (NullPointerException|loadException| missingReqdSetting e){
- System.out.println("junit reported:" + e.getMessage());
- }
- String authlist = "secureid,IWRjYWVSb2FkbTEyMyEt|sample1,c2FtcGxlMQ==|vdnsagg,dmRuc2FnZw==";
- NsaAuth = rsv.AuthlistHandler(authlist);
- if (NsaAuth != null)
- {
- flag = true;
- }
- Assert.assertEquals(true, flag);
-
-
- }
-}
-
-
diff --git a/src/test/java/org/onap/dcae/vestest/TestConfigProcessor.java b/src/test/java/org/onap/dcae/vestest/TestConfigProcessor.java
new file mode 100644
index 00000000..49b53d24
--- /dev/null
+++ b/src/test/java/org/onap/dcae/vestest/TestConfigProcessor.java
@@ -0,0 +1,309 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.vestest;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.FileReader;
+import java.io.IOException;
+import org.json.JSONObject;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonObject;
+import org.junit.Test;
+
+import org.onap.dcae.commonFunction.ConfigProcessors;
+
+
+public class TestConfigProcessor {
+
+ private JSONObject getFileAsJsonObject() {
+ JSONObject jsonObject = null;
+ FileReader fr = null;
+ final JsonParser parser = new JsonParser();
+ String jsonFilePath = "src/test/resources/event4xjson.txt";
+ try {
+ fr = new FileReader(jsonFilePath);
+ final JsonObject jo = (JsonObject) parser.parse(fr);
+ final String jsonText = jo.toString();
+ jsonObject = new JSONObject(jsonText);
+ } catch (Exception e) {
+ System.out.println("Exception while opening the file");
+ e.printStackTrace();
+ } finally {
+ //close the file
+ if (fr != null) {
+ try {
+ fr.close();
+ } catch (IOException e) {
+ System.out.println("Error closing file reader stream : " + e.toString());
+ }
+ }
+ }
+ return jsonObject;
+ }
+
+ @Test
+ public void testAttrMap() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ final String functionRole = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader")
+ .get("functionalRole").toString();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("functionRole==" + functionRole);
+ final JSONObject jsonArgs = new JSONObject(
+ "{\"field\": \"event.commonEventHeader.nfNamingCode\",\"oldField\": \"event.commonEventHeader.functionalRole\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.map(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.commonEventHeader.nfNamingCode").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals(functionRole, responseData);
+ }
+
+ @Test
+ public void testArrayMap() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ final String alarmAdditionalInformation = (jsonObject.getJSONObject("event")).getJSONObject("faultFields")
+ .get("alarmAdditionalInformation").toString();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("alarmAdditionalInformation==" + alarmAdditionalInformation);
+ final JSONObject jsonArgs = new JSONObject(
+ "{\"field\": \"event.faultFields.eventAdditionalInformation\",\"oldField\": \"event.faultFields.alarmAdditionalInformation\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.map(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.eventAdditionalInformation")
+ .toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals(alarmAdditionalInformation, responseData);
+ }
+
+ @Test
+ public void testJSONObjectMapToArray() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ //final String receiveDiscards = (((jsonObject.getJSONObject("event")).getJSONObject("faultFields")).get("errors")).get("receiveDiscards").toString();
+ System.out.println("event==" + jsonObject.toString());
+ //System.out.println("alarmAdditionalInformation==" + alarmAdditionalInformation);
+ final JSONObject jsonArgs = new JSONObject(
+ "{\"field\": \"event.faultFields.vNicPerformanceArray[]\",\"oldField\": \"event.faultFields.errors\",\"attrMap\":{\"receiveDiscards\":\"receivedDiscardedPacketsAccumulated\"}}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ final String receiveDiscards = cpEvent.getEventObjectVal("event.faultFields.errors.receiveDiscards").toString();
+ System.out.println("receiveDiscards==" + receiveDiscards);
+ cpEvent.map(jsonArgs);
+ final String responseData = cpEvent
+ .getEventObjectVal("event.faultFields.vNicPerformanceArray[0].receivedDiscardedPacketsAccumulated")
+ .toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals(receiveDiscards, responseData);
+ }
+
+ @Test
+ public void testAttrAdd() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ //final String functionRole = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("functionalRole").toString();
+ System.out.println("event==" + jsonObject.toString());
+ //System.out.println("functionRole==" + functionRole);
+ final JSONObject jsonArgs = new JSONObject(
+ "{\"field\": \"event.faultFields.version\",\"value\": \"2.0\",\"fieldType\": \"number\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.addAttribute(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.version").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals("2.0", responseData);
+ }
+
+ @Test
+ public void testAttrUpdate() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ //final String functionRole = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("functionalRole").toString();
+ System.out.println("event==" + jsonObject.toString());
+ //System.out.println("functionRole==" + functionRole);
+ final JSONObject jsonArgs = new JSONObject(
+ "{\"field\": \"event.faultFields.version\",\"value\": \"2.0\",\"fieldType\": \"number\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.updateAttribute(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.version").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals("2.0", responseData);
+ }
+
+ @Test
+ public void testAttrConcatenate() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ final String eventType = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("eventType")
+ .toString();
+ final String domain = (jsonObject.getJSONObject("event")).getJSONObject("commonEventHeader").get("domain")
+ .toString();
+ final String alarmCondition = (jsonObject.getJSONObject("event")).getJSONObject("faultFields")
+ .get("alarmCondition").toString();
+ System.out.println("event==" + jsonObject.toString());
+ final String eventName = domain + "_" + eventType + "_" + alarmCondition;
+ System.out.println("eventName==" + eventName);
+ final JSONObject jsonArgs = new JSONObject(
+ "{\"field\":\"event.commonEventHeader.eventName\",\"concatenate\": [\"$event.commonEventHeader.domain\",\"$event.commonEventHeader.eventType\",\"$event.faultFields.alarmCondition\"],\"delimiter\":\"_\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.concatenateValue(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.commonEventHeader.eventName").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals(eventName, responseData);
+ }
+
+ @Test
+ public void testAttrSubtract() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ final String memoryConfigured = (jsonObject.getJSONObject("event")).getJSONObject("faultFields")
+ .get("memoryConfigured").toString();
+ final String memoryUsed = (jsonObject.getJSONObject("event")).getJSONObject("faultFields").get("memoryUsed")
+ .toString();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("memoryConfigured==" + memoryConfigured);
+ System.out.println("memoryUsed==" + memoryUsed);
+ final JSONObject jsonArgs = new JSONObject(
+ "{\"field\": \"event.faultFields.memoryFree\",\"subtract\": [\"$event.faultFields.memoryConfigured\",\"$event.faultFields.memoryUsed\"]}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.subtractValue(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.memoryFree").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals("1980.0", responseData);
+ }
+
+ @Test
+ public void testSetValue() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("Testing SetValue");
+ final JSONObject jsonArgs = new JSONObject(
+ "{\"field\": \"event.faultFields.version\",\"value\": \"2.0\",\"fieldType\": \"number\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.setValue(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.version").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals("2.0", responseData);
+ }
+
+ @Test
+ public void testSetEventObjectVal() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("Testing SetEventObjectVal");
+ //final JSONObject jsonArgs = new JSONObject ( "{\"field\": \"event.faultFields.version\",\"value\": \"2.0\",\"fieldType\": \"number\"}" );
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.setEventObjectVal("event.faultFields.version", "2.0", "number");
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.version").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals("2.0", responseData);
+ }
+
+ @Test
+ public void testGetValue() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("Testing GetValue");
+ final JSONObject jsonArgs = new JSONObject("{\"field\": \"event.faultFields.eventSeverity\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.getValue(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.eventSeverity").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals("CRITICAL", responseData);
+ }
+
+ @Test
+ public void testGetEventObjectVal() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("Testing GetEventObjectVal");
+ //final JSONObject jsonArgs = new JSONObject ( "{\"field\": \"event.faultFields.eventSeverity\"}" );
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.getEventObjectVal("event.faultFields.eventSeverity");
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.eventSeverity").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals("CRITICAL", responseData);
+ }
+
+ @Test
+ public void testRemoveAttribute() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("Testing removeAttribute");
+ final JSONObject jsonArgs = new JSONObject("{\"field\": \"event.faultFields.memoryUsed\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+ cpEvent.removeAttribute(jsonArgs);
+ final String responseData = cpEvent.getEventObjectVal("event.faultFields.memoryUsed").toString();
+ System.out.println("modified event==" + jsonObject.toString());
+ System.out.println("responseData==" + responseData);
+ assertEquals("ObjectNotFound", responseData);
+ }
+
+ @Test
+ public void testIsFilterMet() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("Testing isFilterMet");
+ final JSONObject jsonArgs = new JSONObject("{\"event.faultFields.eventSeverity\":\"CRITICAL\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+
+ final boolean response = cpEvent.isFilterMet(jsonArgs);
+ String responseData = "CRITICAL";
+ if (!response) {
+ responseData = "notCRITICAL";
+ }
+
+ System.out.println("responseData==" + responseData);
+ assertEquals("CRITICAL", responseData);
+ }
+
+ @Test
+ public void testSuppressEvent() {
+
+ final JSONObject jsonObject = getFileAsJsonObject();
+ System.out.println("event==" + jsonObject.toString());
+ System.out.println("Testing SuppressEvent");
+ final JSONObject jsonArgs = new JSONObject("{\"event.faultFields.eventSeverity\":\"CRITICAL\"}");
+ ConfigProcessors cpEvent = new ConfigProcessors(jsonObject);
+
+ cpEvent.suppressEvent(jsonArgs);
+ String responseData = cpEvent.getEventObjectVal("suppressEvent").toString();
+
+ System.out.println("responseData==" + responseData);
+ assertEquals("true", responseData);
+ }
+}
+
diff --git a/src/test/java/org/onap/dcae/vestest/TestCustomExceptionLoader.java b/src/test/java/org/onap/dcae/vestest/TestCustomExceptionLoader.java
deleted file mode 100644
index 1cbd6c43..00000000
--- a/src/test/java/org/onap/dcae/vestest/TestCustomExceptionLoader.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.dcae.vestest;
-
-import static org.junit.Assert.assertEquals;
-
-import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.onap.dcae.commonFunction.CustomExceptionLoader;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class TestCustomExceptionLoader {
-
- private static final Logger log = LoggerFactory.getLogger(TestCustomExceptionLoader.class);
- private CustomExceptionLoader cl;
-
- @Before
- public void setUp() throws Exception {
- cl = new CustomExceptionLoader();
- CommonStartup.exceptionConfig = "./etc/ExceptionConfig.json";
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void testLoad() {
- String op;
- CustomExceptionLoader.LoadMap();
- op = "dataloaded";
- assertEquals("dataloaded", op);
- }
-
- @Test
- public void testLookup() {
- String[] retarray;
-
- CommonStartup.exceptionConfig = "./etc/ExceptionConfig.json";
- CustomExceptionLoader.LoadMap();
- retarray = CustomExceptionLoader
- .LookupMap(String.valueOf(HttpStatusCodes.k401_unauthorized), "Unauthorized user");
- if (retarray == null) {
- log.info("Lookup failed");
- } else {
- assertEquals("\"POL2000\"", retarray[0]);
- }
- }
-}
-
diff --git a/src/test/java/org/onap/dcae/vestest/TestDmaapPropertyReader.java b/src/test/java/org/onap/dcae/vestest/TestDefaultConfiguration.java
index e54b4cbb..826d26d5 100644
--- a/src/test/java/org/onap/dcae/vestest/TestDmaapPropertyReader.java
+++ b/src/test/java/org/onap/dcae/vestest/TestDefaultConfiguration.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,42 +17,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.dcae.vestest;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import org.onap.dcae.commonFunction.DmaapPropertyReader;
-
-public class TestDmaapPropertyReader {
-
- DmaapPropertyReader dr;
- String testinput = "src/test/resources/testDmaapConfig.json";
- Boolean flag = false;
-
- @Before
- public void setUp() throws Exception {
- // process command line arguments
-
- dr = new DmaapPropertyReader(testinput);
-
- }
-
- @After
- public void tearDown() throws Exception {
+/*
+ *
+ * Purpose: CommonCollectorJunitTest is the wrapper class to invoke all prescribed Junit test cases.
+ *
+ */
- }
+package org.onap.dcae.vestest;
- @Test
- public void testDmaapPropertyReader() {
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import org.json.JSONObject;
+import org.junit.Test;
- Boolean test = true;
- flag = !dr.dmaap_hash.isEmpty();
- Assert.assertEquals(test, flag);
- }
+public class TestDefaultConfiguration {
+ @Test
+ public void shouldDefaultCollectorSchemaFileBeAValidJson() throws IOException {
+ try (BufferedReader bufferedReader = Files.newBufferedReader(Paths.get("etc/collector.properties"))) {
+ Properties properties = new Properties();
+ properties.load(bufferedReader);
+ new JSONObject(properties.getProperty("collector.schema.file"));
+ }
+ }
}
diff --git a/src/test/java/org/onap/dcae/vestest/TestEventProcessor.java b/src/test/java/org/onap/dcae/vestest/TestEventProcessor.java
deleted file mode 100644
index 31807dba..00000000
--- a/src/test/java/org/onap/dcae/vestest/TestEventProcessor.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcae.vestest;
-
-import static org.junit.Assert.*;
-
-
-import java.io.File;
-import java.io.FileReader;
-import java.net.URL;
-import java.util.Map;
-
-import org.json.simple.JSONObject;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.onap.dcae.commonFunction.EventProcessor;
-import org.onap.dcae.commonFunction.EventPublisher;
-import org.onap.dcae.controller.LoadDynamicConfig;
-import org.onap.dcae.commonFunction.DmaapPropertyReader;
-
-
-import com.google.gson.JsonParser;
-
-public class TestEventProcessor {
-
- EventProcessor ec;
- String ev= "{\"event\": {\"commonEventHeader\": { \"reportingEntityName\": \"VM name will be provided by ECOMP\", \"startEpochMicrosec\": 1477012779802988,\"lastEpochMicrosec\": 1477012789802988,\"eventId\": \"83\",\"sourceName\": \"Dummy VM name - No Metadata available\",\"sequence\": 83,\"priority\": \"Normal\",\"functionalRole\": \"vFirewall\",\"domain\": \"measurementsForVfScaling\",\"reportingEntityId\": \"VM UUID will be provided by ECOMP\",\"sourceId\": \"Dummy VM UUID - No Metadata available\",\"version\": 1.1},\"measurementsForVfScalingFields\": {\"measurementInterval\": 10,\"measurementsForVfScalingVersion\": 1.1,\"vNicUsageArray\": [{\"multicastPacketsIn\": 0,\"bytesIn\": 3896,\"unicastPacketsIn\": 0, \"multicastPacketsOut\": 0,\"broadcastPacketsOut\": 0, \"packetsOut\": 28,\"bytesOut\": 12178,\"broadcastPacketsIn\": 0,\"packetsIn\": 58,\"unicastPacketsOut\": 0,\"vNicIdentifier\": \"eth0\"}]}}}";
-
-
- @Before
- public void setUp() throws Exception {
- CommonStartup.streamid="fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling";
- CommonStartup.eventTransformFlag = 1;
-
-
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void testLoad() {
-
-
- EventProcessor ec = new EventProcessor();
-
- ec.event=new org.json.JSONObject(ev);
-
- ec.overrideEvent();
- //event.commonEventHeader.sourceName
- Boolean flag = ec.event.getJSONObject("event").getJSONObject("commonEventHeader").has("sourceName");
- assertEquals(true, flag);
- }
-
-
- @Test
- public void testpublisher() {
-
- DmaapPropertyReader dr;
- EventPublisher ep = null;
- String testinput = "src/test/resources/testDmaapConfig.json";
- Boolean flag = false;
- dr = new DmaapPropertyReader(testinput);
-
- //new EventPublisher("sec_fault_ueb");
- ep = EventPublisher.getInstance("sec_fault_ueb");
- //event.commonEventHeader.sourceName
-
- if (ep.equals(null))
- {
- flag = false;
- }
- else
- {
- flag = true;
- }
- assertEquals(true, flag);
- }
-
-
-}
-
diff --git a/src/test/java/org/onap/dcae/vestest/TestEventReceipt.java b/src/test/java/org/onap/dcae/vestest/TestEventReceipt.java
new file mode 100644
index 00000000..a3893eaa
--- /dev/null
+++ b/src/test/java/org/onap/dcae/vestest/TestEventReceipt.java
@@ -0,0 +1,46 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.vestest;
+
+import static org.junit.Assert.assertEquals;
+
+import org.json.JSONObject;
+import org.junit.Test;
+import org.onap.dcae.commonFunction.CommonStartup;
+import org.onap.dcae.restapi.endpoints.EventReceipt;
+
+public class TestEventReceipt {
+
+
+ @Test
+ public void shouldGetSchemaFileLocationBasedOnVersion() {
+ CommonStartup.schemaFileJson = new JSONObject("{\"v1\":\"filePath1\", \"v5\":\"filePath2\"}");
+ String schemaFilePath = EventReceipt.schemaFileVersion("v5");
+ assertEquals(schemaFilePath, "filePath2");
+ }
+
+ @Test
+ public void shouldByDefaultReturnV5SchemaFileLocation() {
+ CommonStartup.schemaFileJson = new JSONObject("{\"v1\":\"filePath1\", \"v5\":\"filePath2\"}");
+ String schemaFilePath = EventReceipt.schemaFileVersion("v2");
+ assertEquals(schemaFilePath, "filePath2");
+ }
+
+}
diff --git a/src/test/java/org/onap/dcae/vestest/TestFetchConfig.java b/src/test/java/org/onap/dcae/vestest/TestFetchConfig.java
new file mode 100644
index 00000000..0b6b5027
--- /dev/null
+++ b/src/test/java/org/onap/dcae/vestest/TestFetchConfig.java
@@ -0,0 +1,81 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.vestest;
+
+import static org.junit.Assert.assertTrue;
+import static org.onap.dcae.vestest.TestingUtilities.createTemporaryFile;
+
+import com.google.gson.JsonObject;
+import java.nio.file.Path;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.dcae.controller.FetchDynamicConfig;
+import org.onap.dcae.controller.LoadDynamicConfig;
+
+
+public class TestFetchConfig {
+
+ private Path temporaryFile;
+
+ @Before
+ public void setUp() {
+ temporaryFile = createTemporaryFile();
+ }
+
+ @Test
+ public void shouldWriteFileAndAttachDMaaPStreamsPropertiesFromConfiguration() {
+ // given
+ FetchDynamicConfig loadDynamicConfig = new FetchDynamicConfig();
+ FetchDynamicConfig.configFile = temporaryFile.toString();
+ String sampleConfiguration = LoadDynamicConfig.readFile("src/test/resources/controller-config_singleline_ip.json");
+
+ // when
+ loadDynamicConfig.writefile(sampleConfiguration);
+
+ // then
+ JsonObject actuallyWrittenJSONContent = TestingUtilities.readJSONFromFile(temporaryFile);
+ assertTrue(actuallyWrittenJSONContent.has("streams_publishes"));
+ }
+
+ @Test
+ public void shouldThrowNoErrorsWhileParsingConsulResponse() {
+ // given
+ FetchDynamicConfig.retString = "[{\"ID\":\"81bc2a17-8cfa-3f6f-30a9-a545a9b6ac2f\",\"Node\":\"zldcrdm5bdcc2dokr00\",\"Address\":\"135.25.108.161\",\"Datacenter\":\"zldcrdm5bdcc2\",\"TaggedAddresses\":{\"lan\":\"135.25.108.161\",\"wan\":\"135.25.108.161\"},\"NodeMeta\":{\"fqdn\":\"zldcrdm5bdcc2dokr00.2f3fb3.rdm5b.tci.att.com\"},\"ServiceID\":\"20299a144716:config_binding_service:10000\",\"ServiceName\":\"config_binding_service\",\"ServiceTags\":[],\"ServiceAddress\":\"135.25.108.161\",\"ServicePort\":10000,\"ServiceEnableTagOverride\":false,\"CreateIndex\":9153156,\"ModifyIndex\":9153156}]";
+
+ // then
+ FetchDynamicConfig.getCBS();
+ }
+
+
+ @Test
+ public void shouldReturnTrueOnConfigurationChange() {
+ // given
+ FetchDynamicConfig.configFile = "src/test/resources/controller-config_singleline_ip.json";
+ FetchDynamicConfig.retCBSString = "{\"header.authflag\": \"1\", \"collector.schema.file\": \"{\\\"v1\\\": \\\"./etc/CommonEventFormat_27.2.json\\\", \\\"v2\\\": \\\"./etc/CommonEventFormat_27.2.json\\\", \\\"v3\\\": \\\"./etc/CommonEventFormat_27.2.json\\\", \\\"v4\\\": \\\"./etc/CommonEventFormat_27.2.json\\\", \\\"v5\\\": \\\"./etc/CommonEventFormat_28.4.json\\\"}\", \"collector.keystore.passwordfile\": \"/opt/app/dcae-certificate/.password\", \"tomcat.maxthreads\": \"200\", \"collector.dmaap.streamid\": \"fault=ves-fault|syslog=ves-syslog|heartbeat=ves-heartbeat|measurementsForVfScaling=ves-measurement|mobileFlow=ves-mobileflow|other=ves-other|stateChange=ves-statechange|thresholdCrossingAlert=ves-thresholdCrossingAlert|voiceQuality=ves-voicequality|sipSignaling=ves-sipsignaling\", \"streams_subscribes\": {}, \"collector.inputQueue.maxPending\": \"8096\", \"collector.keystore.alias\": \"dynamically generated\", \"streams_publishes\": {\"ves-mobileflow\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590629043\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-MOBILEFLOW-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-measurement\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590433916\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-ENC-MEASUREMENT-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-voicequality\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590778397\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-VES-VOICEQUALITY-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-thresholdCrossingAlert\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590728150\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-TCA-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-fault\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590384670\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-FAULT-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-heartbeat\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590530041\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-HEARTBEAT-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-sipsignaling\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590828736\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-VES-SIPSIGNALING-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-syslog\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590482019\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-SYSLOG-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-other\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590581045\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-OTHER-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}, \"ves-statechange\": {\"type\": \"message_router\", \"dmaap_info\": {\"client_id\": \"1517590677649\", \"client_role\": \"com.att.secCollector.member\", \"location\": \"rdm5bdcc2\", \"topic_url\": \"https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-STATECHANGE-OUTPUT-v1\"}, \"aaf_username\": \"userid@namespace\", \"aaf_password\": \"authpwd\"}}, \"collector.schema.checkflag\": \"1\", \"services_calls\": {}, \"event.transform.flag\": \"1\", \"collector.keystore.file.location\": \"/opt/app/dcae-certificate/keystore.jks\", \"header.authlist\": \"sample1,c2FtcGxlMQ==|userid1,base64encodepwd1|userid2,base64encodepwd2\", \"collector.service.secure.port\": \"8443\", \"collector.service.port\": \"-1\"}";
+
+ // when
+ boolean didConfigsChange = FetchDynamicConfig.verifyConfigChange();
+
+ // then
+ assertTrue(didConfigsChange);
+ }
+
+}
+
diff --git a/src/test/java/org/onap/dcae/vestest/TestJsonSchemaValidation.java b/src/test/java/org/onap/dcae/vestest/TestJsonSchemaValidation.java
new file mode 100644
index 00000000..0489811d
--- /dev/null
+++ b/src/test/java/org/onap/dcae/vestest/TestJsonSchemaValidation.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dcae.vestest;
+
+import static java.nio.file.Files.readAllBytes;
+import static junit.framework.Assert.assertEquals;
+
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import java.io.IOException;
+import java.nio.file.Paths;
+import org.junit.Test;
+import org.onap.dcae.commonFunction.CommonStartup;
+
+public class TestJsonSchemaValidation {
+
+ @Test
+ public void shouldValidEventPassSchema_27_2() throws IOException {
+ String result = CommonStartup.validateAgainstSchema(
+ readJSONFromFile("src/test/resources/VES_valid.txt").toString(),
+ readJSONFromFile("etc/CommonEventFormat_27.2.json").toString());
+ assertEquals(result, "true");
+ }
+
+
+ @Test
+ public void shouldInvalidEventDoesNotPassSchema_27_2() throws IOException {
+ String result = CommonStartup.validateAgainstSchema(
+ readJSONFromFile("src/test/resources/VES_invalid.txt").toString(),
+ readJSONFromFile("etc/CommonEventFormat_27.2.json").toString());
+ assertEquals(result, "false");
+ }
+
+
+ private static JsonObject readJSONFromFile(String path) throws IOException {
+ return (JsonObject) new JsonParser().parse(new String(readAllBytes(Paths.get(path))));
+ }
+}
+
diff --git a/src/test/java/org/onap/dcae/vestest/TestLoadDynamicConfig.java b/src/test/java/org/onap/dcae/vestest/TestLoadDynamicConfig.java
index 902add73..03a074d7 100644
--- a/src/test/java/org/onap/dcae/vestest/TestLoadDynamicConfig.java
+++ b/src/test/java/org/onap/dcae/vestest/TestLoadDynamicConfig.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PROJECT
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,54 +19,58 @@
*/
package org.onap.dcae.vestest;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.onap.dcae.vestest.TestingUtilities.createTemporaryFile;
-import java.io.File;
-import java.io.FileReader;
-import java.net.URL;
-import java.util.Map;
-
-import org.json.simple.JSONObject;
-
-import org.junit.After;
-import org.junit.Assert;
+import com.github.fge.jackson.JsonLoader;
+import com.google.gson.JsonObject;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.onap.dcae.controller.LoadDynamicConfig;
-import com.google.gson.JsonParser;
-
public class TestLoadDynamicConfig {
- LoadDynamicConfig lc;
- String propop = "src/test/resources/testcollector.properties";
-
- @Before
- public void setUp() throws Exception {
-
-
+ private Path temporaryFile;
+
+ @Before
+ public void setUp() {
+ temporaryFile = createTemporaryFile();
+ }
+
+ @Test
+ public void shouldReadFileContent() throws IOException {
+ // given
+ String expectedJSON = "{ \"field\" : 1 }";
+ Files.write(temporaryFile, expectedJSON.getBytes());
- }
+ // when
+ String readFileContent = LoadDynamicConfig.readFile(temporaryFile.toString());
- @After
- public void tearDown() throws Exception {
- }
+ // then
+ assertEquals(JsonLoader.fromString(expectedJSON), JsonLoader.fromString(readFileContent));
+ }
- @Test
- public void testLoad() {
+ @Test
+ public void shouldWriteFileAndAttachDMaaPRelatedPropertiesFromConfiguration() {
+ // given
+ LoadDynamicConfig loadDynamicConfig = new LoadDynamicConfig();
+ loadDynamicConfig.propFile = "src/test/resources/test_collector_ip_op.properties";
+ loadDynamicConfig.configFile = "src/test/resources/controller-config_dmaap_ip.json";
+ loadDynamicConfig.dMaaPOutputFile = temporaryFile.toString();
+ String sampleConfiguration = LoadDynamicConfig.readFile(loadDynamicConfig.configFile);
- // File file = new File(".");
- // for(String fileNames : file.list()) System.out.println(fileNames);
-
- Boolean flag=false;
- lc = new LoadDynamicConfig();
- lc.propFile = "src/test/resources/testcollector.properties";
- lc.configFile = "src/test/resources/controller-config.json";
-
- String data = LoadDynamicConfig.readFile(propop);
- assertEquals(data.isEmpty(), flag);
- }
+ // when
+ loadDynamicConfig.writeconfig(new JSONObject(sampleConfiguration));
+ // then
+ JsonObject actuallyWrittenJSONContent = TestingUtilities.readJSONFromFile(temporaryFile);
+ assertTrue(actuallyWrittenJSONContent.has("ves-fault-secondary"));
+ }
}
diff --git a/src/test/java/org/onap/dcae/vestest/TestSchemaValidation.java b/src/test/java/org/onap/dcae/vestest/TestSchemaValidation.java
deleted file mode 100644
index a34b3336..00000000
--- a/src/test/java/org/onap/dcae/vestest/TestSchemaValidation.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcae.vestest;
-
-import static org.junit.Assert.*;
-
-import java.io.ByteArrayInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.simple.JSONObject;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.onap.dcae.restapi.endpoints.EventReceipt;
-
-import com.att.nsa.drumlin.service.framework.DrumlinServlet;
-import com.att.nsa.drumlin.service.framework.context.DrumlinRequestContext;
-import com.google.gson.JsonParser;
-
-public class TestSchemaValidation {
-
- CommonStartup cl;
- String schema = null;
- String payload = null;
- String payloadinvalid = null;
-
- @Before
- public void setUp() throws Exception {
-
- schema = new JsonParser().parse(new FileReader("etc/CommonEventFormat_27.2.json")).toString();
- payload = new JsonParser().parse(new FileReader("src/test/resources/VES_valid.txt")).toString();
- payloadinvalid = new JsonParser().parse(new FileReader("src/test/resources/VES_invalid.txt")).toString();
-
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void testsuccessfulschemavalidation() {
-
- String valresult = CommonStartup.schemavalidate(payload, schema);
- System.out.println("testsuccessfulschemavalidation:" + valresult);
- Assert.assertEquals(valresult, "true");
- }
-
- @Test
- public void testunsuccessfulschemavalidation() {
- String valresult = null;
- valresult = CommonStartup.schemavalidate(payloadinvalid, schema);
- System.out.println("testunsuccessfulschemavalidation:" + valresult);
- Assert.assertFalse(valresult.equals("true"));
-
- }
-
-
- @Test
- public void testeventReceipt() {
-
- //com.att.nsa.drumlin.service.framework.context.DrumlinRequestContext.DrumlinRequestContext(DrumlinServlet webServlet,
- //HttpServletRequest req, HttpServletResponse resp, DrumlinConnection s, Map<String, Object> objects, DrumlinRequestRouter router)
- //HttpServletRequest req = new HttpServletRequest();
- //HttpServletResponse res = new HttpServletResponse();
- DrumlinServlet webServlet = new DrumlinServlet();
- //webServlet.addToBaseContext(key, o);
- //Map<String,Object> mp = new Map<String, Object>();
- DrumlinRequestContext ctx = new DrumlinRequestContext(webServlet, null, null, null, null, null);
- EventReceipt er= new EventReceipt();
- try {
- EventReceipt.receiveVESEvent(null);
- } catch ( NullPointerException e) {
- // TODO Auto-generated catch block
-
- }
-
-
- Assert.assertEquals("true", "true");
-
- }
-
- @Test
- public void testsafeclosefr() {
-
-
- FileReader fr;
- try {
- fr = new FileReader("etc/CommonEventFormat_27.2.json");
- EventReceipt.safeClose(fr);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Assert.assertEquals("true", "true");
-
- }
-
- @Test
- public void testsafecloseis() {
-
- InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode("randomstring").array());
- EventReceipt.safeClose(is);
- Assert.assertEquals("true", "true");
-
- }
-}
-
diff --git a/src/test/java/org/onap/dcae/vestest/TestVESLogger.java b/src/test/java/org/onap/dcae/vestest/TestVESLogger.java
new file mode 100644
index 00000000..484f7dc8
--- /dev/null
+++ b/src/test/java/org/onap/dcae/vestest/TestVESLogger.java
@@ -0,0 +1,75 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.vestest;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.onap.dcae.commonFunction.VESLogger.REQUEST_ID;
+
+import com.att.nsa.logging.LoggingContext;
+import com.att.nsa.logging.log4j.EcompFields;
+import java.util.UUID;
+import org.junit.Test;
+import org.onap.dcae.commonFunction.VESLogger;
+
+public class TestVESLogger {
+
+ @Test
+ public void shouldOnLoggingContextInitializationPutRandomUUIDAsRequestID() {
+ LoggingContext commonLoggingContext = VESLogger.getCommonLoggingContext();
+ String requestId = commonLoggingContext.get(REQUEST_ID, "default");
+
+ assertNotNull(requestId);
+ assertNotSame(requestId, "default");
+
+ }
+
+ @Test
+ public void shouldOnLoggingContextInitializationPutGivenUUIDAsRequestIDAndSupplyEndTimestamp() {
+ final UUID uuid = UUID.randomUUID();
+ LoggingContext loggingContextForThread = VESLogger.getLoggingContextForThread(uuid);
+ String requestId = loggingContextForThread.get(REQUEST_ID, "default");
+ String endTimestamp = loggingContextForThread.get(EcompFields.kEndTimestamp, "default");
+
+ assertNotNull(requestId);
+ assertNotNull(endTimestamp);
+ assertNotSame(endTimestamp, "default");
+ assertEquals(requestId, uuid.toString());
+ }
+
+ @Test
+ public void shouldOnLoggingContextInitializationPutGivenUUIDAsRequestIDAndSupplyEndTimestampAndCompleteStatusCode() {
+ final UUID uuid = UUID.randomUUID();
+ LoggingContext loggingContextForThread = VESLogger.getLoggingContextForThread(uuid.toString());
+ String requestId = loggingContextForThread.get(REQUEST_ID, "default");
+ String statusCode = loggingContextForThread.get("statusCode", "default");
+ String endTimestamp = loggingContextForThread.get(EcompFields.kEndTimestamp, "default");
+
+ assertNotNull(requestId);
+ assertNotNull(endTimestamp);
+ assertNotNull(statusCode);
+ assertNotSame(endTimestamp, "default");
+ assertEquals(requestId, uuid.toString());
+ assertEquals(statusCode, "COMPLETE");
+ }
+
+}
+
diff --git a/src/test/java/org/onap/dcae/vestest/TestingUtilities.java b/src/test/java/org/onap/dcae/vestest/TestingUtilities.java
new file mode 100644
index 00000000..eff31f6d
--- /dev/null
+++ b/src/test/java/org/onap/dcae/vestest/TestingUtilities.java
@@ -0,0 +1,93 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.vestest;
+
+import static java.nio.file.Files.readAllBytes;
+
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import io.vavr.collection.HashMap;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+/**
+ * @author Pawel Szalapski (pawel.szalapski@nokia.com)
+ */
+public final class TestingUtilities {
+
+ private TestingUtilities() {
+ // utility class, no objects allowed
+ }
+
+ static JsonObject readJSONFromFile(Path path) {
+ return rethrow(() -> (JsonObject) new JsonParser().parse(new String(readAllBytes(path))));
+ }
+
+ static Path createTemporaryFile() {
+ return rethrow(() -> {
+ Path temporaryDirectory = Files.createTempDirectory("temporaryDirectory");
+ Path temporaryFile = TestingUtilities.createFile(temporaryDirectory + "/testFile");
+ TestingUtilities.scheduleToBeDeletedAfterTests(temporaryDirectory);
+ TestingUtilities.scheduleToBeDeletedAfterTests(temporaryFile);
+ return temporaryFile;
+ });
+ }
+
+ public static HashMap<String, String[]> convertDMaaPStreamsPropertyToMap(String streamIdsProperty) {
+ java.util.HashMap<String, String[]> domainToStreamIdsMapping = new java.util.HashMap<>();
+ String[] topics = streamIdsProperty.split("\\|");
+ for (String t : topics) {
+ String domain = t.split("=")[0];
+ String[] streamIds = t.split("=")[1].split(",");
+ domainToStreamIdsMapping.put(domain, streamIds);
+ }
+ return HashMap.ofAll(domainToStreamIdsMapping);
+ }
+
+ private static Path createFile(String path) {
+ return rethrow(() -> Files.createFile(Paths.get(path)));
+ }
+
+ private static void scheduleToBeDeletedAfterTests(Path path) {
+ path.toFile().deleteOnExit();
+ }
+
+ /**
+ * Exception in test case usually means there is something wrong, it should never be catched, but rather thrown to
+ * be handled by JUnit framework.
+ */
+ private static <T> T rethrow(CheckedSupplier<T> supplier) {
+ try {
+ return supplier.get();
+ } catch (Exception e) {
+ throw new RuntimeException();
+ }
+ }
+
+ @FunctionalInterface
+ interface CheckedSupplier<T> {
+
+ T get() throws Exception;
+ }
+
+
+}
diff --git a/src/test/java/org/onap/dcae/vestest/VesCollectorJunitTest.java b/src/test/java/org/onap/dcae/vestest/VesCollectorJunitTest.java
deleted file mode 100644
index 88ea1926..00000000
--- a/src/test/java/org/onap/dcae/vestest/VesCollectorJunitTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/*
- *
- * Purpose: CommonCollectorJunitTest is the wrapper class to invoke all prescribed Junit test cases.
- *
- */
-
-package org.onap.dcae.vestest;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-import org.json.JSONObject;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class VesCollectorJunitTest {
-
- private static final Logger log = LoggerFactory.getLogger(VesCollectorJunitTest.class);
-
- public static String schemaFile = "etc/CommonEventFormat_27.2.json";
- public static String output;
-
-
- String message = "true";
- InputJsonValidation messageUtil = new InputJsonValidation();
-
- @Test
- public void validJsonValidation() {
-
- output = "true";
- testHelper(new Properties());
-
- assertEquals("true", output);
- }
-
-
- @Test
- public void nonValidJsonValidation() {
- output = "false";
- testHelper(new Properties());
- //assertEquals("false",messageUtil.nonValidJsonValidation());
- assertEquals("false", output);
- }
-
- private void testHelper(Properties prop) {
- try (InputStream input = new FileInputStream("etc/collector.properties")) {
- prop.load(input);
- //schemaFile=prop.getProperty("collector.schema.file");
-
- JSONObject schemaFileJson = new JSONObject(
- prop.getProperty("collector.schema.file"));
- log.info("JSON Schemafile" + schemaFileJson);
- //schemaFile = schemaFileJson.getString("v4");
-
- log.info("Schema file location: " + schemaFile);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- log.error(e.getLocalizedMessage(), e);
- }
- }
-
- //The test case requires common collector running in the environment prior to start execution of JUNIT test cases
- /*
- @Test
- public void testValidJSONObjectReception() {
-
- assertEquals("true",messageUtil.eventReception());
- assertEquals("true",output);
- }*/
-}
-
diff --git a/src/test/java/org/onap/dcae/vestest/VesCollectorJunitTestRunner.java b/src/test/java/org/onap/dcae/vestest/VesCollectorJunitTestRunner.java
deleted file mode 100644
index 04f04ec8..00000000
--- a/src/test/java/org/onap/dcae/vestest/VesCollectorJunitTestRunner.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/*
- * Purpose: CommonCollectorJunitTestRunner is the main class where test suit execution starts its
- * test cases execution the common collector test suit has been written in order to incorporate
- * functional and logical testing of collector features.
- */
-
-package org.onap.dcae.vestest;
-
-import org.junit.runner.JUnitCore;
-import org.junit.runner.Result;
-import org.junit.runner.notification.Failure;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class VesCollectorJunitTestRunner {
-
- private static final Logger log = LoggerFactory.getLogger(VesCollectorJunitTestRunner.class);
-
- /**
- * Runner for test case.
- *
- * @param args command line arguments
- */
- public static void main(String[] args) {
-
- log.info("STARTING TEST SUITE EXECUTION.....");
-
- Result result = JUnitCore.runClasses(VesCollectorJunitTest.class);
-
- for (Failure failure : result.getFailures()) {
- log.info(failure.toString());
- }
-
- log.info("Execution Final result : " + result.wasSuccessful());
- }
-}
diff --git a/src/test/resources/controller-config.json b/src/test/resources/controller-config.json
deleted file mode 100644
index c71f434d..00000000
--- a/src/test/resources/controller-config.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "services_calls": {},
- "collector.schema.checkflag": 1,
- "collector.inputQueue.maxPending": 8096,
- "collector.keystore.alias": "dynamically generated",
- "collector.schema.file": "{\"v1\":\"./etc/CommonEventFormat_27.2.json\",\"v2\":\"./etc/CommonEventFormat_27.2.json\",\"v3\":\"./etc/CommonEventFormat_27.2.json\",\"v4\":\"./etc/CommonEventFormat_27.2.json\",\"v5\":\"./etc/CommonEventFormat_28.4.json\"}",
- "header.authlist": "userid1,base64encodepwd1|userid2,base64encodepwd2",
- "streams_subscribes": {},
- "tomcat.maxthreads": "200",
- "collector.service.secure.port": 8443,
- "collector.dmaap.streamid": "fault=ves_fault|syslog=ves_syslog|heartbeat=ves_heartbeat|measurementsForVfScaling=ves_measurement|mobileFlow=ves_mobileflow|other=ves_other|stateChange=ves_statechange|thresholdCrossingAlert=ves_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling",
- "event.transform.flag": 0,
- "collector.keystore.file.location": "/opt/app/dcae-certificate/keystore.jks",
- "collector.keystore.passwordfile": "/opt/app/dcae-certificate/.password",
- "header.authflag": 0,
- "collector.service.port": 8080
-}
diff --git a/src/test/resources/controller-config_dmaap_ip.json b/src/test/resources/controller-config_dmaap_ip.json
new file mode 100644
index 00000000..8979a614
--- /dev/null
+++ b/src/test/resources/controller-config_dmaap_ip.json
@@ -0,0 +1,239 @@
+{
+ "header.authflag": 1,
+ "collector.inputQueue.maxPending": 8096,
+ "collector.keystore.alias": "dynamically generated",
+ "collector.schema.checkflag": 1,
+ "collector.keystore.file.location": "/opt/app/dcae-certificate/keystore.jks",
+ "tomcat.maxthreads": "200",
+ "collector.keystore.passwordfile": "/opt/app/dcae-certificate/.password",
+ "collector.service.secure.port": 8443,
+ "collector.schema.file": "{\"v1\":\"./etc/CommonEventFormat_27.2.json\",\"v2\":\"./etc/CommonEventFormat_27.2.json\",\"v3\":\"./etc/CommonEventFormat_27.2.json\",\"v4\":\"./etc/CommonEventFormat_27.2.json\",\"v5\":\"./etc/CommonEventFormat_28.4.json\"}",
+ "collector.dmaap.streamid": "fault=ves-fault,ves-fault-secondary|syslog=ves-syslog,ves-syslog-secondary|heartbeat=ves-heartbeat,ves-heartbeat-secondary|measurementsForVfScaling=ves-measurement,ves-measurement-secondary|mobileFlow=ves-mobileflow,ves-mobileflow-secondary|other=ves-other,ves-other-secondary|stateChange=ves-statechange,ves-statechange-secondary|thresholdCrossingAlert=ves-thresholdCrossingAlert,ves-thresholdCrossingAlert-secondary|voiceQuality=ves-voicequality,ves-voicequality-secondary|sipSignaling=ves-sipsignaling,ves-sipsignaling-secondary",
+ "streams_subscribes": {},
+ "collector.service.port": -1,
+ "services_calls": {},
+ "streams_publishes": {
+ "ves-other": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-fault": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-syslog": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-other-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-syslog-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-thresholdCrossingAlert-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-voicequality": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-sipsignaling-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-heartbeat": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-mobileflow-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-heartbeat-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-measurement-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-measurement": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-sipsignaling": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-statechange-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-voicequality-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-fault-secondary": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-statechange": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-mobileflow": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ },
+ "ves-thresholdCrossingAlert": {
+ "aaf_username": null,
+ "type": "message_router",
+ "aaf_password": null,
+ "dmaap_info": {
+ "client_id": null,
+ "location": "mtl5",
+ "client_role": null,
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ }
+ },
+ "event.transform.flag": 1,
+ "header.authlist": "sample1,c2FtcGxlMQ==|userid1,base64encodepwd1|userid2,base64encodepwd2"
+}
diff --git a/src/test/resources/controller-config_singleline_ip.json b/src/test/resources/controller-config_singleline_ip.json
new file mode 100644
index 00000000..220e3f1b
--- /dev/null
+++ b/src/test/resources/controller-config_singleline_ip.json
@@ -0,0 +1 @@
+{"header.authflag": "1", "collector.schema.file": "{\"v1\": \"./etc/CommonEventFormat_27.2.json\", \"v2\": \"./etc/CommonEventFormat_27.2.json\", \"v3\": \"./etc/CommonEventFormat_27.2.json\", \"v4\": \"./etc/CommonEventFormat_27.2.json\", \"v5\": \"./etc/CommonEventFormat_28.4.json\"}", "collector.keystore.passwordfile": "/opt/app/dcae-certificate/.password", "tomcat.maxthreads": "200", "collector.dmaap.streamid": "fault=ves-fault|syslog=ves-syslog|heartbeat=ves-heartbeat|measurementsForVfScaling=ves-measurement|mobileFlow=ves-mobileflow|other=ves-other|stateChange=ves-statechange|thresholdCrossingAlert=ves-thresholdCrossingAlert|voiceQuality=ves-voicequality|sipSignaling=ves-sipsignaling", "streams_subscribes": {}, "collector.inputQueue.maxPending": "8096", "collector.keystore.alias": "dynamically generated", "streams_publishes": {"ves-mobileflow": {"type": "message_router", "dmaap_info": {"client_id": "1517590629043", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-MOBILEFLOW-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-measurement": {"type": "message_router", "dmaap_info": {"client_id": "1517590433916", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-ENC-MEASUREMENT-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-voicequality": {"type": "message_router", "dmaap_info": {"client_id": "1517590778397", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-VES-VOICEQUALITY-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-thresholdCrossingAlert": {"type": "message_router", "dmaap_info": {"client_id": "1517590728150", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-TCA-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-fault": {"type": "message_router", "dmaap_info": {"client_id": "1517590384670", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-FAULT-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-heartbeat": {"type": "message_router", "dmaap_info": {"client_id": "1517590530041", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-HEARTBEAT-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-sipsignaling": {"type": "message_router", "dmaap_info": {"client_id": "1517590828736", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-VES-SIPSIGNALING-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-syslog": {"type": "message_router", "dmaap_info": {"client_id": "1517590482019", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-SYSLOG-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-other": {"type": "message_router", "dmaap_info": {"client_id": "1517590581045", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-OTHER-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}, "ves-statechange": {"type": "message_router", "dmaap_info": {"client_id": "1517590677649", "client_role": "com.att.secCollector.member", "location": "rdm5bdcc2", "topic_url": "https://DMAAPHOST:3905/events/com.att.dcae.dmaap.FTL.24256-SEC-STATECHANGE-OUTPUT-v1"}, "aaf_username": "userid@namespace", "aaf_password": "authpwd"}}, "collector.schema.checkflag": "1", "services_calls": {}, "event.transform.flag": "1", "collector.keystore.file.location": "/opt/app/dcae-certificate/keystore.jks", "header.authlist": "sample1,c2FtcGxlMQ==|userid1,base64encodepwd1|userid2,base64encodepwd2", "collector.service.secure.port": "8443", "collector.service.port": "-1"} \ No newline at end of file
diff --git a/src/test/resources/testDmaapConfig.json b/src/test/resources/testDmaapConfig_ip.json
index 247db789..247db789 100644
--- a/src/test/resources/testDmaapConfig.json
+++ b/src/test/resources/testDmaapConfig_ip.json
diff --git a/src/test/resources/testFullDmaapConfig_gen2.json b/src/test/resources/testFullDmaapConfig_gen2.json
new file mode 100644
index 00000000..68804663
--- /dev/null
+++ b/src/test/resources/testFullDmaapConfig_gen2.json
@@ -0,0 +1,24 @@
+{
+ "ves-fault-secondary": {
+ "aaf_username": "sampleUsername",
+ "dmaap_info": {
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV",
+ "location": "mtl5",
+ "client_id": null,
+ "client_role": null
+ },
+ "type": "message_router",
+ "aaf_password": "SamplePasswd"
+ },
+ "ves-thresholdCrossingAlert-secondary": {
+ "aaf_username": "sampleUsername2",
+ "dmaap_info": {
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV",
+ "location": "mtl5",
+ "client_id": null,
+ "client_role": null
+ },
+ "type": "message_router",
+ "aaf_password": "SamplePassWD2"
+ }
+} \ No newline at end of file
diff --git a/src/test/resources/testParseDMaaPCredentialsGen2.json b/src/test/resources/testParseDMaaPCredentialsGen2.json
new file mode 100644
index 00000000..953cb6e8
--- /dev/null
+++ b/src/test/resources/testParseDMaaPCredentialsGen2.json
@@ -0,0 +1,21 @@
+{
+ "auth-credentials-null": {
+ "aaf_username": null,
+ "dmaap_info": {
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV",
+ },
+ "aaf_password": null
+ },
+ "auth-credentials-present": {
+ "aaf_username": "sampleUser",
+ "dmaap_info": {
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV",
+ },
+ "aaf_password": "samplePassword"
+ },
+ "auth-credentials-missing": {
+ "dmaap_info": {
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV",
+ }
+ }
+} \ No newline at end of file
diff --git a/src/test/resources/testParseDMaaPCredentialsLegacy.json b/src/test/resources/testParseDMaaPCredentialsLegacy.json
new file mode 100644
index 00000000..ca59c7e7
--- /dev/null
+++ b/src/test/resources/testParseDMaaPCredentialsLegacy.json
@@ -0,0 +1,26 @@
+{
+ "channels": [
+ {
+ "name": "auth-credentials-null",
+ "cambria.url": "127.0.0.1:3904",
+ "cambria.hosts": "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com",
+ "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV",
+ "basicAuthPassword": null,
+ "basicAuthUsername": null,
+ },
+ {
+ "name": "auth-credentials-present",
+ "cambria.url": "127.0.0.1:3904",
+ "cambria.hosts": "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com",
+ "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV",
+ "basicAuthPassword": "samplePassword",
+ "basicAuthUsername": "sampleUser",
+ },
+ {
+ "name": "auth-credentials-missing",
+ "cambria.url": "127.0.0.1:3904",
+ "cambria.hosts": "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com",
+ "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV",
+ }
+ ]
+} \ No newline at end of file
diff --git a/src/test/resources/testParseDMaaPGen2.json b/src/test/resources/testParseDMaaPGen2.json
new file mode 100644
index 00000000..5b4fe6a6
--- /dev/null
+++ b/src/test/resources/testParseDMaaPGen2.json
@@ -0,0 +1,12 @@
+{
+ "event-segments-with-port": {
+ "dmaap_info": {
+ "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV",
+ }
+ },
+ "other-segments-without-ports": {
+ "dmaap_info": {
+ "topic_url": "http://UEBHOST:3904/somethingHere/DCAE-SE-COLLECTOR-EVENTS-DEV",
+ }
+ }
+} \ No newline at end of file
diff --git a/src/test/resources/testParseDMaaPLegacy.json b/src/test/resources/testParseDMaaPLegacy.json
new file mode 100644
index 00000000..9661e30c
--- /dev/null
+++ b/src/test/resources/testParseDMaaPLegacy.json
@@ -0,0 +1,21 @@
+{
+ "channels": [
+ {
+ "name": "url-precedes-hosts",
+ "cambria.url": "127.0.0.1:3904",
+ "cambria.hosts": "h1.att.com,h2.att.com",
+ "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV",
+ },
+ {
+ "name": "url-key-missing",
+ "cambria.hosts": "h1.att.com,h2.att.com",
+ "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV",
+ },
+ {
+ "name": "url-is-null",
+ "cambria.url": null,
+ "cambria.hosts": "h1.att.com,h2.att.com",
+ "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV"
+ }
+ ]
+} \ No newline at end of file
diff --git a/src/test/resources/test_anynode_class.json b/src/test/resources/test_anynode_class.json
new file mode 100644
index 00000000..0d349451
--- /dev/null
+++ b/src/test/resources/test_anynode_class.json
@@ -0,0 +1,9 @@
+{
+ "channels": [{
+ "one": "number1", "two": "number2", "three": "number3"}],
+ "sampleStrList": ["1", "2", "3", "4", "5"],
+ "sampleNestedObject": {"a": 1, "b": 2},
+ "sampleInt": 1,
+ "sampleString": "str",
+ "sampleNull": null
+}
diff --git a/src/test/resources/test_collector_ip_op.properties b/src/test/resources/test_collector_ip_op.properties
new file mode 100644
index 00000000..f29a2ba6
--- /dev/null
+++ b/src/test/resources/test_collector_ip_op.properties
@@ -0,0 +1,16 @@
+collector.service.port=-1
+collector.service.secure.port=8443
+collector.keystore.file.location=/opt/app/dcae-certificate/keystore.jks
+collector.keystore.passwordfile=/opt/app/dcae-certificate/.password
+collector.keystore.alias=dynamically generated
+collector.schema.checkflag=1
+collector.schema.file={\"v1\":\"./etc/CommonEventFormat_27.2.json\",\"v2\":\"./etc/CommonEventFormat_27.2.json\",\"v3\":\"./etc/CommonEventFormat_27.2.json\",\"v4\":\"./etc/CommonEventFormat_27.2.json\",\"v5\":\"./etc/CommonEventFormat_28.4.json\"}
+collector.dmaap.streamid=fault=ves-fault,ves-fault-secondary|syslog=ves-syslog,ves-syslog-secondary|heartbeat=ves-heartbeat,ves-heartbeat-secondary|measurementsForVfScaling=ves-measurement,ves-measurement-secondary|mobileFlow=ves-mobileflow,ves-mobileflow-secondary|other=ves-other,ves-other-secondary|stateChange=ves-statechange,ves-statechange-secondary|thresholdCrossingAlert=ves-thresholdCrossingAlert,ves-thresholdCrossingAlert-secondary|voiceQuality=ves-voicequality,ves-voicequality-secondary|sipSignaling=ves-sipsignaling,ves-sipsignaling-secondary
+collector.dmaapfile=./etc/DmaapConfig.json
+header.authflag=1
+header.authlist=sample1,c2FtcGxlMQ==|userid1,base64encodepwd1|userid2,base64encodepwd2
+event.transform.flag=1
+collector.inputQueue.maxPending = 8096
+streams_subscribes = {}
+services_calls = {}
+tomcat.maxthreads = 200
diff --git a/src/test/resources/testcollector.properties b/src/test/resources/testcollector.properties
index 6b166b04..7de53d61 100644
--- a/src/test/resources/testcollector.properties
+++ b/src/test/resources/testcollector.properties
@@ -1,75 +1,14 @@
-###############################################################################
-##
-## Collector Server config
-##
-## - Default values are shown as commented settings.
-##
-###############################################################################
-##
-## HTTP(S) service
-##
-## Normally:
-##
-## - 8080 is http service
-## - https is disabled by default (-1)
-##
-## - At this time, the server always binds to 0.0.0.0
-##
-## The default port when header.authflag is disabled (0)
-collector.service.port=9999
-
-## The secure port is required if header.authflag is set to 1 (true)
-## Authentication is only supported via secure port
-## When enabled - require valid keystore defined
-collector.service.secure.port=8443
-
-## The keystore must be setup per installation when secure port is configured
-collector.keystore.file.location=../etc/keystore
-collector.keystore.passwordfile=./etc/passwordfile
-collector.keystore.alias=tomcat
-
-
-###############################################################################
-## Processing
-##
-## If there's a problem that prevents the collector from processing alarms,
-## it's normally better to apply back pressure to the caller than to try to
-## buffer beyond a reasonable size limit. With a limit, the server won't crash
-## due to being out of memory, and the caller will get a 5xx reply saying the
-## server is in trouble.
-collector.inputQueue.maxPending=8096
-
-## Schema Validation checkflag
-## default no validation checkflag (-1)
-## If enabled (1) - schemafile location must be specified
-collector.schema.checkflag=1
-collector.schema.file={\"v1\":\"./etc/CommonEventFormat_27.2.json\",\"v2\":\"./etc/CommonEventFormat_27.2.json\",\"v3\":\"./etc/CommonEventFormat_27.2.json\",\"v4\":\"./etc/CommonEventFormat_27.2.json\",\"v5\":\"./etc/CommonEventFormat_28.4.json\"}
-
-## List all streamid per domain to be supported. The streamid should match to channel name on dmaapfile
-collector.dmaap.streamid=fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling
-collector.dmaapfile=./etc/DmaapConfig.json
-
-## Custom ExceptionConfiguration
-exceptionConfig=./etc/ExceptionConfig.json
-
-## authflag control authentication by the collector
-## If enabled (1) - then authlist has to be defined
-## When authflag is enabled, only secure port will be supported
-## To disable enter 0
-header.authflag=1
-## Combination of userid,base64 encoded pwd list to be supported
-## userid and pwd comma separated; pipe delimitation between each pair
-header.authlist=secureid,IWRjYWVSb2FkbTEyMyEt|sample1,c2FtcGxlMQ==|vdnsagg,dmRuc2FnZw==
-
-## Event transformation Flag - when set expects configurable transformation
-## defined under ./etc/eventTransform.json
-## Enabled by default; to disable set to 0
-event.transform.flag=1
-
-###############################################################################
-##
-## Tomcat control
-##
-#tomcat.maxthreads=(tomcat default, which is usually 200)
-
-
+collector.service.port=9999
+collector.service.secure.port=8443
+collector.keystore.file.location=../etc/keystore
+collector.keystore.passwordfile=./etc/passwordfile
+collector.keystore.alias=tomcat
+collector.schema.checkflag=1
+collector.schema.file={\"v1\":\"./etc/CommonEventFormat_27.2.json\",\"v2\":\"./etc/CommonEventFormat_27.2.json\",\"v3\":\"./etc/CommonEventFormat_27.2.json\",\"v4\":\"./etc/CommonEventFormat_27.2.json\",\"v5\":\"./etc/CommonEventFormat_28.4.json\"}
+collector.dmaap.streamid=fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling
+collector.dmaapfile=./etc/DmaapConfig.json
+header.authflag=1
+header.authlist=secureid,IWRjYWVSb2FkbTEyMyEt|sample1,c2FtcGxlMQ==
+event.transform.flag=1
+
+