From d661dbcf431f0f02ecf98f748e3516ba0ab23dff Mon Sep 17 00:00:00 2001 From: elinuxhenrik Date: Fri, 17 Aug 2018 12:34:58 +0200 Subject: Add seed code. First version based on PRH micro service. Change-Id: Iea1673a8a1961006b1ea98ef245e213e3652eb82 Issue-ID: DCAEGEN2-638 Signed-off-by: elinuxhenrik --- .../onap/dcaegen2/collectors/datafile/MainApp.java | 52 ++++ .../datafile/configuration/AppConfig.java | 212 ++++++++++++++++ .../collectors/datafile/configuration/Config.java | 39 +++ .../datafile/configuration/DatafileAppConfig.java | 143 +++++++++++ .../datafile/configuration/SchedulerConfig.java | 88 +++++++ .../datafile/configuration/SwaggerConfig.java | 82 +++++++ .../datafile/configuration/TomcatHttpConfig.java | 55 +++++ .../datafile/controllers/HeartbeatController.java | 65 +++++ .../datafile/controllers/ScheduleController.java | 75 ++++++ .../datafile/exceptions/AaiNotFoundException.java | 31 +++ .../datafile/exceptions/DatafileTaskException.java | 35 +++ .../exceptions/DmaapEmptyResponseException.java | 31 +++ .../exceptions/DmaapNotFoundException.java | 31 +++ .../datafile/service/DmaapConsumerJsonParser.java | 130 ++++++++++ .../collectors/datafile/tasks/AaiConsumerTask.java | 36 +++ .../datafile/tasks/AaiConsumerTaskImpl.java | 78 ++++++ .../collectors/datafile/tasks/AaiProducerTask.java | 49 ++++ .../datafile/tasks/AaiProducerTaskImpl.java | 89 +++++++ .../datafile/tasks/DmaapConsumerTask.java | 49 ++++ .../datafile/tasks/DmaapConsumerTaskImpl.java | 86 +++++++ .../datafile/tasks/DmaapPublisherTask.java | 47 ++++ .../datafile/tasks/DmaapPublisherTaskImpl.java | 78 ++++++ .../collectors/datafile/tasks/ScheduledTasks.java | 113 +++++++++ .../src/main/resources/application.properties | 14 ++ .../src/main/resources/keystore.jks | Bin 0 -> 2643 bytes .../src/main/resources/keystore.jks.old | Bin 0 -> 2272 bytes .../src/main/resources/logback-spring.xml | 47 ++++ .../src/main/resources/scheduled-context.xml | 16 ++ .../configuration/DatafileAppConfigTest.java | 212 ++++++++++++++++ .../integration/ScheduledXmlContextITest.java | 66 +++++ .../datafile/integration/ServiceMockProvider.java | 45 ++++ .../junit5/mockito/MockitoExtension.java | 83 +++++++ .../service/DmaapConsumerJsonParserTest.java | 273 +++++++++++++++++++++ .../datafile/tasks/AaiConsumerTaskImplTest.java | 149 +++++++++++ .../datafile/tasks/AaiConsumerTaskSpy.java | 50 ++++ .../datafile/tasks/AaiProducerTaskImplTest.java | 133 ++++++++++ .../datafile/tasks/AaiPublisherTaskSpy.java | 58 +++++ .../datafile/tasks/DmaapConsumerTaskImplTest.java | 136 ++++++++++ .../datafile/tasks/DmaapConsumerTaskSpy.java | 59 +++++ .../datafile/tasks/DmaapProducerTaskSpy.java | 59 +++++ .../datafile/tasks/DmaapPublisherTaskImplTest.java | 124 ++++++++++ .../datafile/tasks/ScheduleControllerSpy.java | 54 ++++ .../src/test/resources/datafile_endpoints.json | 47 ++++ .../src/test/resources/logback-test.xml | 33 +++ 44 files changed, 3352 insertions(+) create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/MainApp.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/AppConfig.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/Config.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/DatafileAppConfig.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/SchedulerConfig.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/SwaggerConfig.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/TomcatHttpConfig.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/controllers/HeartbeatController.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/controllers/ScheduleController.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/AaiNotFoundException.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DatafileTaskException.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DmaapEmptyResponseException.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DmaapNotFoundException.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/service/DmaapConsumerJsonParser.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTask.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskImpl.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTask.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTaskImpl.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTask.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskImpl.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTask.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTaskImpl.java create mode 100644 datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduledTasks.java create mode 100644 datafile-app-server/src/main/resources/application.properties create mode 100644 datafile-app-server/src/main/resources/keystore.jks create mode 100644 datafile-app-server/src/main/resources/keystore.jks.old create mode 100644 datafile-app-server/src/main/resources/logback-spring.xml create mode 100644 datafile-app-server/src/main/resources/scheduled-context.xml create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/configuration/DatafileAppConfigTest.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/ScheduledXmlContextITest.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/ServiceMockProvider.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/junit5/mockito/MockitoExtension.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/service/DmaapConsumerJsonParserTest.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskImplTest.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskSpy.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTaskImplTest.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiPublisherTaskSpy.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskImplTest.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskSpy.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapProducerTaskSpy.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTaskImplTest.java create mode 100644 datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduleControllerSpy.java create mode 100644 datafile-app-server/src/test/resources/datafile_endpoints.json create mode 100644 datafile-app-server/src/test/resources/logback-test.xml (limited to 'datafile-app-server/src') diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/MainApp.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/MainApp.java new file mode 100644 index 00000000..63fbccb0 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/MainApp.java @@ -0,0 +1,52 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; + +/** + * @author Przemysław Wąsala on 3/23/18 + */ +@SpringBootApplication +@Configuration +@ComponentScan +@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) +@EnableScheduling +public class MainApp { + + public static void main(String[] args) { + SpringApplication.run(MainApp.class, args); + } + + @Bean + TaskScheduler taskScheduler() { + return new ConcurrentTaskScheduler(); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/AppConfig.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/AppConfig.java new file mode 100644 index 00000000..1fd50c94 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/AppConfig.java @@ -0,0 +1,212 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.configuration; + +import java.util.Optional; + +import java.util.function.Predicate; + +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.DmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.ImmutableAaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.ImmutableDmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.ImmutableDmaapPublisherConfiguration; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; + + +/** + * @author Przemysław Wąsala on 4/9/18 + */ + +@Component +@Configuration +public class AppConfig extends DatafileAppConfig { + + private static Predicate isEmpty = String::isEmpty; + @Value("${dmaap.dmaapConsumerConfiguration.dmaapHostName:}") + public String consumerDmaapHostName; + + @Value("${dmaap.dmaapConsumerConfiguration.dmaapPortNumber:}") + public Integer consumerDmaapPortNumber; + + @Value("${dmaap.dmaapConsumerConfiguration.dmaapTopicName:}") + public String consumerDmaapTopicName; + + @Value("${dmaap.dmaapConsumerConfiguration.dmaapProtocol:}") + public String consumerDmaapProtocol; + + @Value("${dmaap.dmaapConsumerConfiguration.dmaapUserName:}") + public String consumerDmaapUserName; + + @Value("${dmaap.dmaapConsumerConfiguration.dmaapUserPassword:}") + public String consumerDmaapUserPassword; + + @Value("${dmaap.dmaapConsumerConfiguration.dmaapContentType:}") + public String consumerDmaapContentType; + + @Value("${dmaap.dmaapConsumerConfiguration.consumerId:}") + public String consumerId; + + @Value("${dmaap.dmaapConsumerConfiguration.consumerGroup:}") + public String consumerGroup; + + @Value("${dmaap.dmaapConsumerConfiguration.timeoutMs:}") + public Integer consumerTimeoutMs; + + @Value("${dmaap.dmaapConsumerConfiguration.message-limit:}") + public Integer consumerMessageLimit; + + @Value("${dmaap.dmaapProducerConfiguration.dmaapHostName:}") + public String producerDmaapHostName; + + @Value("${dmaap.dmaapProducerConfiguration.dmaapPortNumber:}") + public Integer producerDmaapPortNumber; + + @Value("${dmaap.dmaapProducerConfiguration.dmaapTopicName:}") + public String producerDmaapTopicName; + + @Value("${dmaap.dmaapProducerConfiguration.dmaapProtocol:}") + public String producerDmaapProtocol; + + @Value("${dmaap.dmaapProducerConfiguration.dmaapUserName:}") + public String producerDmaapUserName; + + @Value("${dmaap.dmaapProducerConfiguration.dmaapUserPassword:}") + public String producerDmaapUserPassword; + + @Value("${dmaap.dmaapProducerConfiguration.dmaapContentType:}") + public String producerDmaapContentType; + + @Value("${aai.aaiClientConfiguration.aaiHost:}") + public String aaiHost; + + @Value("${aai.aaiClientConfiguration.aaiHostPortNumber:}") + public Integer aaiPort; + + @Value("${aai.aaiClientConfiguration.aaiProtocol:}") + public String aaiProtocol; + + @Value("${aai.aaiClientConfiguration.aaiUserName:}") + public String aaiUserName; + + @Value("${aai.aaiClientConfiguration.aaiUserPassword:}") + public String aaiUserPassword; + + @Value("${aai.aaiClientConfiguration.aaiIgnoreSslCertificateErrors:}") + public Boolean aaiIgnoreSslCertificateErrors; + + @Value("${aai.aaiClientConfiguration.aaiBasePath:}") + public String aaiBasePath; + + @Value("${aai.aaiClientConfiguration.aaiPnfPath:}") + public String aaiPnfPath; + + @Override + public DmaapConsumerConfiguration getDmaapConsumerConfiguration() { + return new ImmutableDmaapConsumerConfiguration.Builder() + .dmaapUserPassword( + Optional.ofNullable(consumerDmaapUserPassword).filter(isEmpty.negate()) + .orElse(dmaapConsumerConfiguration.dmaapUserPassword())) + .dmaapUserName( + Optional.ofNullable(consumerDmaapUserName).filter(isEmpty.negate()) + .orElse(dmaapConsumerConfiguration.dmaapUserName())) + .dmaapHostName( + Optional.ofNullable(consumerDmaapHostName).filter(isEmpty.negate()) + .orElse(dmaapConsumerConfiguration.dmaapHostName())) + .dmaapPortNumber( + Optional.ofNullable(consumerDmaapPortNumber).filter(p -> !p.toString().isEmpty()) + .orElse(dmaapConsumerConfiguration.dmaapPortNumber())) + .dmaapProtocol( + Optional.ofNullable(consumerDmaapProtocol).filter(isEmpty.negate()) + .orElse(dmaapConsumerConfiguration.dmaapProtocol())) + .dmaapContentType( + Optional.ofNullable(consumerDmaapContentType).filter(isEmpty.negate()) + .orElse(dmaapConsumerConfiguration.dmaapContentType())) + .dmaapTopicName( + Optional.ofNullable(consumerDmaapTopicName).filter(isEmpty.negate()) + .orElse(dmaapConsumerConfiguration.dmaapTopicName())) + .messageLimit( + Optional.ofNullable(consumerMessageLimit).filter(p -> !p.toString().isEmpty()) + .orElse(dmaapConsumerConfiguration.messageLimit())) + .timeoutMs(Optional.ofNullable(consumerTimeoutMs).filter(p -> !p.toString().isEmpty()) + .orElse(dmaapConsumerConfiguration.timeoutMs())) + .consumerGroup(Optional.ofNullable(consumerGroup).filter(isEmpty.negate()) + .orElse(dmaapConsumerConfiguration.consumerGroup())) + .consumerId(Optional.ofNullable(consumerId).filter(isEmpty.negate()) + .orElse(dmaapConsumerConfiguration.consumerId())) + .build(); + } + + @Override + public AaiClientConfiguration getAaiClientConfiguration() { + return new ImmutableAaiClientConfiguration.Builder() + .aaiHost(Optional.ofNullable(aaiHost).filter(isEmpty.negate()).orElse(aaiClientConfiguration.aaiHost())) + .aaiPort( + Optional.ofNullable(aaiPort).filter(p -> !p.toString().isEmpty()) + .orElse(aaiClientConfiguration.aaiPort())) + .aaiIgnoreSslCertificateErrors( + Optional.ofNullable(aaiIgnoreSslCertificateErrors).filter(p -> !p.toString().isEmpty()) + .orElse(aaiClientConfiguration.aaiIgnoreSslCertificateErrors())) + .aaiProtocol( + Optional.ofNullable(aaiProtocol).filter(isEmpty.negate()).orElse(aaiClientConfiguration.aaiProtocol())) + .aaiUserName( + Optional.ofNullable(aaiUserName).filter(isEmpty.negate()).orElse(aaiClientConfiguration.aaiUserName())) + .aaiUserPassword(Optional.ofNullable(aaiUserPassword).filter(isEmpty.negate()) + .orElse(aaiClientConfiguration.aaiUserPassword())) + .aaiBasePath(Optional.ofNullable(aaiBasePath).filter(isEmpty.negate()) + .orElse(aaiClientConfiguration.aaiBasePath())) + .aaiPnfPath( + Optional.ofNullable(aaiPnfPath).filter(isEmpty.negate()).orElse(aaiClientConfiguration.aaiPnfPath())) + .aaiHeaders(aaiClientConfiguration.aaiHeaders()) + .build(); + } + + @Override + public DmaapPublisherConfiguration getDmaapPublisherConfiguration() { + return new ImmutableDmaapPublisherConfiguration.Builder() + .dmaapContentType( + Optional.ofNullable(producerDmaapContentType).filter(isEmpty.negate()) + .orElse(dmaapPublisherConfiguration.dmaapContentType())) + .dmaapHostName( + Optional.ofNullable(producerDmaapHostName).filter(isEmpty.negate()) + .orElse(dmaapPublisherConfiguration.dmaapHostName())) + .dmaapPortNumber( + Optional.ofNullable(producerDmaapPortNumber).filter(p -> !p.toString().isEmpty()) + .orElse(dmaapPublisherConfiguration.dmaapPortNumber())) + .dmaapProtocol( + Optional.ofNullable(producerDmaapProtocol).filter(isEmpty.negate()) + .orElse(dmaapPublisherConfiguration.dmaapProtocol())) + .dmaapTopicName( + Optional.ofNullable(producerDmaapTopicName).filter(isEmpty.negate()) + .orElse(dmaapPublisherConfiguration.dmaapTopicName())) + .dmaapUserName( + Optional.ofNullable(producerDmaapUserName).filter(isEmpty.negate()) + .orElse(dmaapPublisherConfiguration.dmaapUserName())) + .dmaapUserPassword( + Optional.ofNullable(producerDmaapUserPassword).filter(isEmpty.negate()) + .orElse(dmaapPublisherConfiguration.dmaapUserPassword())) + .build(); + } + +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/Config.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/Config.java new file mode 100644 index 00000000..5c6f1512 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/Config.java @@ -0,0 +1,39 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.configuration; + +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.DmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration; + +/** + * @author Przemysław Wąsala on 4/25/18 + */ +public interface Config { + + DmaapConsumerConfiguration getDmaapConsumerConfiguration(); + + AaiClientConfiguration getAaiClientConfiguration(); + + DmaapPublisherConfiguration getDmaapPublisherConfiguration(); + + void initFileStreamReader(); +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/DatafileAppConfig.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/DatafileAppConfig.java new file mode 100644 index 00000000..169bf8ed --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/DatafileAppConfig.java @@ -0,0 +1,143 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.configuration; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.google.gson.TypeAdapterFactory; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import java.nio.charset.StandardCharsets; +import java.util.ServiceLoader; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.DmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * @author Przemysław Wąsala on 4/9/18 + */ +@Configuration +@EnableConfigurationProperties +@ConfigurationProperties("app") +public abstract class DatafileAppConfig implements Config { + + private static final String CONFIG = "configs"; + private static final String AAI = "aai"; + private static final String DMAAP = "dmaap"; + private static final String AAI_CONFIG = "aaiClientConfiguration"; + private static final String DMAAP_PRODUCER = "dmaapProducerConfiguration"; + private static final String DMAAP_CONSUMER = "dmaapConsumerConfiguration"; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + AaiClientConfiguration aaiClientConfiguration; + + DmaapConsumerConfiguration dmaapConsumerConfiguration; + + DmaapPublisherConfiguration dmaapPublisherConfiguration; + + @NotEmpty + private String filepath; + + + @Override + public DmaapConsumerConfiguration getDmaapConsumerConfiguration() { + return dmaapConsumerConfiguration; + } + + @Override + public AaiClientConfiguration getAaiClientConfiguration() { + return aaiClientConfiguration; + } + + @Override + public DmaapPublisherConfiguration getDmaapPublisherConfiguration() { + return dmaapPublisherConfiguration; + } + + @Override + public void initFileStreamReader() { + + GsonBuilder gsonBuilder = new GsonBuilder(); + ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory); + JsonParser parser = new JsonParser(); + JsonObject jsonObject; + try (InputStream inputStream = getInputStream(filepath)) { + JsonElement rootElement = getJsonElement(parser, inputStream); + if (rootElement.isJsonObject()) { + jsonObject = rootElement.getAsJsonObject(); + aaiClientConfiguration = deserializeType(gsonBuilder, + jsonObject.getAsJsonObject(CONFIG).getAsJsonObject(AAI).getAsJsonObject(AAI_CONFIG), + AaiClientConfiguration.class); + + dmaapConsumerConfiguration = deserializeType(gsonBuilder, + jsonObject.getAsJsonObject(CONFIG).getAsJsonObject(DMAAP).getAsJsonObject(DMAAP_CONSUMER), + DmaapConsumerConfiguration.class); + + dmaapPublisherConfiguration = deserializeType(gsonBuilder, + jsonObject.getAsJsonObject(CONFIG).getAsJsonObject(DMAAP).getAsJsonObject(DMAAP_PRODUCER), + DmaapPublisherConfiguration.class); + } + } catch (IOException e) { + logger.warn("Problem with file loading, file: {}", filepath, e); + } catch (JsonSyntaxException e) { + logger.warn("Problem with Json deserialization", e); + } + } + + JsonElement getJsonElement(JsonParser parser, InputStream inputStream) { + return parser.parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); + } + + private T deserializeType(@NotNull GsonBuilder gsonBuilder, @NotNull JsonObject jsonObject, + @NotNull Class type) { + return gsonBuilder.create().fromJson(jsonObject, type); + } + + InputStream getInputStream(@NotNull String filepath) throws IOException { + return new BufferedInputStream(new FileInputStream(filepath)); + } + + String getFilepath() { + return this.filepath; + } + + public void setFilepath(String filepath) { + this.filepath = filepath; + } + +} \ No newline at end of file diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/SchedulerConfig.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/SchedulerConfig.java new file mode 100644 index 00000000..823fe732 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/SchedulerConfig.java @@ -0,0 +1,88 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.configuration; + +import io.swagger.annotations.ApiOperation; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ScheduledFuture; +import javax.annotation.PostConstruct; + +import org.onap.dcaegen2.collectors.datafile.tasks.ScheduledTasks; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.annotation.EnableScheduling; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 6/13/18 + */ +@Configuration +@EnableScheduling +public class SchedulerConfig extends DatafileAppConfig { + + private static final int SCHEDULING_DELAY = 2000; + private static volatile List scheduledFutureList = new ArrayList<>(); + + private final TaskScheduler taskScheduler; + private final ScheduledTasks scheduledTask; + + @Autowired + public SchedulerConfig(TaskScheduler taskScheduler, ScheduledTasks scheduledTask) { + this.taskScheduler = taskScheduler; + this.scheduledTask = scheduledTask; + } + + /** + * Function which have to stop tasks execution. + * + * @return response entity about status of cancellation operation + */ + @ApiOperation(value = "Get response on stopping task execution") + public synchronized Mono> getResponseFromCancellationOfTasks() { + scheduledFutureList.forEach(x -> x.cancel(false)); + scheduledFutureList.clear(); + return Mono.defer(() -> + Mono.just(new ResponseEntity<>("Datafile Service has already been stopped!", HttpStatus.CREATED)) + ); + } + + /** + * Function for starting scheduling Datafile workflow. + * + * @return status of operation execution: true - started, false - not started + */ + @PostConstruct + @ApiOperation(value = "Start task if possible") + public synchronized boolean tryToStartTask() { + if (scheduledFutureList.isEmpty()) { + scheduledFutureList.add(taskScheduler + .scheduleWithFixedDelay(scheduledTask::scheduleMainDatafileEventTask, SCHEDULING_DELAY)); + return true; + } else { + return false; + } + + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/SwaggerConfig.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/SwaggerConfig.java new file mode 100644 index 00000000..c45b136a --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/SwaggerConfig.java @@ -0,0 +1,82 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + + +@EnableSwagger2 +@Configuration +@Profile("prod") +public class SwaggerConfig extends WebMvcConfigurationSupport { + + private static final String PACKAGE_PATH = "org.onap.dcaegen2.collectors.datafile"; + private static final String API_TITLE = "Datafile app server"; + private static final String DESCRIPTION = "This page lists all the rest apis for Datafile app server."; + private static final String VERSION = "1.0"; + private static final String RESOURCES_PATH = "classpath:/META-INF/resources/"; + private static final String WEBJARS_PATH = RESOURCES_PATH + "webjars/"; + private static final String SWAGGER_UI = "swagger-ui.html"; + private static final String WEBJARS = "/webjars/**"; + + /** + * Swagger configuration function for hosting it next to spring http website. + * @return Docket + */ + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage(PACKAGE_PATH)) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title(API_TITLE) + .description(DESCRIPTION) + .version(VERSION) + .build(); + } + + + @Override + protected void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler(SWAGGER_UI) + .addResourceLocations(RESOURCES_PATH); + + registry.addResourceHandler(WEBJARS) + .addResourceLocations(WEBJARS_PATH); + } +} \ No newline at end of file diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/TomcatHttpConfig.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/TomcatHttpConfig.java new file mode 100644 index 00000000..b6231418 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/TomcatHttpConfig.java @@ -0,0 +1,55 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.configuration; + +import org.apache.catalina.connector.Connector; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.servlet.server.ServletWebServerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Przemysław Wąsala on 4/18/18 + */ +@Configuration +public class TomcatHttpConfig { + + /** + * Class for setting up hosting Datafile on http/https. + * + * @return ServletWebServerFactory + */ + @Bean + public ServletWebServerFactory servletContainer() { + TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); + tomcat.addAdditionalTomcatConnectors(getHttpConnector()); + return tomcat; + } + + private Connector getHttpConnector() { + Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); + connector.setScheme("http"); + connector.setPort(8100); + connector.setSecure(false); + return connector; + } + +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/controllers/HeartbeatController.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/controllers/HeartbeatController.java new file mode 100644 index 00000000..070fe591 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/controllers/HeartbeatController.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.controllers; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 4/19/18 + */ +@RestController +@Api(value = "HeartbeatController", description = "Check liveness of Datafile service") +public class HeartbeatController { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + /** + * Endpoint for checking that Datafile is alive. + * + * @return HTTP Status Code + */ + @RequestMapping(value = "heartbeat", method = RequestMethod.GET) + @ApiOperation(value = "Returns liveness of Datafile service") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Datafile sevice is living"), + @ApiResponse(code = 401, message = "You are not authorized to view the resource"), + @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"), + @ApiResponse(code = 404, message = "The resource you were trying to reach is not found") + } + ) + public Mono> heartbeat() { + logger.trace("Receiving heartbeat request"); + return Mono.defer(() -> + Mono.just(new ResponseEntity<>("alive", HttpStatus.OK)) + ); + } +} \ No newline at end of file diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/controllers/ScheduleController.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/controllers/ScheduleController.java new file mode 100644 index 00000000..f3cf354f --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/controllers/ScheduleController.java @@ -0,0 +1,75 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.controllers; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +import org.onap.dcaegen2.collectors.datafile.configuration.SchedulerConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 4/5/18 + */ +@RestController +@Api(value = "ScheduleController", description = "Schedule Controller") +public class ScheduleController { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final SchedulerConfig schedulerConfig; + + @Autowired + public ScheduleController(SchedulerConfig schedulerConfig) { + this.schedulerConfig = schedulerConfig; + } + + @RequestMapping(value = "start", method = RequestMethod.GET) + @ApiOperation(value = "Start scheduling worker request") + public Mono> startTasks() { + logger.trace("Receiving start scheduling worker request"); + return Mono.fromSupplier(schedulerConfig::tryToStartTask).map(this::createStartTaskResponse); + } + + @RequestMapping(value = "stopDatafile", method = RequestMethod.GET) + @ApiOperation(value = "Receiving stop scheduling worker request") + public Mono> stopTask() { + logger.trace("Receiving stop scheduling worker request"); + return schedulerConfig.getResponseFromCancellationOfTasks(); + } + + @ApiOperation(value = "Sends success or error response on starting task execution") + private ResponseEntity createStartTaskResponse(boolean wasScheduled) { + if (wasScheduled) { + return new ResponseEntity<>("Datafile Service has been started!", HttpStatus.CREATED); + } else { + return new ResponseEntity<>("Datafile Service is still running!", HttpStatus.NOT_ACCEPTABLE); + } + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/AaiNotFoundException.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/AaiNotFoundException.java new file mode 100644 index 00000000..a83b5bd6 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/AaiNotFoundException.java @@ -0,0 +1,31 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.exceptions; + +/** + * @author Przemysław Wąsala on 3/23/18 + */ +public class AaiNotFoundException extends DatafileTaskException { + + public AaiNotFoundException(String message) { + super(message); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DatafileTaskException.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DatafileTaskException.java new file mode 100644 index 00000000..41f77332 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DatafileTaskException.java @@ -0,0 +1,35 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.exceptions; + +/** + * @author Przemysław Wąsala on 4/13/18 + */ +public class DatafileTaskException extends Exception { + + public DatafileTaskException() { + super(); + } + + public DatafileTaskException(String message) { + super(message); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DmaapEmptyResponseException.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DmaapEmptyResponseException.java new file mode 100644 index 00000000..d9f6f873 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DmaapEmptyResponseException.java @@ -0,0 +1,31 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.exceptions; + +/** + * @author Przemysław Wąsala on 6/13/18 + */ +public class DmaapEmptyResponseException extends DatafileTaskException { + + public DmaapEmptyResponseException() { + super(); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DmaapNotFoundException.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DmaapNotFoundException.java new file mode 100644 index 00000000..ebff8ae3 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/exceptions/DmaapNotFoundException.java @@ -0,0 +1,31 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.exceptions; + +/** + * @author Przemysław Wąsala on 4/13/18 + */ +public class DmaapNotFoundException extends DatafileTaskException { + + public DmaapNotFoundException(String message) { + super(message); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/service/DmaapConsumerJsonParser.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/service/DmaapConsumerJsonParser.java new file mode 100644 index 00000000..aeaf0da1 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/service/DmaapConsumerJsonParser.java @@ -0,0 +1,130 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.service; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapEmptyResponseException; +import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapNotFoundException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel; +import org.springframework.util.StringUtils; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 5/8/18 + */ +public class DmaapConsumerJsonParser { + + private static final String EVENT = "event"; + private static final String OTHER_FIELDS = "otherFields"; + private static final String PNF_OAM_IPV_4_ADDRESS = "pnfOamIpv4Address"; + private static final String PNF_OAM_IPV_6_ADDRESS = "pnfOamIpv6Address"; + private static final String PNF_VENDOR_NAME = "pnfVendorName"; + private static final String PNF_SERIAL_NUMBER = "pnfSerialNumber"; + + /** + * Extract info from string and create @see {@link org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel}. + * + * @param monoMessage - results from DMaaP + * @return reactive DMaaPModel + */ + public Mono getJsonObject(Mono monoMessage) { + return monoMessage + .flatMap(this::getJsonParserMessage) + .flatMap(this::createJsonConsumerModel); + } + + private Mono getJsonParserMessage(String message) { + return StringUtils.isEmpty(message) ? Mono.error(new DmaapEmptyResponseException()) + : Mono.fromSupplier(() -> new JsonParser().parse(message)); + } + + private Mono createJsonConsumerModel(JsonElement jsonElement) { + return jsonElement.isJsonObject() + ? create(Mono.fromSupplier(jsonElement::getAsJsonObject)) + : getConsumerDmaapModelFromJsonArray(jsonElement); + } + + private Mono getConsumerDmaapModelFromJsonArray(JsonElement jsonElement) { + return create( + Mono.fromCallable(() -> StreamSupport.stream(jsonElement.getAsJsonArray().spliterator(), false).findFirst() + .flatMap(this::getJsonObjectFromAnArray) + .orElseThrow(DmaapEmptyResponseException::new))); + } + + public Optional getJsonObjectFromAnArray(JsonElement element) { + return Optional.of(new JsonParser().parse(element.getAsString()).getAsJsonObject()); + } + + private Mono create(Mono jsonObject) { + return jsonObject.flatMap(monoJsonP -> + !containsHeader(monoJsonP) ? Mono.error(new DmaapNotFoundException("Incorrect JsonObject - missing header")) + : transform(monoJsonP)); + } + + private Mono transform(JsonObject monoJsonP) { + monoJsonP = monoJsonP.getAsJsonObject(EVENT).getAsJsonObject(OTHER_FIELDS); + String pnfVendorName = getValueFromJson(monoJsonP, PNF_VENDOR_NAME); + String pnfSerialNumber = getValueFromJson(monoJsonP, PNF_SERIAL_NUMBER); + String pnfOamIpv4Address = getValueFromJson(monoJsonP, PNF_OAM_IPV_4_ADDRESS); + String pnfOamIpv6Address = getValueFromJson(monoJsonP, PNF_OAM_IPV_6_ADDRESS); + return + (!vendorAndSerialNotEmpty(pnfSerialNumber, pnfVendorName) || !ipPropertiesNotEmpty(pnfOamIpv4Address, + pnfOamIpv6Address)) + ? Mono.error(new DmaapNotFoundException("Incorrect json, consumerDmaapModel can not be created: " + + printMessage(pnfVendorName, pnfSerialNumber, pnfOamIpv4Address, pnfOamIpv6Address))) : + Mono.just(ImmutableConsumerDmaapModel.builder() + .pnfName(pnfVendorName.substring(0, Math.min(pnfVendorName.length(), 3)).toUpperCase() + .concat(pnfSerialNumber)).ipv4(pnfOamIpv4Address) + .ipv6(pnfOamIpv6Address).build()); + } + + private String getValueFromJson(JsonObject jsonObject, String jsonKey) { + return jsonObject.has(jsonKey) ? jsonObject.get(jsonKey).getAsString() : ""; + } + + private boolean vendorAndSerialNotEmpty(String pnfSerialNumber, String pnfVendorName) { + return (!StringUtils.isEmpty(pnfSerialNumber) && !StringUtils.isEmpty(pnfVendorName)); + } + + private boolean ipPropertiesNotEmpty(String ipv4, String ipv6) { + return (!StringUtils.isEmpty(ipv4)) || !(StringUtils.isEmpty(ipv6)); + } + + private boolean containsHeader(JsonObject jsonObject) { + return jsonObject.has(EVENT) && jsonObject.getAsJsonObject(EVENT).has(OTHER_FIELDS); + } + + private String printMessage(String pnfVendorName, String pnfSerialNumber, String pnfOamIpv4Address, + String pnfOamIpv6Address) { + return String.format("%n{" + + "\"pnfVendorName\" : \"%s\"," + + "\"pnfSerialNumber\": \"%s\"," + + "\"pnfOamIpv4Address\": \"%s\"," + + "\"pnfOamIpv6Address\": \"%s\"" + + "%n}", pnfVendorName, pnfSerialNumber, pnfOamIpv4Address, pnfOamIpv6Address); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTask.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTask.java new file mode 100644 index 00000000..8083a255 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTask.java @@ -0,0 +1,36 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import java.util.Optional; + +import org.onap.dcaegen2.collectors.datafile.exceptions.AaiNotFoundException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.AaiConsumerClient; + +public abstract class AaiConsumerTask { + + abstract Optional consume(ConsumerDmaapModel message) throws AaiNotFoundException; + + abstract AaiConsumerClient resolveClient(); + + protected abstract String execute(ConsumerDmaapModel consumerDmaapModel) throws AaiNotFoundException; +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskImpl.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskImpl.java new file mode 100644 index 00000000..d487b6b2 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskImpl.java @@ -0,0 +1,78 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import java.io.IOException; +import java.util.Optional; + +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.configuration.Config; +import org.onap.dcaegen2.collectors.datafile.exceptions.AaiNotFoundException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.AaiConsumerClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class AaiConsumerTaskImpl extends AaiConsumerTask { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final Config datafileAppConfig; + private AaiConsumerClient aaiConsumerClient; + + @Autowired + public AaiConsumerTaskImpl(AppConfig datafileAppConfig) { + this.datafileAppConfig = datafileAppConfig; + } + + @Override + Optional consume(ConsumerDmaapModel consumerDmaapModel) throws AaiNotFoundException { + logger.trace("Method called with arg {}", consumerDmaapModel); + try { + return aaiConsumerClient.getHttpResponse(consumerDmaapModel); + } catch (IOException e) { + logger.warn("Get request not successful", e); + throw new AaiNotFoundException("Get request not successful"); + } + } + + @Override + public String execute(ConsumerDmaapModel consumerDmaapModel) throws AaiNotFoundException { + consumerDmaapModel = Optional.ofNullable(consumerDmaapModel) + .orElseThrow(() -> new AaiNotFoundException("Invoked null object to AAI task")); + logger.trace("Method called with arg {}", consumerDmaapModel); + aaiConsumerClient = resolveClient(); + return consume(consumerDmaapModel).orElseThrow(() -> new AaiNotFoundException("Null response code")); + } + + protected AaiClientConfiguration resolveConfiguration() { + return datafileAppConfig.getAaiClientConfiguration(); + } + + @Override + AaiConsumerClient resolveClient() { + return Optional.ofNullable(aaiConsumerClient).orElseGet(() -> new AaiConsumerClient(resolveConfiguration())); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTask.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTask.java new file mode 100644 index 00000000..ca2d03da --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTask.java @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.exceptions.AaiNotFoundException; +import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.AaiReactiveWebClient; +import org.onap.dcaegen2.collectors.datafile.service.producer.AaiProducerReactiveHttpClient; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 4/13/18 + */ +public abstract class AaiProducerTask { + + abstract Mono publish(Mono message) throws AaiNotFoundException; + + abstract AaiProducerReactiveHttpClient resolveClient(); + + protected abstract AaiClientConfiguration resolveConfiguration(); + + protected abstract Mono execute(Mono consumerDmaapModel) + throws DatafileTaskException; + + WebClient buildWebClient() { + return new AaiReactiveWebClient().fromConfiguration(resolveConfiguration()).build(); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTaskImpl.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTaskImpl.java new file mode 100644 index 00000000..9d888aa7 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTaskImpl.java @@ -0,0 +1,89 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.configuration.Config; +import org.onap.dcaegen2.collectors.datafile.exceptions.AaiNotFoundException; +import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapNotFoundException; +import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.model.utils.HttpUtils; +import org.onap.dcaegen2.collectors.datafile.service.producer.AaiProducerReactiveHttpClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 4/13/18 + */ +@Component +public class AaiProducerTaskImpl extends + AaiProducerTask { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final Config datafileAppConfig; + private AaiProducerReactiveHttpClient aaiProducerReactiveHttpClient; + + @Autowired + public AaiProducerTaskImpl(AppConfig datafileAppConfig) { + this.datafileAppConfig = datafileAppConfig; + } + + @Override + Mono publish(Mono consumerDmaapModel) { + logger.info("Sending PNF model to AAI {}", consumerDmaapModel); + return aaiProducerReactiveHttpClient.getAaiProducerResponse(consumerDmaapModel) + .flatMap(response -> { + if (HttpUtils.isSuccessfulResponseCode(response)) { + return consumerDmaapModel; + } + return Mono + .error(new AaiNotFoundException("Incorrect response code for continuation of tasks workflow")); + }); + } + + @Override + AaiProducerReactiveHttpClient resolveClient() { + return aaiProducerReactiveHttpClient == null ? new AaiProducerReactiveHttpClient(resolveConfiguration()) + .createAaiWebClient(buildWebClient()) : aaiProducerReactiveHttpClient; + } + + @Override + protected AaiClientConfiguration resolveConfiguration() { + return datafileAppConfig.getAaiClientConfiguration(); + } + + @Override + protected Mono execute(Mono consumerDmaapModel) throws DatafileTaskException { + if (consumerDmaapModel == null) { + throw new DmaapNotFoundException("Invoked null object to DMaaP task"); + } + aaiProducerReactiveHttpClient = resolveClient(); + logger.trace("Method called with arg {}", consumerDmaapModel); + return publish(consumerDmaapModel); + + } +} \ No newline at end of file diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTask.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTask.java new file mode 100644 index 00000000..a5764704 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTask.java @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import org.onap.dcaegen2.collectors.datafile.config.DmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.DMaaPReactiveWebClient; +import org.onap.dcaegen2.collectors.datafile.service.consumer.DMaaPConsumerReactiveHttpClient; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 4/13/18 + */ +abstract class DmaapConsumerTask { + + abstract Mono consume(Mono message) throws DatafileTaskException; + + abstract DMaaPConsumerReactiveHttpClient resolveClient(); + + abstract void initConfigs(); + + protected abstract DmaapConsumerConfiguration resolveConfiguration(); + + protected abstract Mono execute(String object) throws DatafileTaskException; + + WebClient buildWebClient() { + return new DMaaPReactiveWebClient().fromConfiguration(resolveConfiguration()).build(); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskImpl.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskImpl.java new file mode 100644 index 00000000..8d45a7fd --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskImpl.java @@ -0,0 +1,86 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import org.onap.dcaegen2.collectors.datafile.config.DmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.configuration.Config; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.DmaapConsumerJsonParser; +import org.onap.dcaegen2.collectors.datafile.service.consumer.DMaaPConsumerReactiveHttpClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 3/23/18 + */ +@Component +public class DmaapConsumerTaskImpl extends DmaapConsumerTask { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Config datafileAppConfig; + private DmaapConsumerJsonParser dmaapConsumerJsonParser; + private DMaaPConsumerReactiveHttpClient dmaaPConsumerReactiveHttpClient; + + @Autowired + public DmaapConsumerTaskImpl(AppConfig datafileAppConfig) { + this.datafileAppConfig = datafileAppConfig; + this.dmaapConsumerJsonParser = new DmaapConsumerJsonParser(); + } + + DmaapConsumerTaskImpl(AppConfig datafileAppConfig, DmaapConsumerJsonParser dmaapConsumerJsonParser) { + this.datafileAppConfig = datafileAppConfig; + this.dmaapConsumerJsonParser = dmaapConsumerJsonParser; + } + + @Override + Mono consume(Mono message) { + logger.info("Consumed model from DMaaP: {}", message); + return dmaapConsumerJsonParser.getJsonObject(message); + } + + @Override + public Mono execute(String object) { + dmaaPConsumerReactiveHttpClient = resolveClient(); + logger.trace("Method called with arg {}", object); + return consume((dmaaPConsumerReactiveHttpClient.getDMaaPConsumerResponse())); + } + + @Override + void initConfigs() { + datafileAppConfig.initFileStreamReader(); + } + + @Override + protected DmaapConsumerConfiguration resolveConfiguration() { + return datafileAppConfig.getDmaapConsumerConfiguration(); + } + + @Override + DMaaPConsumerReactiveHttpClient resolveClient() { + return dmaaPConsumerReactiveHttpClient == null + ? new DMaaPConsumerReactiveHttpClient(resolveConfiguration()).createDMaaPWebClient(buildWebClient()) + : dmaaPConsumerReactiveHttpClient; + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTask.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTask.java new file mode 100644 index 00000000..467eee0b --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTask.java @@ -0,0 +1,47 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration; +import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.DMaaPReactiveWebClient; +import org.onap.dcaegen2.collectors.datafile.service.producer.DMaaPProducerReactiveHttpClient; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 3/23/18 + */ +abstract class DmaapPublisherTask { + + abstract Mono publish(Mono consumerDmaapModel) throws DatafileTaskException; + + abstract DMaaPProducerReactiveHttpClient resolveClient(); + + protected abstract DmaapPublisherConfiguration resolveConfiguration(); + + protected abstract Mono execute(Mono consumerDmaapModel) throws DatafileTaskException; + + WebClient buildWebClient() { + return new DMaaPReactiveWebClient().fromConfiguration(resolveConfiguration()).build(); + } +} diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTaskImpl.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTaskImpl.java new file mode 100644 index 00000000..4d435a4f --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTaskImpl.java @@ -0,0 +1,78 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.configuration.Config; +import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapNotFoundException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.producer.DMaaPProducerReactiveHttpClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; + +/** + * @author Przemysław Wąsala on 4/13/18 + */ +@Component +public class DmaapPublisherTaskImpl extends DmaapPublisherTask { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Config datafileAppConfig; + private DMaaPProducerReactiveHttpClient dmaapProducerReactiveHttpClient; + + @Autowired + public DmaapPublisherTaskImpl(AppConfig datafileAppConfig) { + this.datafileAppConfig = datafileAppConfig; + } + + @Override + Mono publish(Mono consumerDmaapModel) { + logger.info("Publishing on DMaaP topic {} object {}", resolveConfiguration().dmaapTopicName(), + consumerDmaapModel); + return dmaapProducerReactiveHttpClient.getDMaaPProducerResponse(consumerDmaapModel); + } + + @Override + public Mono execute(Mono consumerDmaapModel) throws DmaapNotFoundException { + if (consumerDmaapModel == null) { + throw new DmaapNotFoundException("Invoked null object to DMaaP task"); + } + dmaapProducerReactiveHttpClient = resolveClient(); + logger.trace("Method called with arg {}", consumerDmaapModel); + return publish(consumerDmaapModel); + } + + @Override + protected DmaapPublisherConfiguration resolveConfiguration() { + return datafileAppConfig.getDmaapPublisherConfiguration(); + } + + @Override + DMaaPProducerReactiveHttpClient resolveClient() { + return dmaapProducerReactiveHttpClient == null + ? new DMaaPProducerReactiveHttpClient(resolveConfiguration()).createDMaaPWebClient(buildWebClient()) + : dmaapProducerReactiveHttpClient; + } +} \ No newline at end of file diff --git a/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduledTasks.java b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduledTasks.java new file mode 100644 index 00000000..2600b563 --- /dev/null +++ b/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduledTasks.java @@ -0,0 +1,113 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import java.util.concurrent.Callable; + +import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapEmptyResponseException; +import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +/** + * @author Przemysław Wąsala on 3/23/18 + */ +@Component +public class ScheduledTasks { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final DmaapConsumerTask dmaapConsumerTask; + private final DmaapPublisherTask dmaapProducerTask; + private final AaiProducerTask aaiProducerTask; + + /** + * Constructor for tasks registration in DatafileWorkflow. + * + * @param dmaapConsumerTask - fist task + * @param dmaapPublisherTask - third task + * @param aaiPublisherTask - second task + */ + @Autowired + public ScheduledTasks(DmaapConsumerTask dmaapConsumerTask, DmaapPublisherTask dmaapPublisherTask, + AaiProducerTask aaiPublisherTask) { + this.dmaapConsumerTask = dmaapConsumerTask; + this.dmaapProducerTask = dmaapPublisherTask; + this.aaiProducerTask = aaiPublisherTask; + } + + /** + * Main function for scheduling datafileWorkflow. + */ + public void scheduleMainDatafileEventTask() { + logger.trace("Execution of tasks was registered"); + + Mono dmaapProducerResponse = Mono.fromCallable(consumeFromDMaaPMessage()) + .doOnError(DmaapEmptyResponseException.class, error -> logger.warn("Nothing to consume from DMaaP")) + .map(this::publishToAaiConfiguration) + .flatMap(this::publishToDmaapConfiguration) + .subscribeOn(Schedulers.elastic()); + + dmaapProducerResponse.subscribe(this::onSuccess, this::onError, this::onComplete); + } + + private void onComplete() { + logger.info("Datafile tasks have been completed"); + } + + private void onSuccess(String responseCode) { + logger.info("Datafile consumed tasks. HTTP Response code {}", responseCode); + } + + private void onError(Throwable throwable) { + if (!(throwable instanceof DmaapEmptyResponseException)) { + logger.warn("Chain of tasks have been aborted due to errors in Datafile workflow", throwable); + } + } + + private Callable> consumeFromDMaaPMessage() { + return () -> { + dmaapConsumerTask.initConfigs(); + return dmaapConsumerTask.execute(""); + }; + } + + private Mono publishToAaiConfiguration(Mono monoDMaaPModel) { + try { + return aaiProducerTask.execute(monoDMaaPModel); + } catch (DatafileTaskException e) { + return Mono.error(e); + } + } + + private Mono publishToDmaapConfiguration(Mono monoAaiModel) { + try { + return dmaapProducerTask.execute(monoAaiModel); + } catch (DatafileTaskException e) { + return Mono.error(e); + } + } +} diff --git a/datafile-app-server/src/main/resources/application.properties b/datafile-app-server/src/main/resources/application.properties new file mode 100644 index 00000000..205b6caa --- /dev/null +++ b/datafile-app-server/src/main/resources/application.properties @@ -0,0 +1,14 @@ +spring.profiles.active=prod +spring.main.web-application-type=none +server.port=8433 +server.ssl.key-store-type=PKCS12 +server.ssl.key-store-password=nokiapnf +server.ssl.key-store=classpath:keystore.jks +server.ssl.key-password=nokiapnf +server.ssl.key-alias=tomcat-localhost +logging.level.root=ERROR +logging.level.org.springframework=ERROR +logging.level.org.springframework.data=ERROR +logging.level.org.onap.dcaegen2.collectors.datafile=INFO +logging.file=logs/log/application.log +app.filepath=config/datafile_endpoints.json diff --git a/datafile-app-server/src/main/resources/keystore.jks b/datafile-app-server/src/main/resources/keystore.jks new file mode 100644 index 00000000..cd27cc01 Binary files /dev/null and b/datafile-app-server/src/main/resources/keystore.jks differ diff --git a/datafile-app-server/src/main/resources/keystore.jks.old b/datafile-app-server/src/main/resources/keystore.jks.old new file mode 100644 index 00000000..8a2b4f99 Binary files /dev/null and b/datafile-app-server/src/main/resources/keystore.jks.old differ diff --git a/datafile-app-server/src/main/resources/logback-spring.xml b/datafile-app-server/src/main/resources/logback-spring.xml new file mode 100644 index 00000000..925b38cc --- /dev/null +++ b/datafile-app-server/src/main/resources/logback-spring.xml @@ -0,0 +1,47 @@ + + + + + + + + + + ${FILE_LOG_PATTERN} + + ${LOG_FILE} + + ${LOG_FILE}.%d{yyyy-MM-dd}.%i.log + 50MB + 30 + 10GB + + + + + + + + + + + + ${FILE_LOG_PATTERN} + + ${LOG_FILE} + + ${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz + 50MB + 30 + 10GB + + + + + + + + \ No newline at end of file diff --git a/datafile-app-server/src/main/resources/scheduled-context.xml b/datafile-app-server/src/main/resources/scheduled-context.xml new file mode 100644 index 00000000..369d2c7b --- /dev/null +++ b/datafile-app-server/src/main/resources/scheduled-context.xml @@ -0,0 +1,16 @@ + + + + + + + + diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/configuration/DatafileAppConfigTest.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/configuration/DatafileAppConfigTest.java new file mode 100644 index 00000000..7d54b4d5 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/configuration/DatafileAppConfigTest.java @@ -0,0 +1,212 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.configuration; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.configuration.DatafileAppConfig; +import org.onap.dcaegen2.collectors.datafile.integration.junit5.mockito.MockitoExtension; + +/** + * @author Przemysław Wąsala on 4/9/18 + */ +@ExtendWith({MockitoExtension.class}) +class DatafileAppConfigTest { + + private static final String DATAFILE_ENDPOINTS = "datafile_endpoints.json"; + private static final String jsonString = "{\"configs\":{\"aai\":{\"aaiClientConfiguration\":{\"aaiHost\":" + + "\"localhost\",\"aaiPort\":8080,\"aaiIgnoreSslCertificateErrors\":true,\"aaiProtocol\":" + + "\"https\",\"aaiUserName\":\"admin\",\"aaiUserPassword\":\"admin\",\"aaiBasePath\":\"/aai/v11\"," + + "\"aaiPnfPath\":\"/network/pnfs/pnf\",\"aaiHeaders\":{\"X-FromAppId\":\"datafile\",\"X-TransactionId\":\"9999\"," + + "\"Accept\":\"application/json\",\"Real-Time\":\"true\",\"Content-Type\":\"application/merge-patch+json\"," + + "\"Authorization\":\"Basic QUFJOkFBSQ==\"}}}," + + "\"dmaap\":{\"dmaapConsumerConfiguration\":{\"consumerGroup\":\"other\",\"consumerId\":\"1\"," + + "\"dmaapContentType\":\"application/json\",\"dmaapHostName\":\"localhost\",\"dmaapPortNumber\":2222," + + "\"dmaapProtocol\":\"http\",\"dmaapTopicName\":\"temp\",\"dmaapUserName\":\"admin\",\"dmaapUserPassword\"" + + ":\"admin\",\"messageLimit\":1000,\"timeoutMs\":1000},\"dmaapProducerConfiguration\":{\"dmaapContentType\":" + + "\"application/json\",\"dmaapHostName\":\"localhost\",\"dmaapPortNumber\":2223,\"dmaapProtocol\":\"http\"," + + "\"dmaapTopicName\":\"temp\",\"dmaapUserName\":\"admin\",\"dmaapUserPassword\":\"admin\"}}}}"; + + private static final String incorrectJsonString = "{\"configs\":{\"aai\":{\"aaiClientConfiguration\":{\"aaiHost\":" + + "\"localhost\",\"aaiPort\":8080,\"aaiIgnoreSslCertificateErrors\":true,\"aaiProtocol\":\"https\"," + + "\"aaiUserName\":\"admin\",\"aaiUserPassword\":\"admin\",\"aaiBasePath\":\"/aai/v11\",\"aaiPnfPath\":" + + "\"/network/pnfs/pnf\",\"aaiHeaders\":{\"X-FromAppId\":\"datafile\",\"X-TransactionId\":\"9999\",\"Accept\":" + + "\"application/json\",\"Real-Time\":\"true\",\"Content-Type\":\"application/merge-patch+json\"," + + "\"Authorization\":\"Basic QUFJOkFBSQ==\"}}},\"dmaap\"" + + ":{\"dmaapConsumerConfiguration\":{\"consumerGroup\":\"other\",\"consumerId\":\"1\",\"dmaapContentType\"" + + ":\"application/json\",\"dmaapHostName\":\"localhost\",\"dmaapPortNumber\":2222,\"dmaapProtocol\":\"http\"" + + ",\"dmaapTopicName\":\"temp\",\"dmaapUserName\":\"admin\",\"dmaapUserPassword\":\"admin\",\"messageLimit\"" + + ":1000,\"timeoutMs\":1000},\"dmaapProducerConfiguration\":{\"dmaapContentType\":\"application/json\"," + + "\"dmaapHostName\":\"localhost\",\"dmaapPortNumber\":2223,\"dmaapProtocol\":\"http\",\"dmaaptopicName\"" + + ":\"temp\",\"dmaapuserName\":\"admin\",\"dmaapuserPassword\":\"admin\"}}}}"; + + private static DatafileAppConfig datafileAppConfig; + private static AppConfig appConfig; + + private static String filePath = Objects + .requireNonNull(DatafileAppConfigTest.class.getClassLoader().getResource(DATAFILE_ENDPOINTS)).getFile(); + + @BeforeEach + void setUp() { + datafileAppConfig = spy(DatafileAppConfig.class); + appConfig = spy(new AppConfig()); + } + + @Test + void whenApplicationWasStarted_FilePathIsSet() { + // + // When + // + datafileAppConfig.setFilepath(filePath); + // + // Then + // + verify(datafileAppConfig, times(1)).setFilepath(anyString()); + verify(datafileAppConfig, times(0)).initFileStreamReader(); + Assertions.assertEquals(filePath, datafileAppConfig.getFilepath()); + } + + @Test + void whenTheConfigurationFits_GetAaiAndDmaapObjectRepresentationConfiguration() + throws IOException { + // + // Given + // + InputStream inputStream = new ByteArrayInputStream((jsonString.getBytes( + StandardCharsets.UTF_8))); + // + // When + // + datafileAppConfig.setFilepath(filePath); + doReturn(inputStream).when(datafileAppConfig).getInputStream(any()); + datafileAppConfig.initFileStreamReader(); + appConfig.dmaapConsumerConfiguration = datafileAppConfig.getDmaapConsumerConfiguration(); + appConfig.dmaapPublisherConfiguration = datafileAppConfig.getDmaapPublisherConfiguration(); + appConfig.aaiClientConfiguration = datafileAppConfig.getAaiClientConfiguration(); + // + // Then + // + verify(datafileAppConfig, times(1)).setFilepath(anyString()); + verify(datafileAppConfig, times(1)).initFileStreamReader(); + Assertions.assertNotNull(datafileAppConfig.getAaiClientConfiguration()); + Assertions.assertNotNull(datafileAppConfig.getDmaapConsumerConfiguration()); + Assertions.assertNotNull(datafileAppConfig.getDmaapPublisherConfiguration()); + Assertions + .assertEquals(appConfig.getDmaapPublisherConfiguration(), datafileAppConfig.getDmaapPublisherConfiguration()); + Assertions + .assertEquals(appConfig.getDmaapConsumerConfiguration(), datafileAppConfig.getDmaapConsumerConfiguration()); + Assertions + .assertEquals(appConfig.getAaiClientConfiguration(), datafileAppConfig.getAaiClientConfiguration()); + + } + + @Test + void whenFileIsNotExist_ThrowIoException() { + // + // Given + // + filePath = "/temp.json"; + datafileAppConfig.setFilepath(filePath); + // + // When + // + datafileAppConfig.initFileStreamReader(); + // + // Then + // + verify(datafileAppConfig, times(1)).setFilepath(anyString()); + verify(datafileAppConfig, times(1)).initFileStreamReader(); + Assertions.assertNull(datafileAppConfig.getAaiClientConfiguration()); + Assertions.assertNull(datafileAppConfig.getDmaapConsumerConfiguration()); + Assertions.assertNull(datafileAppConfig.getDmaapPublisherConfiguration()); + + } + + @Test + void whenFileIsExistsButJsonIsIncorrect() throws IOException { + // + // Given + // + InputStream inputStream = new ByteArrayInputStream((incorrectJsonString.getBytes( + StandardCharsets.UTF_8))); + // + // When + // + datafileAppConfig.setFilepath(filePath); + doReturn(inputStream).when(datafileAppConfig).getInputStream(any()); + datafileAppConfig.initFileStreamReader(); + + // + // Then + // + verify(datafileAppConfig, times(1)).setFilepath(anyString()); + verify(datafileAppConfig, times(1)).initFileStreamReader(); + Assertions.assertNotNull(datafileAppConfig.getAaiClientConfiguration()); + Assertions.assertNotNull(datafileAppConfig.getDmaapConsumerConfiguration()); + Assertions.assertNull(datafileAppConfig.getDmaapPublisherConfiguration()); + + } + + + @Test + void whenTheConfigurationFits_ButRootElementIsNotAJsonObject() + throws IOException { + // Given + InputStream inputStream = new ByteArrayInputStream((jsonString.getBytes( + StandardCharsets.UTF_8))); + // When + datafileAppConfig.setFilepath(filePath); + doReturn(inputStream).when(datafileAppConfig).getInputStream(any()); + JsonElement jsonElement = mock(JsonElement.class); + when(jsonElement.isJsonObject()).thenReturn(false); + doReturn(jsonElement).when(datafileAppConfig).getJsonElement(any(JsonParser.class), any(InputStream.class)); + datafileAppConfig.initFileStreamReader(); + appConfig.dmaapConsumerConfiguration = datafileAppConfig.getDmaapConsumerConfiguration(); + appConfig.dmaapPublisherConfiguration = datafileAppConfig.getDmaapPublisherConfiguration(); + appConfig.aaiClientConfiguration = datafileAppConfig.getAaiClientConfiguration(); + + // Then + verify(datafileAppConfig, times(1)).setFilepath(anyString()); + verify(datafileAppConfig, times(1)).initFileStreamReader(); + Assertions.assertNull(datafileAppConfig.getAaiClientConfiguration()); + Assertions.assertNull(datafileAppConfig.getDmaapConsumerConfiguration()); + Assertions.assertNull(datafileAppConfig.getDmaapPublisherConfiguration()); + } +} \ No newline at end of file diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/ScheduledXmlContextITest.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/ScheduledXmlContextITest.java new file mode 100644 index 00000000..b9aa2f78 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/ScheduledXmlContextITest.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.integration; + +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.onap.dcaegen2.collectors.datafile.integration.junit5.mockito.MockitoExtension; +import org.onap.dcaegen2.collectors.datafile.tasks.ScheduledTasks; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; + +/** + * @author Przemysław Wąsala on 3/27/18 + */ + +@Configuration +@ComponentScan +@ExtendWith({MockitoExtension.class, SpringExtension.class}) +@ContextConfiguration(locations = {"classpath:scheduled-context.xml"}) +class ScheduledXmlContextITest extends AbstractTestNGSpringContextTests { + + private static final int WAIT_FOR_SCHEDULING = 1; + + @Autowired + private ScheduledTasks scheduledTask; + + @Test + void testScheduling() { + final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + executorService.scheduleWithFixedDelay(this::verifyDmaapConsumerTask, 0, WAIT_FOR_SCHEDULING, TimeUnit.SECONDS); + } + + private void verifyDmaapConsumerTask() { + verify(scheduledTask, atLeast(1)).scheduleMainDatafileEventTask(); + } +} + + diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/ServiceMockProvider.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/ServiceMockProvider.java new file mode 100644 index 00000000..47107588 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/ServiceMockProvider.java @@ -0,0 +1,45 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.integration; + +import static org.mockito.Mockito.mock; + +import org.onap.dcaegen2.collectors.datafile.configuration.DatafileAppConfig; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Przemysław Wąsala on 7/10/18 + */ +@Configuration +class ServiceMockProvider { + + @Bean + public DatafileAppConfig getDatafileAppConfig() { + return mock(DatafileAppConfig.class); + } + + @Bean + public ConsumerDmaapModel getRequestDetails() { + return mock(ConsumerDmaapModel.class); + } +} diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/junit5/mockito/MockitoExtension.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/junit5/mockito/MockitoExtension.java new file mode 100644 index 00000000..df167425 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/integration/junit5/mockito/MockitoExtension.java @@ -0,0 +1,83 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.integration.junit5.mockito; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Parameter; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolver; +import org.junit.jupiter.api.extension.TestInstancePostProcessor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** + * @author Przemysław Wąsala on 3/27/18 + * + * {@code MockitoExtension } showcases the {@link TestInstancePostProcessor} and {@link ParameterResolver} extension + * APIs of JUnit 5 by providing dependency injection support at the field level and at the method parameter level + * viaMockito 2.x's {@link Mock @Mock} annotation. + */ +public class MockitoExtension implements TestInstancePostProcessor, ParameterResolver { + + @Override + public void postProcessTestInstance(Object testInstance, ExtensionContext context) { + MockitoAnnotations.initMocks(testInstance); + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { + return parameterContext.getParameter().isAnnotationPresent(Mock.class); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { + return getMock(parameterContext.getParameter(), extensionContext); + } + + private Object getMock(Parameter parameter, ExtensionContext extensionContext) { + Class mockType = parameter.getType(); + Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType)); + String mockName = getMockName(parameter); + + if (mockName != null) { + return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName)); + } else { + return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType)); + } + } + + private String getMockName(Parameter parameter) { + String explicitMockName = parameter.getAnnotation(Mock.class).name().trim(); + if (!explicitMockName.isEmpty()) { + return explicitMockName; + } else if (parameter.isNamePresent()) { + return parameter.getName(); + } + return null; + } + + +} diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/service/DmaapConsumerJsonParserTest.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/service/DmaapConsumerJsonParserTest.java new file mode 100644 index 00000000..d7ceee82 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/service/DmaapConsumerJsonParserTest.java @@ -0,0 +1,273 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.service; + +import static org.mockito.Mockito.spy; + +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import java.util.Optional; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapNotFoundException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.DmaapConsumerJsonParser; +import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * @author Przemysław Wąsala on 5/8/18 + */ +class DmaapConsumerJsonParserTest { + + @Test + void whenPassingCorrectJson_validationNotThrowingAnException() { + //given + String message = + "[{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"," + + "\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\"" + + ":{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\":" + + "3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\":1517206400" + + ",\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfOamIpv4Address\":" + + "\"10.16.123.234\",\"pnfOamIpv6Address\":\"0:0:0:0:0:FFFF:0A10:7BEA\",\"pnfSerialNumber\":" + + "\"QTFCOC540002E\",\"pnfSoftwareVersion\":\"v4.5.0.1\",\"pnfType\":\"AirScale\",\"pnfVendorName\":" + + "\"Nokia\"}}}]"; + + String parsed = + "{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\",\"eventName\"" + + ":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":{}," + + "\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\":" + + "3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\":" + + "1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfOamIpv4Address\":" + + "\"10.16.123.234\",\"pnfOamIpv6Address\":\"0:0:0:0:0:FFFF:0A10:7BEA\",\"pnfSerialNumber\":" + + "\"QTFCOC540002E\",\"pnfSoftwareVersion\":\"v4.5.0.1\",\"pnfType\":\"AirScale\",\"pnfVendorName\":" + + "\"Nokia\"}}}"; + ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234") + .ipv6("0:0:0:0:0:FFFF:0A10:7BEA") + .pnfName("NOKQTFCOC540002E").build(); + //when + DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser()); + JsonElement jsonElement = new JsonParser().parse(parsed); + Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject())) + .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement); + ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser + .getJsonObject(Mono.just((message))).block(); + //then + Assertions.assertNotNull(consumerDmaapModel); + Assertions.assertEquals(expectedObject, consumerDmaapModel); + } + + @Test + void whenPassingCorrectJsonWithoutIpv4_validationNotThrowingAnException() { + //given + String message = + "[{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"," + + "\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":" + + "{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\":3}" + + ",\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\":1517206400," + + "\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfOamIpv6Address\":" + + "\"0:0:0:0:0:FFFF:0A10:7BEA\",\"pnfSerialNumber\":\"QTFCOC540002E\",\"pnfSoftwareVersion\"" + + ":\"v4.5.0.1\",\"pnfType\":\"AirScale\",\"pnfVendorName\":\"Nokia\"}}}]"; + + String parsed = + "{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\",\"eventName\"" + + ":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":{}," + + "\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\":3}" + + ",\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\":1517206400," + + "\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfOamIpv6Address\":" + + "\"0:0:0:0:0:FFFF:0A10:7BEA\",\"pnfSerialNumber\":\"QTFCOC540002E\",\"pnfSoftwareVersion\"" + + ":\"v4.5.0.1\",\"pnfType\":\"AirScale\",\"pnfVendorName\":\"Nokia\"}}}"; + + //when + DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser()); + JsonElement jsonElement = new JsonParser().parse(parsed); + Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject())) + .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement); + dmaapConsumerJsonParser.getJsonObject(Mono.just((message))); + ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser.getJsonObject(Mono.just((message))) + .block(); + //then + ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder().ipv4("") + .ipv6("0:0:0:0:0:FFFF:0A10:7BEA") + .pnfName("NOKQTFCOC540002E").build(); + Assertions.assertNotNull(consumerDmaapModel); + Assertions.assertEquals(expectedObject, consumerDmaapModel); + } + + @Test + void whenPassingCorrectJsonWihoutIpv6_validationNotThrowingAnException() { + //given + String message = + "[{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"," + + "\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":" + + "{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682," + + "\"version\":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate" + + "\":1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfOamIpv4Address" + + "\":\"10.16.123.234\",\"pnfSerialNumber\":\"QTFCOC540002E\",\"pnfSoftwareVersion\":\"v4.5.0.1\"," + + "\"pnfType\":\"AirScale\",\"pnfVendorName\":\"Nokia\"}}}]"; + String parsed = + "{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\",\"eventName\"" + + ":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":{}," + + "\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682," + + "\"version\":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate" + + "\":1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfOamIpv4Address" + + "\":\"10.16.123.234\",\"pnfSerialNumber\":\"QTFCOC540002E\",\"pnfSoftwareVersion\":\"v4.5.0.1\"," + + "\"pnfType\":\"AirScale\",\"pnfVendorName\":\"Nokia\"}}}"; + + ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234").ipv6("") + .pnfName("NOKQTFCOC540002E").build(); + //when + DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser()); + JsonElement jsonElement = new JsonParser().parse(parsed); + Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject())) + .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement); + ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser.getJsonObject(Mono.just((message))) + .block(); + //then + Assertions.assertNotNull(consumerDmaapModel); + Assertions.assertEquals(expectedObject, consumerDmaapModel); + } + + @Test + void whenPassingCorrectJsonWihoutIpv4andIpv6_validationThrowingAnException() { + String message = + "[{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"," + + "\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":" + + "{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\"" + + ":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\"" + + ":1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfSoftwareVersion\":" + + "\"v4.5.0.1\",\"pnfType\":\"AirScale\",\"pnfVendorName\":\"Nokia\"}}}]"; + String parsed = + "{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\",\"eventName\"" + + ":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":{}," + + "\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\"" + + ":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\"" + + ":1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfSoftwareVersion\":" + + "\"v4.5.0.1\",\"pnfType\":\"AirScale\",\"pnfVendorName\":\"Nokia\"}}}"; + DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser()); + JsonElement jsonElement = new JsonParser().parse(parsed); + Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject())) + .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement); + StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(message))) + .expectSubscription().expectError(DmaapNotFoundException.class).verify(); + + } + + @Test + void whenPassingJsonWithoutMandatoryHeaderInformation_validationThrowingAnException() { + String parsed = "{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"" + + ",\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":{}," + + "\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\",\"priority\"" + + ":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":\"<>\"," + + "\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\":3}}}"; + DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser()); + JsonElement jsonElement = new JsonParser().parse(parsed); + Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject())) + .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement); + String incorrectMessage = + "[{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"" + + ",\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":" + + "{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\":3" + + "}}}]"; + StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(incorrectMessage))) + .expectSubscription().expectError(DmaapNotFoundException.class).verify(); + } + + @Test + void whenPassingJsonWithoutPnfSerialNumberOrPnfVendorName_validationThrowingAnException() { + String parsed = "{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":" + + "\"<>-reg\",\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"" + + "internalHeaderFields\":{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\"," + + "\"nfcNamingCode\":\"5DU\",\"priority\":\"Normal\",reportingEntityName\":\"5GRAN_DU\",\"sequence\":0," + + "\"sourceId\":\"<>\",\"sourceName\":\"5GRAN_DU\",startEpochMicrosec\":1519837825682,\"" + + "version\":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\"" + + ":1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfOamIpv4Address\":" + + "\"10.16.123.234\",\"pnfOamIpv6Address\":\"0:0:0:0:0:FFFF:0A10:7BEA\",\"pnfSoftwareVersion\":" + + "\"v4.5.0.1\",\"pnfType\":\"AirScale\"}}}"; + DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser()); + JsonElement jsonElement = new JsonParser().parse(parsed); + Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject())) + .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement); + String jsonWithoutPnfVendorAndSerialNumber = + "[{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":" + + "\"<>-reg\",\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"" + + "internalHeaderFields\":{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\"," + + "\"nfcNamingCode\":\"5DU\",\"priority\":\"Normal\",reportingEntityName\":\"5GRAN_DU\",\"sequence\":0," + + "\"sourceId\":\"<>\",\"sourceName\":\"5GRAN_DU\",startEpochMicrosec\":1519837825682," + + "\"version\":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\"," + + "\"pnfLastServiceDate\":1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\"," + + "\"pnfOamIpv4Address\":\"10.16.123.234\",\"pnfOamIpv6Address\":\"0:0:0:0:0:FFFF:0A10:7BEA\"," + + "\"pnfSoftwareVersion\":\"v4.5.0.1\",\"pnfType\":\"AirScale\"}}}]"; + StepVerifier + .create(dmaapConsumerJsonParser.getJsonObject(Mono.just(jsonWithoutPnfVendorAndSerialNumber))) + .expectSubscription().expectError(DmaapNotFoundException.class).verify(); + } + + @Test + void whenPassingJsonWithoutIpInformation_validationThrowingAnException() { + String parsed = + "{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"," + + "\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\"" + + ":{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\"" + + ":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\":" + + "1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":" + + "\"AJ02\",\"pnfSerialNumber\":\"QTFCOC540002E\",\"pnfSoftwareVersion\":\"v4.5.0.1\",\"pnfType\":" + + "\"AirScale\"," + "\"pnfVendorName\":\"Nokia\"}}}"; + DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser()); + JsonElement jsonElement = new JsonParser().parse(parsed); + Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject())) + .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement); + String jsonWithoutIpInformation = + "[{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"," + + "\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\"" + + ":{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\"" + + ":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\"" + + ":1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfSerialNumber\"" + + ":\"QTFCOC540002E\",\"pnfSoftwareVersion\":\"v4.5.0.1\",\"pnfType\":\"AirScale\"," + + "\"pnfVendorName\":\"Nokia\"}}}]"; + StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(jsonWithoutIpInformation))) + .expectSubscription().expectError(DmaapNotFoundException.class).verify(); + } +} diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskImplTest.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskImplTest.java new file mode 100644 index 00000000..05a99b43 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskImplTest.java @@ -0,0 +1,149 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.Optional; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.exceptions.AaiNotFoundException; +import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.AaiConsumerClient; +import org.onap.dcaegen2.collectors.datafile.tasks.AaiConsumerTaskImpl; +import org.onap.dcaegen2.collectors.datafile.config.ImmutableAaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel; + +/** + * @author Przemysław Wąsala on 5/17/18 + */ +class AaiConsumerTaskImplTest { + + private static ConsumerDmaapModel consumerDmaapModel; + private static AaiConsumerTaskImpl aaiConsumerTask; + + private static final String AAI_HOST = "/aai/v12/network/pnfs/pnf/NOKQTFCOC540002E"; + private static final Integer PORT = 1234; + private static final String PROTOCOL = "https"; + private static final String USER_NAME_PASSWORD = "Datafile"; + private static final String BASE_PATH = "/aai/v12"; + private static final String PNF_PATH = "/network/pnfs/pnf"; + + private static AaiClientConfiguration aaiClientConfiguration; + private static AaiConsumerClient aaiConsumerClient; + private static AppConfig appConfig; + + @BeforeAll + static void setUp() { + aaiClientConfiguration = new ImmutableAaiClientConfiguration.Builder() + .aaiHost(AAI_HOST) + .aaiPort(PORT) + .aaiProtocol(PROTOCOL) + .aaiUserName(USER_NAME_PASSWORD) + .aaiUserPassword(USER_NAME_PASSWORD) + .aaiIgnoreSslCertificateErrors(true) + .aaiBasePath(BASE_PATH) + .aaiPnfPath(PNF_PATH) + .build(); + consumerDmaapModel = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234") + .ipv6("0:0:0:0:0:FFFF:0A10:7BEA") + .pnfName("NOKQTFCOC540002E").build(); + appConfig = mock(AppConfig.class); + + } + + @Test + void whenPassedObjectDoesntFit_ThrowsDatafileTaskException() { + //given/when + when(appConfig.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration); + aaiConsumerTask = new AaiConsumerTaskImpl(appConfig); + Executable executableCode = () -> aaiConsumerTask.execute(null); + //then + Assertions + .assertThrows(DatafileTaskException.class, executableCode, "Passing wrong object type to execute function"); + + } + + @Test + void whenPassedObjectFits_ReturnsCorrectStatus() throws DatafileTaskException, IOException { + //given/when + getAaiConsumerTask_WhenMockingHttpResponseCode("200", false); + String response = aaiConsumerTask.execute(consumerDmaapModel); + + //then + verify(aaiConsumerClient, times(1)).getHttpResponse(any(ConsumerDmaapModel.class)); + verifyNoMoreInteractions(aaiConsumerClient); + Assertions.assertEquals("200", response); + } + + @Test + void whenPassedObjectFits_butIncorrectResponseReturns() throws IOException, AaiNotFoundException { + //given/when + getAaiConsumerTask_WhenMockingHttpResponseCode("400", false); + String response = aaiConsumerTask.execute(consumerDmaapModel); + + //then + verify(aaiConsumerClient, times(1)).getHttpResponse(any(ConsumerDmaapModel.class)); + verifyNoMoreInteractions(aaiConsumerClient); + Assertions.assertEquals("400", response); + } + + @Test + void whenPassedObjectFits_ThrowsIoExceptionAndHandleIt() throws IOException { + //given/when + getAaiConsumerTask_WhenMockingHttpResponseCode(null, true); + Executable executableCode = () -> aaiConsumerTask.execute(any(ConsumerDmaapModel.class)); + Assertions + .assertThrows(DatafileTaskException.class, executableCode, "HttpClient throws IOException"); + + //then + verifyNoMoreInteractions(aaiConsumerClient); + } + + + private static void getAaiConsumerTask_WhenMockingHttpResponseCode(String httpResponseCode, boolean throwsException) + throws IOException { + aaiConsumerClient = mock(AaiConsumerClient.class); + if (throwsException) { + when(aaiConsumerClient.getHttpResponse(consumerDmaapModel)).thenThrow(IOException.class); + } else { + when(aaiConsumerClient.getHttpResponse(consumerDmaapModel)).thenReturn(Optional.of(httpResponseCode)); + } + when(appConfig.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration); + aaiConsumerTask = spy(new AaiConsumerTaskImpl(appConfig)); + when(aaiConsumerTask.resolveConfiguration()).thenReturn(aaiClientConfiguration); + doReturn(aaiConsumerClient).when(aaiConsumerTask).resolveClient(); + } + +} \ No newline at end of file diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskSpy.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskSpy.java new file mode 100644 index 00000000..9e1842b0 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiConsumerTaskSpy.java @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.tasks.AaiConsumerTask; +import org.onap.dcaegen2.collectors.datafile.tasks.AaiConsumerTaskImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +@Configuration +public class AaiConsumerTaskSpy { + + /** + * Mocking bean for tests. + * + * @return A&AI ConsumerTask spy + */ + @Bean + @Primary + public AaiConsumerTask registerSimpleAaiPublisherTask() { + AppConfig appConfig = mock(AppConfig.class); + when(appConfig.getAaiClientConfiguration()).thenReturn(mock(AaiClientConfiguration.class)); + return spy(new AaiConsumerTaskImpl(appConfig)); + } +} \ No newline at end of file diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTaskImplTest.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTaskImplTest.java new file mode 100644 index 00000000..f33fc931 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiProducerTaskImplTest.java @@ -0,0 +1,133 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.producer.AaiProducerReactiveHttpClient; +import org.onap.dcaegen2.collectors.datafile.tasks.AaiProducerTaskImpl; +import org.onap.dcaegen2.collectors.datafile.config.ImmutableAaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * @author Przemysław Wąsala on 5/14/18 + */ +class AaiProducerTaskImplTest { + + + private static final String AAI_HOST = "/aai/v11/network/pnfs/pnf/NOKQTFCOC540002E"; + private static final Integer PORT = 1234; + private static final String PROTOCOL = "https"; + private static final String USER_NAME_PASSWORD = "Datafile"; + private static final String BASE_PATH = "/aai/v11"; + private static final String PNF_PATH = "/network/pnfs/pnf"; + + private static ConsumerDmaapModel consumerDmaapModel; + private static AaiProducerTaskImpl aaiProducerTask; + private static AaiClientConfiguration aaiClientConfiguration; + private static AaiProducerReactiveHttpClient aaiProducerReactiveHttpClient; + private static AppConfig appConfig; + + @BeforeAll + static void setUp() { + aaiClientConfiguration = new ImmutableAaiClientConfiguration.Builder() + .aaiHost(AAI_HOST) + .aaiPort(PORT) + .aaiProtocol(PROTOCOL) + .aaiUserName(USER_NAME_PASSWORD) + .aaiUserPassword(USER_NAME_PASSWORD) + .aaiIgnoreSslCertificateErrors(true) + .aaiBasePath(BASE_PATH) + .aaiPnfPath(PNF_PATH) + .build(); + consumerDmaapModel = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234") + .ipv6("0:0:0:0:0:FFFF:0A10:7BEA") + .pnfName("NOKQTFCOC540002E").build(); + appConfig = mock(AppConfig.class); + + } + + @Test + void whenPassedObjectDoesntFit_ThrowsDatafileTaskException() { + //given/when/ + when(appConfig.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration); + aaiProducerTask = new AaiProducerTaskImpl(appConfig); + Executable executableCode = () -> aaiProducerTask.execute(null); + + //then + Assertions + .assertThrows(DatafileTaskException.class, executableCode, "Passing wrong object type to execute function"); + } + + @Test + void whenPassedObjectFits_ReturnsCorrectStatus() throws DatafileTaskException { + //given/when + getAaiProducerTask_whenMockingResponseObject(200); + Mono response = aaiProducerTask.execute(Mono.just(consumerDmaapModel)); + + //then + verify(aaiProducerReactiveHttpClient, times(1)).getAaiProducerResponse(any()); + verifyNoMoreInteractions(aaiProducerReactiveHttpClient); + Assertions.assertEquals(consumerDmaapModel, response.block()); + + } + + + @Test + void whenPassedObjectFits_butIncorrectResponseReturns() throws DatafileTaskException { + //given/when + getAaiProducerTask_whenMockingResponseObject(400); + StepVerifier.create(aaiProducerTask.execute(Mono.just(consumerDmaapModel))).expectSubscription() + .expectError(DatafileTaskException.class).verify(); + //then + verify(aaiProducerReactiveHttpClient, times(1)).getAaiProducerResponse(any()); + verifyNoMoreInteractions(aaiProducerReactiveHttpClient); + } + + private static void getAaiProducerTask_whenMockingResponseObject(Integer statusCode) { + //given + aaiProducerReactiveHttpClient = mock(AaiProducerReactiveHttpClient.class); + when(aaiProducerReactiveHttpClient.getAaiProducerResponse(any())) + .thenReturn(Mono.just(statusCode)); + when(appConfig.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration); + aaiProducerTask = spy(new AaiProducerTaskImpl(appConfig)); + when(aaiProducerTask.resolveConfiguration()).thenReturn(aaiClientConfiguration); + doReturn(aaiProducerReactiveHttpClient).when(aaiProducerTask).resolveClient(); + } +} \ No newline at end of file diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiPublisherTaskSpy.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiPublisherTaskSpy.java new file mode 100644 index 00000000..3beda94b --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/AaiPublisherTaskSpy.java @@ -0,0 +1,58 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.service.producer.AaiProducerReactiveHttpClient; +import org.onap.dcaegen2.collectors.datafile.tasks.AaiProducerTask; +import org.onap.dcaegen2.collectors.datafile.tasks.AaiProducerTaskImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +/** + * @author Przemysław Wąsala on 4/13/18 + */ +@Configuration +public class AaiPublisherTaskSpy { + + /** + * Mocking bean for tests. + * + * @return A&AI ProducerTask spy + */ + @Bean + @Primary + public AaiProducerTask registerSimpleAaiPublisherTask() { + AppConfig appConfig = spy(AppConfig.class); + doReturn(mock(AaiClientConfiguration.class)).when(appConfig).getAaiClientConfiguration(); + AaiProducerTaskImpl aaiProducerTask = spy(new AaiProducerTaskImpl(appConfig)); + AaiProducerReactiveHttpClient aaiProducerReactiveHttpClient = mock(AaiProducerReactiveHttpClient.class); + doReturn(mock(AaiClientConfiguration.class)).when(aaiProducerTask).resolveConfiguration(); + doReturn(aaiProducerReactiveHttpClient).when(aaiProducerTask).resolveClient(); + return aaiProducerTask; + } +} diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskImplTest.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskImplTest.java new file mode 100644 index 00000000..19ab1ab9 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskImplTest.java @@ -0,0 +1,136 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import java.util.Optional; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.onap.dcaegen2.collectors.datafile.config.DmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapEmptyResponseException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.DmaapConsumerJsonParser; +import org.onap.dcaegen2.collectors.datafile.service.consumer.DMaaPConsumerReactiveHttpClient; +import org.onap.dcaegen2.collectors.datafile.tasks.DmaapConsumerTaskImpl; +import org.onap.dcaegen2.collectors.datafile.config.ImmutableDmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * @author Przemysław Wąsala on 5/17/18 + */ +class DmaapConsumerTaskImplTest { + + private static ConsumerDmaapModel consumerDmaapModel; + private static DmaapConsumerTaskImpl dmaapConsumerTask; + private static DMaaPConsumerReactiveHttpClient dMaaPConsumerReactiveHttpClient; + private static AppConfig appConfig; + private static DmaapConsumerConfiguration dmaapConsumerConfiguration; + private static String message; + private static String parsed; + + @BeforeAll + static void setUp() { + dmaapConsumerConfiguration = new ImmutableDmaapConsumerConfiguration.Builder().consumerGroup("OpenDCAE-c12") + .consumerId("c12").dmaapContentType("application/json").dmaapHostName("54.45.33.2").dmaapPortNumber(1234) + .dmaapProtocol("https").dmaapUserName("Datafile").dmaapUserPassword("Datafile") + .dmaapTopicName("unauthenticated.SEC_OTHER_OUTPUT").timeoutMs(-1).messageLimit(-1).build(); + + consumerDmaapModel = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234") + .ipv6("0:0:0:0:0:FFFF:0A10:7BEA") + .pnfName("NOKQTFCOC540002E").build(); + appConfig = mock(AppConfig.class); + message = + "[{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\"," + + "\"eventName\":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\"" + + ":{},\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682,\"version\"" + + ":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\",\"pnfLastServiceDate\":" + + "1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\",\"pnfOamIpv4Address\":" + + "\"10.16.123.234\",\"pnfOamIpv6Address\":\"0:0:0:0:0:FFFF:0A10:7BEA\",\"pnfSerialNumber\":" + + "\"QTFCOC540002E\",\"pnfSoftwareVersion\":\"v4.5.0.1\",\"pnfType\":\"AirScale\",\"pnfVendorName\":" + + "\"Nokia\"}}}]"; + parsed = + "{\"event\":{\"commonEventHeader\":{\"domain\":\"other\",\"eventId\":\"<>-reg\",\"eventName\"" + + ":\"pnfRegistration_5GDU\",\"eventType\":\"pnfRegistration\",\"internalHeaderFields\":{}," + + "\"lastEpochMicrosec\":1519837825682,\"nfNamingCode\":\"5GRAN\",\"nfcNamingCode\":\"5DU\"," + + "\"priority\":\"Normal\",\"reportingEntityName\":\"5GRAN_DU\",\"sequence\":0,\"sourceId\":" + + "\"<>\",\"sourceName\":\"5GRAN_DU\",\"startEpochMicrosec\":1519837825682," + + "\"version\":3},\"otherFields\":{\"otherFieldsVersion\":1,\"pnfFamily\":\"BBU\"," + + "\"pnfLastServiceDate\":1517206400,\"pnfManufactureDate\":1516406400,\"pnfModelNumber\":\"AJ02\"," + + "\"pnfOamIpv4Address\":\"10.16.123.234\",\"pnfOamIpv6Address\":\"0:0:0:0:0:FFFF:0A10:7BEA\"," + + "\"pnfSerialNumber\":\"QTFCOC540002E\",\"pnfSoftwareVersion\":\"v4.5.0.1\",\"pnfType\":\"AirScale\"," + + "\"pnfVendorName\":\"Nokia\"}}}"; + } + + @Test + void whenPassedObjectDoesntFit_DoesNotThrowDatafileTaskException() { + //given + prepareMocksForDmaapConsumer(Optional.empty()); + + //then + StepVerifier.create(dmaapConsumerTask.execute("Sample input")).expectSubscription() + .expectError(DmaapEmptyResponseException.class).verify(); + + verify(dMaaPConsumerReactiveHttpClient, times(1)).getDMaaPConsumerResponse(); + } + + @Test + void whenPassedObjectFits_ReturnsCorrectResponse() { + //given + prepareMocksForDmaapConsumer(Optional.of(message)); + //when + Mono response = dmaapConsumerTask.execute("Sample input"); + + //then + verify(dMaaPConsumerReactiveHttpClient, times(1)).getDMaaPConsumerResponse(); + assertEquals(consumerDmaapModel, response.block()); + + + } + + private void prepareMocksForDmaapConsumer(Optional message) { + DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser()); + JsonElement jsonElement = new JsonParser().parse(parsed); + Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject())) + .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement); + dMaaPConsumerReactiveHttpClient = mock(DMaaPConsumerReactiveHttpClient.class); + when(dMaaPConsumerReactiveHttpClient.getDMaaPConsumerResponse()).thenReturn(Mono.just(message.orElse(""))); + when(appConfig.getDmaapConsumerConfiguration()).thenReturn(dmaapConsumerConfiguration); + dmaapConsumerTask = spy(new DmaapConsumerTaskImpl(appConfig, dmaapConsumerJsonParser)); + when(dmaapConsumerTask.resolveConfiguration()).thenReturn(dmaapConsumerConfiguration); + doReturn(dMaaPConsumerReactiveHttpClient).when(dmaapConsumerTask).resolveClient(); + } +} \ No newline at end of file diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskSpy.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskSpy.java new file mode 100644 index 00000000..de5c8535 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapConsumerTaskSpy.java @@ -0,0 +1,59 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +import org.onap.dcaegen2.collectors.datafile.config.DmaapConsumerConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.service.consumer.DMaaPConsumerReactiveHttpClient; +import org.onap.dcaegen2.collectors.datafile.tasks.DmaapConsumerTask; +import org.onap.dcaegen2.collectors.datafile.tasks.DmaapConsumerTaskImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +/** + * @author Przemysław Wąsala on 3/27/18 + */ +@Configuration +public class DmaapConsumerTaskSpy { + + /** + * Mocking bean for tests. + * + * @return DMaaP ConsumerTask spy + */ + @Bean + @Primary + public DmaapConsumerTask registerSimpleDmaapConsumerTask() { + AppConfig appConfig = spy(AppConfig.class); + doReturn(mock(DmaapConsumerConfiguration.class)).when(appConfig).getDmaapConsumerConfiguration(); + DmaapConsumerTaskImpl dmaapConsumerTask = spy(new DmaapConsumerTaskImpl(appConfig)); + DMaaPConsumerReactiveHttpClient dmaapConsumerReactiveHttpClient = mock( + DMaaPConsumerReactiveHttpClient.class); + doReturn(mock(DmaapConsumerConfiguration.class)).when(dmaapConsumerTask).resolveConfiguration(); + doReturn(dmaapConsumerReactiveHttpClient).when(dmaapConsumerTask).resolveClient(); + return dmaapConsumerTask; + } +} diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapProducerTaskSpy.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapProducerTaskSpy.java new file mode 100644 index 00000000..870c712e --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapProducerTaskSpy.java @@ -0,0 +1,59 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.service.producer.DMaaPProducerReactiveHttpClient; +import org.onap.dcaegen2.collectors.datafile.tasks.DmaapPublisherTask; +import org.onap.dcaegen2.collectors.datafile.tasks.DmaapPublisherTaskImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +/** + * @author Przemysław Wąsala on 4/13/18 + */ +@Configuration +public class DmaapProducerTaskSpy { + + /** + * Mocking bean for tests. + * + * @return DMaaP PublisherTask spy + */ + @Bean + @Primary + public DmaapPublisherTask registerSimpleDmaapPublisherTask() { + AppConfig appConfig = spy(AppConfig.class); + doReturn(mock(DmaapPublisherConfiguration.class)).when(appConfig).getDmaapPublisherConfiguration(); + DmaapPublisherTaskImpl dmaapPublisherTask = spy(new DmaapPublisherTaskImpl(appConfig)); + DMaaPProducerReactiveHttpClient extendedDmaapProducerHttpClient = mock( + DMaaPProducerReactiveHttpClient.class); + doReturn(mock(DmaapPublisherConfiguration.class)).when(dmaapPublisherTask).resolveConfiguration(); + doReturn(extendedDmaapProducerHttpClient).when(dmaapPublisherTask).resolveClient(); + return dmaapPublisherTask; + } +} diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTaskImplTest.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTaskImplTest.java new file mode 100644 index 00000000..2b79bc40 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/DmaapPublisherTaskImplTest.java @@ -0,0 +1,124 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration; +import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig; +import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapNotFoundException; +import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; +import org.onap.dcaegen2.collectors.datafile.service.producer.DMaaPProducerReactiveHttpClient; +import org.onap.dcaegen2.collectors.datafile.tasks.DmaapPublisherTaskImpl; +import org.onap.dcaegen2.collectors.datafile.config.ImmutableDmaapPublisherConfiguration; +import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel; +import org.springframework.http.HttpStatus; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * @author Przemysław Wąsala on 5/17/18 + */ +class DmaapPublisherTaskImplTest { + + private static ConsumerDmaapModel consumerDmaapModel; + private static DmaapPublisherTaskImpl dmaapPublisherTask; + private static DMaaPProducerReactiveHttpClient dMaaPProducerReactiveHttpClient; + private static AppConfig appConfig; + private static DmaapPublisherConfiguration dmaapPublisherConfiguration; + + @BeforeAll + static void setUp() { + dmaapPublisherConfiguration = new ImmutableDmaapPublisherConfiguration.Builder() + .dmaapContentType("application/json").dmaapHostName("54.45.33.2").dmaapPortNumber(1234) + .dmaapProtocol("https").dmaapUserName("Datafile").dmaapUserPassword("Datafile") + .dmaapTopicName("unauthenticated.SEC_OTHER_OUTPUT").build(); + consumerDmaapModel = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234") + .ipv6("0:0:0:0:0:FFFF:0A10:7BEA") + .pnfName("NOKQTFCOC540002E").build(); + appConfig = mock(AppConfig.class); + } + + @Test + void whenPassedObjectDoesntFit_ThrowsDatafileTaskException() { + //given + when(appConfig.getDmaapPublisherConfiguration()).thenReturn(dmaapPublisherConfiguration); + dmaapPublisherTask = new DmaapPublisherTaskImpl(appConfig); + + //when + Executable executableFunction = () -> dmaapPublisherTask.execute(null); + + //then + assertThrows(DatafileTaskException.class, executableFunction, "The specified parameter is incorrect"); + } + + @Test + void whenPassedObjectFits_ReturnsCorrectStatus() throws DatafileTaskException { + //given + prepareMocksForTests(HttpStatus.OK.value()); + + //when + StepVerifier.create(dmaapPublisherTask.execute(Mono.just(consumerDmaapModel))).expectSubscription() + .expectNext(HttpStatus.OK.toString()).verifyComplete(); + + //then + verify(dMaaPProducerReactiveHttpClient, times(1)) + .getDMaaPProducerResponse(any(Mono.class)); + verifyNoMoreInteractions(dMaaPProducerReactiveHttpClient); + } + + + @Test + void whenPassedObjectFits_butIncorrectResponseReturns() throws DmaapNotFoundException { + //given + prepareMocksForTests(HttpStatus.UNAUTHORIZED.value()); + + //when + StepVerifier.create(dmaapPublisherTask.execute(Mono.just(consumerDmaapModel))).expectSubscription() + .expectNext(String.valueOf(HttpStatus.UNAUTHORIZED.value())).verifyComplete(); + + //then + verify(dMaaPProducerReactiveHttpClient, times(1)).getDMaaPProducerResponse(any(Mono.class)); + verifyNoMoreInteractions(dMaaPProducerReactiveHttpClient); + } + + + private void prepareMocksForTests(Integer httpResponseCode) { + dMaaPProducerReactiveHttpClient = mock(DMaaPProducerReactiveHttpClient.class); + when(dMaaPProducerReactiveHttpClient.getDMaaPProducerResponse(any(Mono.class))) + .thenReturn(Mono.just(httpResponseCode.toString())); + dmaapPublisherTask = spy(new DmaapPublisherTaskImpl(appConfig)); + when(dmaapPublisherTask.resolveConfiguration()).thenReturn(dmaapPublisherConfiguration); + doReturn(dMaaPProducerReactiveHttpClient).when(dmaapPublisherTask).resolveClient(); + } +} \ No newline at end of file diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduleControllerSpy.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduleControllerSpy.java new file mode 100644 index 00000000..d47d31d1 --- /dev/null +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduleControllerSpy.java @@ -0,0 +1,54 @@ +/* + * ============LICENSE_START======================================================= + * Datafile Collector Service + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.collectors.datafile.tasks; + +import static org.mockito.Mockito.spy; + +import org.onap.dcaegen2.collectors.datafile.tasks.AaiProducerTask; +import org.onap.dcaegen2.collectors.datafile.tasks.DmaapConsumerTask; +import org.onap.dcaegen2.collectors.datafile.tasks.DmaapPublisherTask; +import org.onap.dcaegen2.collectors.datafile.tasks.ScheduledTasks; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +/** + * @author Przemysław Wąsala on 4/5/18 + */ +@Configuration +public class ScheduleControllerSpy { + + @Autowired + private DmaapConsumerTask dmaapConsumerTaskImplSpy; + + @Autowired + private DmaapPublisherTask dmaapPublisherTaskImplSpy; + + @Autowired + private AaiProducerTask aaiPublisherTaskImplSpy; + + @Bean + @Primary + public ScheduledTasks registerSimpleScheduledTask() { + return spy(new ScheduledTasks(dmaapConsumerTaskImplSpy, dmaapPublisherTaskImplSpy, aaiPublisherTaskImplSpy)); + } +} diff --git a/datafile-app-server/src/test/resources/datafile_endpoints.json b/datafile-app-server/src/test/resources/datafile_endpoints.json new file mode 100644 index 00000000..599315b6 --- /dev/null +++ b/datafile-app-server/src/test/resources/datafile_endpoints.json @@ -0,0 +1,47 @@ +{ + "configs": { + "aai": { + "aaiClientConfiguration": { + "aaiHost": "localhost", + "aaiPort": 8080, + "aaiIgnoreSSLCertificateErrors": true, + "aaiProtocol": "https", + "aaiUserName": "AAI", + "aaiUserPassword": "AAI", + "aaiBasePath": "/aai/v11", + "aaiPnfPath": "/network/pnfs/pnf", + "aaiHeaders": { + "X-FromAppId": "datafile", + "X-TransactionId": "9999", + "Accept": "application/json", + "Real-Time": "true", + "Content-Type":"application/merge-patch+json" + } + } + }, + "dmaap": { + "dmaapConsumerConfiguration": { + "consumerGroup": "other", + "consumerId": "1", + "dmaapContentType": "application/json", + "dmaapHostName": "localhost", + "dmaapPortNumber": 2222, + "dmaapProtocol": "http", + "dmaapTopicName": "/events/pnfReady", + "dmaapUserName": "admin", + "dmaapUserPassword": "admin", + "messageLimit": 1000, + "timeoutMS": 1000 + }, + "dmaapProducerConfiguration": { + "dmaapContentType": "application/json", + "dmaapHostName": "localhost", + "dmaapPortNumber": 2223, + "dmaapProtocol": "http", + "dmaapTopicName": "/events/pnfReady", + "dmaapUserName": "admin", + "dmaapUserPassword": "admin" + } + } + } +} \ No newline at end of file diff --git a/datafile-app-server/src/test/resources/logback-test.xml b/datafile-app-server/src/test/resources/logback-test.xml new file mode 100644 index 00000000..3ff015e7 --- /dev/null +++ b/datafile-app-server/src/test/resources/logback-test.xml @@ -0,0 +1,33 @@ + + + + + + + + %d{ISO8601} - %-5p [%t:%C{1}@%L] - %m%n + + + + + + + + + -- cgit 1.2.3-korg