diff options
73 files changed, 1285 insertions, 916 deletions
diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index 8d95607..2496d14 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -25,22 +25,14 @@ "https://checkstyle.org/dtds/suppressions_1_0.dtd"> <suppressions> - <suppress checks=".*" files="\.java" lines="1-20" - /> - <suppress checks=".*" files="\.properties" - /> - <suppress checks="javadoc" files="\.java" - /> - <suppress checks="LineLength" files="\.java" - /> - <suppress checks="HiddenField" files="\.java" - /> - <suppress checks="FinalClass" files="\.java" - /> - <suppress checks="FinalParameters" files="\.java" - /> - <suppress checks="AvoidInlineConditionals" files="\.java" - /> - <suppress checks="DesignForExtension" files="\.java" - /> + <suppress checks=".*" files="\.java" lines="1-20"/> + <suppress checks=".*" files="\.properties"/> + <suppress checks="javadoc" files="\.java"/> + <suppress checks="LineLength" files="\.java"/> + <suppress checks="HiddenField" files="\.java"/> + <suppress checks="FinalClass" files="\.java"/> + <suppress checks="FinalParameters" files="\.java"/> + <suppress checks="AvoidInlineConditionals" files="\.java"/> + <suppress checks="DesignForExtension" files="\.java"/> + <suppress checks="CustomImportOrder" files="\.java"/> </suppressions> diff --git a/netconfsimulator/Dockerfile_app b/netconfsimulator/Dockerfile_app index 589be17..d1cc447 100644 --- a/netconfsimulator/Dockerfile_app +++ b/netconfsimulator/Dockerfile_app @@ -1,4 +1,4 @@ -FROM docker.io/openjdk:8-jre-alpine +FROM docker.io/openjdk:11-jre-slim ARG VERSION=${version} diff --git a/netconfsimulator/pom.xml b/netconfsimulator/pom.xml index b000f1c..6dbdf0c 100644 --- a/netconfsimulator/pom.xml +++ b/netconfsimulator/pom.xml @@ -35,15 +35,12 @@ <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <maven.compiler.source>1.8</maven.compiler.source> - <maven.compiler.target>1.8</maven.compiler.target> + <maven.compiler.source>11</maven.compiler.source> + <maven.compiler.target>11</maven.compiler.target> <maven.build.timestamp.format>yyyyMMdd'T'HHmmss</maven.build.timestamp.format> <docker.registry>nexus3.onap.org:10003</docker.registry> <docker.image.tag>latest</docker.image.tag> <docker.image.name>onap/${project.artifactId}</docker.image.name> - <spring.boot.version>2.1.6.RELEASE</spring.boot.version> - <spring.kafka.version>2.2.7.RELEASE</spring.kafka.version> - <apache.httpclient.version>4.5.6</apache.httpclient.version> <dependency.directory.name>libs</dependency.directory.name> <dependency.directory.location>${project.build.directory}/${dependency.directory.name} </dependency.directory.location> @@ -55,47 +52,60 @@ <skip-integration-tests>true</skip-integration-tests> <skip-unit-tests>false</skip-unit-tests> <project.build.integrationTestSourceDirectory>${project.basedir}/src/it/java</project.build.integrationTestSourceDirectory> + <build-helper-maven-plugin.version>3.1.0</build-helper-maven-plugin.version> </properties> <dependencies> + + <!-- Compile DEPENDENCIES --> + <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> - <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> - <version>${spring.boot.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> - <version>1.18.2</version> - <scope>provided</scope> + <scope>provided</scope> </dependency> <dependency> <groupId>org.onosproject</groupId> <artifactId>jnc</artifactId> - <version>1.0</version> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-websocket</artifactId> - <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> - <version>1.1</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpmime</artifactId> + </dependency> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger2</artifactId> + </dependency> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger-ui</artifactId> </dependency> - <!-- Kafka --> + <!-- Kafka --> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> - <version>${spring.kafka.version}</version> </dependency> <!-- TEST DEPENDENCIES --> @@ -103,91 +113,48 @@ <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> - <version>3.9.1</version> - <scope>test</scope> + <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> - <version>2.18.3</version> - <scope>test</scope> + <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> - <version>5.3.1</version> - <scope>test</scope> + <scope>test</scope> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> - <version>5.3.1</version> - <scope>test</scope> + <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> - <version>4.12</version> - <scope>test</scope> + <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> - <version>${spring.boot.version}</version> - <scope>test</scope> + <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka-test</artifactId> - <version>${spring.kafka.version}</version> - <scope>test</scope> + <scope>test</scope> </dependency> <dependency> <groupId>org.bitbucket.radistao.test</groupId> <artifactId>before-after-spring-test-runner</artifactId> - <version>0.1.0</version> - <scope>test</scope> + <scope>test</scope> </dependency> <dependency> <groupId>com.palantir.docker.compose</groupId> <artifactId>docker-compose-rule-junit4</artifactId> - <version>0.29.1</version> - <scope>test</scope> + <scope>test</scope> </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - <version>4.5.6</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpmime</artifactId> - <version>4.5.6</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - <version>${apache.httpclient.version}</version> - </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpmime</artifactId> - <version>${apache.httpclient.version}</version> - </dependency> - - <dependency> - <groupId>io.springfox</groupId> - <artifactId>springfox-swagger2</artifactId> - <version>2.9.2</version> - </dependency> - <dependency> - <groupId>io.springfox</groupId> - <artifactId>springfox-swagger-ui</artifactId> - <version>2.9.2</version> - </dependency> - </dependencies> <build> @@ -230,7 +197,7 @@ <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> - <version>3.1.0</version> + <version>${build-helper-maven-plugin.version}</version> <executions> <execution> <id>add-integration-test-source-as-test-sources</id> diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/Main.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/Main.java index e2a0ed0..1065e71 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/Main.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/Main.java @@ -25,7 +25,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Main { - public static void main(String[] args) { + // We are excluding this line in Sonar due to fact that + // Spring is handling arguments + public static void main(String[] args) { // NOSONAR SpringApplication.run(Main.class, args); } } diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/MessageDTO.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/Message.java index 4311cd6..9a7debc 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/MessageDTO.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/Message.java @@ -25,7 +25,7 @@ import lombok.Getter; @Getter @AllArgsConstructor -class MessageDTO { +class Message { private long timestamp; private String configuration; } diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/StoreController.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/StoreController.java index 2a196d9..d4414ee 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/StoreController.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/StoreController.java @@ -47,12 +47,12 @@ public class StoreController { } @GetMapping("cm-history") - public List<MessageDTO> getAllConfigurationChanges() { + public List<Message> getAllConfigurationChanges() { return service.getAllMessages(); } @GetMapping("/less") - public List<MessageDTO> less(@RequestParam(value = "offset", required = false, defaultValue = "${spring.kafka.default-offset}") long offset) { + public List<Message> less(@RequestParam(value = "offset", required = false, defaultValue = "${spring.kafka.default-offset}") long offset) { return service.getLastMessages(offset); } diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/StoreService.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/StoreService.java index 5fddff5..6bd8390 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/StoreService.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/StoreService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,6 +28,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.stereotype.Service; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; @@ -48,33 +49,33 @@ public class StoreService { this.consumerFactory = consumerFactory; } - List<MessageDTO> getAllMessages() { - List<MessageDTO> messages = new ArrayList<>(); - String clientID = Long.toString(Instant.now().getEpochSecond()); - try (Consumer<String, String> consumer = consumerFactory.createConsumer(clientID, clientID)) { + List<Message> getAllMessages() { + List<Message> messages = new ArrayList<>(); + String clientId = Long.toString(Instant.now().getEpochSecond()); + try (Consumer<String, String> consumer = consumerFactory.createConsumer(clientId, clientId)) { consumer.subscribe(TOPICS_TO_SUBSCRIBE); - ConsumerRecords<String, String> consumerRecords = consumer.poll(CONSUMING_DURATION_IN_MS); + ConsumerRecords<String, String> consumerRecords = pollConsumerRecords(consumer); consumerRecords.forEach( consumerRecord -> - messages.add(new MessageDTO(consumerRecord.timestamp(), consumerRecord.value()))); + messages.add(new Message(consumerRecord.timestamp(), consumerRecord.value()))); log.debug(String.format("consumed %d messages", consumerRecords.count())); - } + } return messages; } - List<MessageDTO> getLastMessages(long offset) { - List<MessageDTO> messages = new ArrayList<>(); + List<Message> getLastMessages(long offset) { + List<Message> messages = new ArrayList<>(); try (Consumer<String, String> consumer = createConsumer(offset)) { - ConsumerRecords<String, String> consumerRecords = consumer.poll(CONSUMING_DURATION_IN_MS); + ConsumerRecords<String, String> consumerRecords = pollConsumerRecords(consumer); consumerRecords.forEach(consumerRecord -> - messages.add(new MessageDTO(consumerRecord.timestamp(), consumerRecord.value()))); + messages.add(new Message(consumerRecord.timestamp(), consumerRecord.value()))); } return messages; } private Consumer<String, String> createConsumer(long offsetFromLastIndex) { - String clientID = Long.toString(Instant.now().getEpochSecond()); - Consumer<String, String> consumer = consumerFactory.createConsumer(clientID, clientID); + String clientId = Long.toString(Instant.now().getEpochSecond()); + Consumer<String, String> consumer = consumerFactory.createConsumer(clientId, clientId); consumer.subscribe(TOPICS_TO_SUBSCRIBE); seekConsumerTo(consumer, offsetFromLastIndex); return consumer; @@ -82,10 +83,14 @@ public class StoreService { private void seekConsumerTo(Consumer<String, String> consumer, long offsetFromLastIndex) { consumer.seekToEnd(consumer.assignment()); - consumer.poll(CONSUMING_DURATION_IN_MS); + pollConsumerRecords(consumer); TopicPartition topicPartition = consumer.assignment().iterator().next(); long topicCurrentSize = consumer.position(topicPartition); long indexToSeek = offsetFromLastIndex > topicCurrentSize ? 0 : topicCurrentSize - offsetFromLastIndex; consumer.seek(topicPartition, indexToSeek); } + + private ConsumerRecords<String, String> pollConsumerRecords(Consumer<String, String> consumer) { + return consumer.poll(Duration.ofMillis(CONSUMING_DURATION_IN_MS)); + } } diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerEntry.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerEntry.java index e3c04c9..501d36b 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerEntry.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerEntry.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,9 +27,9 @@ import org.springframework.kafka.listener.AbstractMessageListenerContainer; public class KafkaListenerEntry { private String clientId; - private AbstractMessageListenerContainer listenerContainer; + private AbstractMessageListenerContainer<String, String> listenerContainer; - public KafkaListenerEntry(String clientId, AbstractMessageListenerContainer listenerContainer) { + public KafkaListenerEntry(String clientId, AbstractMessageListenerContainer<String, String> listenerContainer) { this.clientId = clientId; this.listenerContainer = listenerContainer; } diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerHandler.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerHandler.java index 604315d..c3ce327 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerHandler.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,12 +22,9 @@ package org.onap.netconfsimulator.kafka.listener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.ConsumerFactory; - import org.springframework.kafka.listener.ContainerProperties; import org.springframework.kafka.listener.KafkaMessageListenerContainer; import org.springframework.kafka.listener.MessageListener; - - import org.springframework.kafka.support.TopicPartitionInitialOffset; import java.time.Instant; @@ -46,12 +43,12 @@ public class KafkaListenerHandler { } - public KafkaListenerEntry createKafkaListener(MessageListener messageListener, String topicName) { + public KafkaListenerEntry createKafkaListener(MessageListener<String, String> messageListener, String topicName) { String clientId = Long.toString(Instant.now().getEpochSecond()); ContainerProperties containerProperties = new ContainerProperties(topicName); containerProperties.setGroupId(clientId); KafkaMessageListenerContainer<String, String> listenerContainer = createListenerContainer(containerProperties, - topicName); + topicName); listenerContainer.setupMessageListener(messageListener); return new KafkaListenerEntry(clientId, listenerContainer); @@ -59,9 +56,9 @@ public class KafkaListenerHandler { KafkaMessageListenerContainer<String, String> createListenerContainer(ContainerProperties containerProperties, - String topicName) { + String topicName) { TopicPartitionInitialOffset config = new TopicPartitionInitialOffset(topicName, PARTITION, - NUMBER_OF_HISTORICAL_MESSAGES_TO_SHOW, RELATIVE_TO_CURRENT); + NUMBER_OF_HISTORICAL_MESSAGES_TO_SHOW, RELATIVE_TO_CURRENT); return new KafkaMessageListenerContainer<>(consumerFactory, containerProperties, config); } } diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationTO.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfiguration.java index e43ff69..51f31ae 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationTO.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfiguration.java @@ -25,7 +25,7 @@ import lombok.Getter; @Getter @AllArgsConstructor -public class NetconfConfigurationTO { +public class NetconfConfiguration { private String configuration; diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationService.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationService.java index 248aec4..8f6f0ba 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationService.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationService.java @@ -64,8 +64,8 @@ public class NetconfConfigurationService { public String editCurrentConfiguration(MultipartFile newConfiguration) throws IOException, JNCException { Element configurationElement = convertMultipartToXmlElement(newConfiguration); configurationEditor.editConfig(configurationElement); - - LOGGER.debug("Loading new configuration: \n{}", configurationElement.toXMLString()); + String configurationXmlString = configurationElement.toXMLString(); + LOGGER.debug("Loading new configuration: \n{}", configurationXmlString); return CONFIGURATION_HAS_BEEN_ACTIVATED; } diff --git a/netconfsimulator/src/main/java/org/onap/netconfsimulator/websocket/NetconfEndpoint.java b/netconfsimulator/src/main/java/org/onap/netconfsimulator/websocket/NetconfEndpoint.java index 5870ee1..5719214 100644 --- a/netconfsimulator/src/main/java/org/onap/netconfsimulator/websocket/NetconfEndpoint.java +++ b/netconfsimulator/src/main/java/org/onap/netconfsimulator/websocket/NetconfEndpoint.java @@ -84,11 +84,11 @@ class NetconfEndpoint extends Endpoint { private void addKafkaListener(RemoteEndpoint.Basic remoteEndpoint) { - MessageListener messageListener = new NetconfMessageListener(remoteEndpoint); + MessageListener<String, String> messageListener = new NetconfMessageListener(remoteEndpoint); KafkaListenerEntry kafkaListener = kafkaListenerHandler.createKafkaListener(messageListener, TOPIC_NAME); - AbstractMessageListenerContainer listenerContainer = kafkaListener.getListenerContainer(); + AbstractMessageListenerContainer<String,String> listenerContainer = kafkaListener.getListenerContainer(); listenerContainer.start(); entry = Optional.of(kafkaListener); } diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/EmbeddedKafkaConfig.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/EmbeddedKafkaConfig.java index 5ddf2b2..6d487b2 100644 --- a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/EmbeddedKafkaConfig.java +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/EmbeddedKafkaConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,7 @@ package org.onap.netconfsimulator.kafka; import java.util.Map; + import org.apache.kafka.clients.consumer.ConsumerConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -40,20 +41,20 @@ import static org.onap.netconfsimulator.kafka.StoreServiceTest.embeddedKafka; class EmbeddedKafkaConfig { @Bean - KafkaTemplate<String, String> kafkaTemplate(){ + KafkaTemplate<String, String> kafkaTemplate() { return new KafkaTemplate<>(producerFactory()); } @Bean @Autowired - ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(ConsumerFactory<String, String> consumerFactory){ + ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(ConsumerFactory<String, String> consumerFactory) { ConcurrentKafkaListenerContainerFactory<String, String> containerFactory = new ConcurrentKafkaListenerContainerFactory<>(); containerFactory.setConsumerFactory(consumerFactory); return containerFactory; } @Bean - ConsumerFactory<String, String> consumerFactory(){ + ConsumerFactory<String, String> consumerFactory() { Map<String, Object> consumerProperties = KafkaTestUtils.consumerProps("sender", "false", embeddedKafka.getEmbeddedKafka()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreControllerTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreControllerTest.java index 02eec12..bd6fd14 100644 --- a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreControllerTest.java +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreControllerTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,7 @@ package org.onap.netconfsimulator.kafka; import java.time.Instant; import java.util.List; + import org.assertj.core.api.Assertions; import org.assertj.core.util.Lists; import org.junit.Test; @@ -39,9 +40,9 @@ public class StoreControllerTest { private static final String MESSAGE_2 = "message 2"; private static final String MESSAGE_1 = "message 1"; - private static final List<MessageDTO> ALL_MESSAGES = Lists.newArrayList(new MessageDTO(Instant.now().getEpochSecond(), MESSAGE_1), - new MessageDTO(Instant.now().getEpochSecond(), MESSAGE_2), - new MessageDTO(Instant.now().getEpochSecond(), MESSAGE_3)); + private static final List<Message> ALL_MESSAGES = Lists.newArrayList(new Message(Instant.now().getEpochSecond(), MESSAGE_1), + new Message(Instant.now().getEpochSecond(), MESSAGE_2), + new Message(Instant.now().getEpochSecond(), MESSAGE_3)); @Mock private StoreService service; @@ -54,33 +55,33 @@ public class StoreControllerTest { public void lessShouldTakeAllMessagesTest() { when(service.getLastMessages(3)).thenReturn(ALL_MESSAGES); - List<MessageDTO> lessResponse = storeController.less(3); + List<Message> lessResponse = storeController.less(3); assertResponseContainsExpectedMessages(lessResponse, 3, MESSAGE_1, MESSAGE_2, MESSAGE_3); } @Test public void lessShouldTakeTwoMessagesTest() { - when(service.getLastMessages(2)).thenReturn(Lists.newArrayList(new MessageDTO(Instant.now().getEpochSecond(), MESSAGE_1))); + when(service.getLastMessages(2)).thenReturn(Lists.newArrayList(new Message(Instant.now().getEpochSecond(), MESSAGE_1))); - List<MessageDTO> lessResult = storeController.less(2); + List<Message> lessResult = storeController.less(2); assertResponseContainsExpectedMessages(lessResult, 1, MESSAGE_1); } @Test - public void shouldGetAllMessages(){ + public void shouldGetAllMessages() { when(service.getAllMessages()).thenReturn(ALL_MESSAGES); - List<MessageDTO> allMsgResult = storeController.getAllConfigurationChanges(); + List<Message> allMsgResult = storeController.getAllConfigurationChanges(); assertResponseContainsExpectedMessages(allMsgResult, 3, MESSAGE_1, MESSAGE_2, MESSAGE_3); } - private void assertResponseContainsExpectedMessages(List<MessageDTO> actualMessages, int expectedMessageCount, String... expectedMessages){ - Assertions.assertThat(actualMessages.stream().map(MessageDTO::getConfiguration)) - .hasSize(expectedMessageCount) - .containsExactly(expectedMessages); + private void assertResponseContainsExpectedMessages(List<Message> actualMessages, int expectedMessageCount, String... expectedMessages) { + Assertions.assertThat(actualMessages.stream().map(Message::getConfiguration)) + .hasSize(expectedMessageCount) + .containsExactly(expectedMessages); } } diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreServiceTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreServiceTest.java index fd36116..fdba959 100644 --- a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreServiceTest.java +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreServiceTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -59,38 +59,38 @@ public class StoreServiceTest { } @Test - public void testShouldReturnAllAvailableMessages(){ + public void testShouldReturnAllAvailableMessages() { - List<MessageDTO> actualMessages = service.getAllMessages(); + List<Message> actualMessages = service.getAllMessages(); assertResponseContainsExpectedMessages(actualMessages, 3, MESSAGE_1, MESSAGE_2, MESSAGE_3); } @Test - public void testShouldGetLastMessagesRespectingOffset(){ + public void testShouldGetLastMessagesRespectingOffset() { - List<MessageDTO> wantedLastMsg = service.getLastMessages(1L); + List<Message> wantedLastMsg = service.getLastMessages(1L); assertResponseContainsExpectedMessages(wantedLastMsg, 1, MESSAGE_3); } @Test - public void testShouldGetAll3Messages() { - List<MessageDTO> wantedLastMsgs = service.getLastMessages(3L); + public void testShouldGetAll3Messages() { + List<Message> wantedLastMsgs = service.getLastMessages(3L); assertResponseContainsExpectedMessages(wantedLastMsgs, 3, MESSAGE_1, MESSAGE_2, MESSAGE_3); } - private void prepareProducer(){ + private void prepareProducer() { kafkaTemplate.send("config", "message1"); kafkaTemplate.send("config", "message2"); kafkaTemplate.send("config", "message3"); } - private void assertResponseContainsExpectedMessages(List<MessageDTO> actualMessages, int expectedMessageCount, String... expectedMessages){ - assertThat(actualMessages.stream().map(MessageDTO::getConfiguration)) - .hasSize(expectedMessageCount) - .containsExactly(expectedMessages); + private void assertResponseContainsExpectedMessages(List<Message> actualMessages, int expectedMessageCount, String... expectedMessages) { + assertThat(actualMessages.stream().map(Message::getConfiguration)) + .hasSize(expectedMessageCount) + .containsExactly(expectedMessages); } } diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationReaderTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationReaderTest.java index a0a15b9..7095040 100644 --- a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationReaderTest.java +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationReaderTest.java @@ -65,7 +65,7 @@ class NetconfConfigurationReaderTest { } @Test - void properlyReadXML() throws IOException, JNCException { + void properlyReadXml() throws IOException, JNCException { when(netconfSession.getConfig()).thenReturn(nodeSet); when(nodeSet.toXMLString()).thenReturn(EXPECTED_STRING_XML); diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationServiceTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationServiceTest.java index 6da6572..f42ad84 100644 --- a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationServiceTest.java +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationServiceTest.java @@ -28,8 +28,10 @@ import static org.mockito.MockitoAnnotations.initMocks; import com.tailf.jnc.Element; import com.tailf.jnc.JNCException; + import java.io.IOException; import java.nio.file.Files; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -49,11 +51,11 @@ class NetconfConfigurationServiceTest { @InjectMocks NetconfConfigurationService service; - private static String CURRENT_CONFIG_XML_STRING = - "<config xmlns=\"http://onap.org/pnf-simulator\" xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" - + " <itemValue1>100</itemValue1>\n" - + " <itemValue2>200</itemValue2>\n" - + "</config>\n"; + private static String CURRENT_CONFIG_XML_STRING = + "<config xmlns=\"http://onap.org/pnf-simulator\" xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <itemValue1>100</itemValue1>\n" + + " <itemValue2>200</itemValue2>\n" + + "</config>\n"; @BeforeEach void setUp() { @@ -71,16 +73,16 @@ class NetconfConfigurationServiceTest { } @Test - void testShouldThrowExceptionWhenCurrentConfigurationDoesNotExists() throws IOException, JNCException{ + void testShouldThrowExceptionWhenCurrentConfigurationDoesNotExists() throws IOException, JNCException { when(reader.getRunningConfig()).thenThrow(JNCException.class); assertThatThrownBy(() -> service.getCurrentConfiguration()).isInstanceOf(JNCException.class); } @Test - void testShouldEditConfigurationSuccessfully() throws IOException, JNCException{ + void testShouldEditConfigurationSuccessfully() throws IOException, JNCException { byte[] bytes = - Files.readAllBytes(ResourceUtils.getFile("classpath:updatedConfig.xml").toPath()); + Files.readAllBytes(ResourceUtils.getFile("classpath:updatedConfig.xml").toPath()); MockMultipartFile editConfigXmlContent = new MockMultipartFile("editConfigXml", bytes); ArgumentCaptor<Element> elementCaptor = ArgumentCaptor.forClass(Element.class); doNothing().when(editor).editConfig(elementCaptor.capture()); @@ -93,7 +95,7 @@ class NetconfConfigurationServiceTest { @Test void testShouldRaiseExceptionWhenMultipartFileIsInvalidXmlFile() throws IOException { byte[] bytes = - Files.readAllBytes(ResourceUtils.getFile("classpath:invalidXmlFile.xml").toPath()); + Files.readAllBytes(ResourceUtils.getFile("classpath:invalidXmlFile.xml").toPath()); MockMultipartFile editConfigXmlContent = new MockMultipartFile("editConfigXml", bytes); assertThatThrownBy(() -> service.editCurrentConfiguration(editConfigXmlContent)).isInstanceOf(JNCException.class); diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/model/NetconfModelLoaderServiceTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/model/NetconfModelLoaderServiceTest.java index a10876b..8d26881 100644 --- a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/model/NetconfModelLoaderServiceTest.java +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/model/NetconfModelLoaderServiceTest.java @@ -61,7 +61,6 @@ class NetconfModelLoaderServiceTest { @Test void shouldSendMultipartToServer() throws IOException { //given - String loadModelAddress = modelLoaderService.getBackendAddress(); makeMockClientReturnStatusOk(httpClient, HttpPost.class); ArgumentCaptor<HttpPost> postArgumentCaptor = ArgumentCaptor.forClass(HttpPost.class); MultipartFile yangMmodel = mock(MultipartFile.class); @@ -69,6 +68,7 @@ class NetconfModelLoaderServiceTest { String moduleName = "moduleName"; when(yangMmodel.getInputStream()).thenReturn(getEmptyImputStream()); when(initialConfig.getInputStream()).thenReturn(getEmptyImputStream()); + String loadModelAddress = modelLoaderService.getBackendAddress(); //when LoadModelResponse response = modelLoaderService.loadYangModel(yangMmodel, initialConfig, moduleName); @@ -86,9 +86,9 @@ class NetconfModelLoaderServiceTest { void shouldSendDeleteRequestToServer() throws IOException { //given String yangModelName = "sampleModel"; - String deleteModelAddress = modelLoaderService.getDeleteAddress(yangModelName); makeMockClientReturnStatusOk(httpClient, HttpDelete.class); ArgumentCaptor<HttpDelete> deleteArgumentCaptor = ArgumentCaptor.forClass(HttpDelete.class); + String deleteModelAddress = modelLoaderService.getDeleteAddress(yangModelName); //when LoadModelResponse response = modelLoaderService.deleteYangModel(yangModelName); diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/NetconfEndpointTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/NetconfEndpointTest.java index c1484d4..e0bffc1 100644 --- a/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/NetconfEndpointTest.java +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/NetconfEndpointTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -74,7 +74,7 @@ class NetconfEndpointTest { @Test void shouldCreateKafkaListenerWhenClientInitializeConnection() { NetconfEndpoint netconfEndpoint = new NetconfEndpoint(kafkaListenerHandler); - AbstractMessageListenerContainer abstractMessageListenerContainer = getListenerContainer(); + AbstractMessageListenerContainer<String, String> abstractMessageListenerContainer = getListenerContainer(); when(session.getBasicRemote()).thenReturn(remoteEndpoint); KafkaListenerEntry kafkaListenerEntry = new KafkaListenerEntry("sampleGroupId", abstractMessageListenerContainer); @@ -93,7 +93,7 @@ class NetconfEndpointTest { @Test void shouldCloseListenerWhenClientDisconnects() { NetconfEndpoint netconfEndpoint = new NetconfEndpoint(kafkaListenerHandler); - AbstractMessageListenerContainer abstractMessageListenerContainer = getListenerContainer(); + AbstractMessageListenerContainer<String, String> abstractMessageListenerContainer = getListenerContainer(); netconfEndpoint.setEntry( Optional.of(new KafkaListenerEntry("sampleGroupId", abstractMessageListenerContainer)) ); netconfEndpoint.onClose(session, mock(CloseReason.class)); @@ -101,7 +101,7 @@ class NetconfEndpointTest { verify(abstractMessageListenerContainer).stop(); } - class TestAbstractMessageListenerContainer extends AbstractMessageListenerContainer { + class TestAbstractMessageListenerContainer extends AbstractMessageListenerContainer<String,String> { TestAbstractMessageListenerContainer(ContainerProperties containerProperties) { @@ -124,7 +124,7 @@ class NetconfEndpointTest { } } - private AbstractMessageListenerContainer getListenerContainer() { + private AbstractMessageListenerContainer<String, String> getListenerContainer() { ContainerProperties containerProperties = new ContainerProperties("config"); containerProperties.setGroupId("sample"); containerProperties.setMessageListener(mock(GenericMessageListener.class)); diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/message/NetconfMessageListenerTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/message/NetconfMessageListenerTest.java index bb040d1..c6e58c9 100644 --- a/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/message/NetconfMessageListenerTest.java +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/message/NetconfMessageListenerTest.java @@ -69,5 +69,7 @@ class NetconfMessageListenerTest { doThrow(new EncodeException("","")).when(remoteEndpoint).sendObject(any(KafkaMessage.class)); netconfMessageListener.onMessage(KAFKA_RECORD); + + verify(remoteEndpoint).sendObject(any(KafkaMessage.class)); } } diff --git a/pnfsimulator/Dockerfile b/pnfsimulator/Dockerfile index 7cadcf4..52e507c 100644 --- a/pnfsimulator/Dockerfile +++ b/pnfsimulator/Dockerfile @@ -1,4 +1,4 @@ -FROM docker.io/openjdk:8-jre-alpine +FROM docker.io/openjdk:11-jre-slim ARG VERSION=${version} diff --git a/pnfsimulator/integration/pom.xml b/pnfsimulator/integration/pom.xml index 2ab2dcf..5b8e738 100644 --- a/pnfsimulator/integration/pom.xml +++ b/pnfsimulator/integration/pom.xml @@ -25,7 +25,7 @@ <modelVersion>4.0.0</modelVersion> <parent> - <groupId>org.onap.simulator</groupId> + <groupId>org.onap.integration.simulators.pnf-simulator</groupId> <artifactId>integration-pnf-simulator</artifactId> <version>1.0.0-SNAPSHOT</version> </parent> @@ -39,8 +39,8 @@ </repositories> <properties> - <maven.compiler.source>1.8</maven.compiler.source> - <maven.compiler.target>1.8</maven.compiler.target> + <maven.compiler.source>11</maven.compiler.source> + <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> diff --git a/pnfsimulator/lombok.config b/pnfsimulator/lombok.config new file mode 100644 index 0000000..a23edb4 --- /dev/null +++ b/pnfsimulator/lombok.config @@ -0,0 +1,2 @@ +config.stopBubbling = true +lombok.addLombokGeneratedAnnotation = true
\ No newline at end of file diff --git a/pnfsimulator/pom.xml b/pnfsimulator/pom.xml index 320805e..436571d 100644 --- a/pnfsimulator/pom.xml +++ b/pnfsimulator/pom.xml @@ -37,30 +37,31 @@ <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <maven.compiler.source>1.8</maven.compiler.source> - <maven.compiler.target>1.8</maven.compiler.target> + <maven.compiler.source>11</maven.compiler.source> + <maven.compiler.target>11</maven.compiler.target> <maven.build.timestamp.format>yyyyMMdd'T'HHmmss</maven.build.timestamp.format> - <simulator.main.class>org.onap.pnfsimulator.Main</simulator.main.class> <docker.image.tag>latest</docker.image.tag> - <junit.jupiter.version>5.1.0</junit.jupiter.version> - <junit.vintage.version>5.1.0</junit.vintage.version> - <spring.boot.version>2.1.0.RELEASE</spring.boot.version> <docker.image.name>onap/${project.artifactId}</docker.image.name> - <dependency.directory.name>libs</dependency.directory.name> <dependency.directory.location>${project.build.directory}/${dependency.directory.name} </dependency.directory.location> - <onap.nexus.dockerregistry.daily>nexus3.onap.org:10003</onap.nexus.dockerregistry.daily> <onap.nexus.url>http://nexus3.onap.org</onap.nexus.url> + <maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version> + <maven-jar-plugin.version>3.0.2</maven-jar-plugin.version> + <git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version> + <maven-surefire-plugin.version>2.19</maven-surefire-plugin.version> + <junit-platform-surefire-provider.version>1.1.1</junit-platform-surefire-provider.version> </properties> <dependencies> - <dependency> - <groupId>org.springframework.boot</groupId> + + <!-- Compile DEPENDENCIES --> + + <dependency> + <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> - <version>${spring.boot.version}</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> @@ -71,158 +72,131 @@ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> - <version>${spring.boot.version}</version> </dependency> <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-mongodb</artifactId> - <version>${spring.boot.version}</version> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> - <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-client</artifactId> - <version>2.1.4.RELEASE</version> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <scope>provided</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> - <version>1.2.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> - <version>1.2.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> - <version>1.7.25</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> - <version>2.6</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> - <version>20180130</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> - <version>2.8.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> - <version>4.5.5</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> - <version>21.0</version> </dependency> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> - <version>1.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> - <version>3.7</version> - </dependency> - <dependency> - <groupId>org.projectlombok</groupId> - <artifactId>lombok</artifactId> - <version>1.18.2</version> - <scope>provided</scope> </dependency> + <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jdk8</artifactId> - <version>2.9.7</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> - <version>2.9.7</version> </dependency> <dependency> - <groupId>io.vavr</groupId> - <artifactId>vavr-match</artifactId> - <version>0.9.2</version> + <groupId>io.vavr</groupId> + <artifactId>vavr-match</artifactId> + </dependency> + <dependency> + <groupId>io.vavr</groupId> + <artifactId>vavr</artifactId> + </dependency> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger2</artifactId> + </dependency> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger-ui</artifactId> + </dependency> + <dependency> + <groupId>org.quartz-scheduler</groupId> + <artifactId>quartz</artifactId> + </dependency> + <dependency> + <groupId>org.quartz-scheduler</groupId> + <artifactId>quartz-jobs</artifactId> </dependency> - <dependency> - <groupId>io.vavr</groupId> - <artifactId>vavr</artifactId> - <version>0.9.2</version> - </dependency> + <!-- TEST DEPENDENCIES --> - <dependency> + <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> - <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-migrationsupport</artifactId> - <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> - <version>3.9.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> - <version>2.18.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> - <version>5.0.4.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> - <version>${spring.boot.version}</version> <scope>test</scope> </dependency> - <dependency> - <groupId>io.springfox</groupId> - <artifactId>springfox-swagger2</artifactId> - <version>2.9.2</version> - </dependency> - <dependency> - <groupId>io.springfox</groupId> - <artifactId>springfox-swagger-ui</artifactId> - <version>2.9.2</version> - </dependency> - <dependency> - <groupId>org.quartz-scheduler</groupId> - <artifactId>quartz</artifactId> - <version>2.2.1</version> - </dependency> - <dependency> - <groupId>org.quartz-scheduler</groupId> - <artifactId>quartz-jobs</artifactId> - <version>2.2.1</version> - </dependency> - </dependencies> + </dependencies> <build> <plugins> <plugin> @@ -244,7 +218,7 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> - <version>3.7.0</version> + <version>${maven-compiler-plugin.version}</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> @@ -255,7 +229,7 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> - <version>3.0.2</version> + <version>${maven-jar-plugin.version}</version> <configuration> <archive> <manifestEntries> @@ -268,7 +242,7 @@ <plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> - <version>2.2.4</version> + <version>${git-commit-id-plugin.version}</version> <executions> <execution> <id>get-commit-info</id> @@ -285,12 +259,12 @@ </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> - <version>2.19</version> + <version>${maven-surefire-plugin.version}</version> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> - <version>1.1.1</version> + <version>${junit-platform-surefire-provider.version}</version> </dependency> </dependencies> <configuration> diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java index e0eace2..708f27f 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java @@ -43,7 +43,9 @@ public class Main { this.fsToDbTemplateSynchronizer = fsToDbTemplateSynchronizer; } - public static void main(String[] args) { + // We are excluding this line in Sonar due to fact that + // Spring is handling arguments + public static void main(String[] args) { // NOSONAR SpringApplication.run(Main.class, args); } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/SwaggerConfig.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/SwaggerConfig.java index 6e0e18e..b6c6187 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/SwaggerConfig.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/SwaggerConfig.java @@ -20,7 +20,7 @@ package org.onap.pnfsimulator; -import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,7 +31,7 @@ import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration -@EnableConfigurationProperties(SSLAuthenticationHelper.class) +@EnableConfigurationProperties(SslAuthenticationHelper.class) @EnableSwagger2 public class SwaggerConfig { diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/db/Row.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/db/Row.java index f9a167b..12745bf 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/db/Row.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/db/Row.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,15 +20,20 @@ package org.onap.pnfsimulator.db; +import lombok.Getter; +import lombok.Setter; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Field; public abstract class Row { - @Id - @Field("_id") - protected String id; + @Id + @Field("_id") + @Getter + @Setter + private String id; - public String getId() { - return id; - } + + public String getId() { + return id; + } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/event/EventData.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/event/EventData.java index 23b1c21..ff85367 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/event/EventData.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/event/EventData.java @@ -24,12 +24,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Builder; import lombok.Getter; import lombok.Setter; +import lombok.ToString; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Field; @Builder @Getter @Setter +@ToString(exclude = "incrementValue") public class EventData { @Id private String id; @@ -62,15 +64,4 @@ public class EventData { this.keywords = keywords; this.incrementValue = incrementValue; } - - @Override - public String toString() { - return "EventData{" - + "id='" + id + '\'' - + ", template='" + template + '\'' - + ", patched='" + patched + '\'' - + ", input='" + input + '\'' - + ", keywords='" + keywords + '\'' - + '}'; - } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/event/EventDataService.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/event/EventDataService.java index 3568f01..266d56b 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/event/EventDataService.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/event/EventDataService.java @@ -21,43 +21,45 @@ package org.onap.pnfsimulator.event; import com.google.gson.JsonObject; + import java.util.List; import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class EventDataService { - private final EventDataRepository repository; - - @Autowired - public EventDataService(EventDataRepository repository) { - this.repository = repository; - } - - private EventData persistEventData(String templateString, String patchedString, String inputString, String keywordsString) { - EventData eventData = EventData.builder() - .template(templateString) - .patched(patchedString) - .input(inputString) - .keywords(keywordsString) - .build(); - return repository.save(eventData); - } - - public EventData persistEventData(JsonObject templateJson, JsonObject patchedJson, JsonObject inputJson, - JsonObject keywordsJson) { - return persistEventData(templateJson.toString(), - patchedJson.toString(), - inputJson.toString(), - keywordsJson.toString()); - } - - public List<EventData> getAllEvents() { - return repository.findAll(); - } - - public Optional<EventData> getById(String id) { - return repository.findById(id); - } + private final EventDataRepository repository; + + @Autowired + public EventDataService(EventDataRepository repository) { + this.repository = repository; + } + + private EventData persistEventData(String templateString, String patchedString, String inputString, String keywordsString) { + EventData eventData = EventData.builder() + .template(templateString) + .patched(patchedString) + .input(inputString) + .keywords(keywordsString) + .build(); + return repository.save(eventData); + } + + public EventData persistEventData(JsonObject templateJson, JsonObject patchedJson, JsonObject inputJson, + JsonObject keywordsJson) { + return persistEventData(templateJson.toString(), + patchedJson.toString(), + inputJson.toString(), + keywordsJson.toString()); + } + + public List<EventData> getAllEvents() { + return repository.findAll(); + } + + public Optional<EventData> getById(String id) { + return repository.findById(id); + } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MdcVariables.java index 5678f4f..4feb168 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MdcVariables.java @@ -20,7 +20,7 @@ package org.onap.pnfsimulator.logging; -public final class MDCVariables { +public final class MdcVariables { public static final String X_ONAP_REQUEST_ID = "X-ONAP-RequestID"; public static final String X_INVOCATION_ID = "X-InvocationID"; @@ -30,6 +30,6 @@ public final class MDCVariables { public static final String RESPONSE_CODE = "ResponseCode"; public static final String SERVICE_NAME = "ServiceName"; - private MDCVariables() { + private MdcVariables() { } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java index 0e4bd56..023b163 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java @@ -52,7 +52,6 @@ import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.io.IOException; -import java.net.MalformedURLException; import java.security.GeneralSecurityException; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -60,13 +59,13 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import static org.onap.pnfsimulator.logging.MDCVariables.INSTANCE_UUID; -import static org.onap.pnfsimulator.logging.MDCVariables.INVOCATION_ID; -import static org.onap.pnfsimulator.logging.MDCVariables.REQUEST_ID; -import static org.onap.pnfsimulator.logging.MDCVariables.RESPONSE_CODE; -import static org.onap.pnfsimulator.logging.MDCVariables.SERVICE_NAME; -import static org.onap.pnfsimulator.logging.MDCVariables.X_INVOCATION_ID; -import static org.onap.pnfsimulator.logging.MDCVariables.X_ONAP_REQUEST_ID; +import static org.onap.pnfsimulator.logging.MdcVariables.INSTANCE_UUID; +import static org.onap.pnfsimulator.logging.MdcVariables.INVOCATION_ID; +import static org.onap.pnfsimulator.logging.MdcVariables.REQUEST_ID; +import static org.onap.pnfsimulator.logging.MdcVariables.RESPONSE_CODE; +import static org.onap.pnfsimulator.logging.MdcVariables.SERVICE_NAME; +import static org.onap.pnfsimulator.logging.MdcVariables.X_INVOCATION_ID; +import static org.onap.pnfsimulator.logging.MdcVariables.X_ONAP_REQUEST_ID; import static org.onap.pnfsimulator.rest.util.ResponseBuilder.MESSAGE; import static org.onap.pnfsimulator.rest.util.ResponseBuilder.TIMESTAMP; import static org.springframework.http.HttpStatus.ACCEPTED; @@ -83,6 +82,7 @@ public class SimulatorController { private static final Marker ENTRY = MarkerFactory.getMarker("ENTRY"); private static final String INCORRECT_TEMPLATE_MESSAGE = "Cannot start simulator, template %s is not in valid format: %s"; private static final String NOT_EXISTING_TEMPLATE = "Cannot start simulator - template %s not found."; + private static final String BREAKING_CHARACTER_REGEX = "[\n|\r|\t]"; private final DateFormat responseDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss,SSS"); private final SimulatorService simulatorService; private EventDataService eventDataService; @@ -94,16 +94,20 @@ public class SimulatorController { this.eventDataService = eventDataService; } + /** + * @deprecated + */ @PostMapping("test") @Deprecated - public ResponseEntity test(@Valid @RequestBody SimulatorRequest simulatorRequest) { + public ResponseEntity<Map<String,Object>> test(@Valid @RequestBody SimulatorRequest simulatorRequest) { MDC.put("test", "test"); - LOGGER.info(ENTRY, simulatorRequest.toString()); + String simulatorRequestString = simulatorRequest.toString(); + LOGGER.info(ENTRY, simulatorRequestString); return buildResponse(OK, ImmutableMap.of(MESSAGE, "message1234")); } @PostMapping(value = "start") - public ResponseEntity start(@RequestHeader HttpHeaders headers, + public ResponseEntity<Map<String,Object>> start(@RequestHeader HttpHeaders headers, @Valid @RequestBody SimulatorRequest triggerEventRequest) { logContextHeaders(headers, "/simulator/start"); LOGGER.info(ENTRY, "Simulator started"); @@ -118,13 +122,12 @@ public class SimulatorController { return buildResponse(BAD_REQUEST, ImmutableMap.of(MESSAGE, String .format(INCORRECT_TEMPLATE_MESSAGE, triggerEventRequest.getTemplateName(), e.getMessage()))); - } catch (GeneralSecurityException e ){ - MDC.put(RESPONSE_CODE, INTERNAL_SERVER_ERROR.toString() ); + } catch (GeneralSecurityException e) { + MDC.put(RESPONSE_CODE, INTERNAL_SERVER_ERROR.toString()); LOGGER.error("Client certificate validation failed: {}", e.getMessage()); return buildResponse(INTERNAL_SERVER_ERROR, ImmutableMap.of(MESSAGE, "Invalid or misconfigured client certificate")); - } - catch (IOException e) { + } catch (IOException e) { MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); LOGGER.warn("Json validation failed: {}", e.getMessage()); return buildResponse(BAD_REQUEST, @@ -139,9 +142,12 @@ public class SimulatorController { } } + /** + * @deprecated + */ @GetMapping("all-events") @Deprecated - public ResponseEntity allEvents() { + public ResponseEntity<Map<String,Object>> allEvents() { List<EventData> eventDataList = eventDataService.getAllEvents(); StringBuilder sb = new StringBuilder(); eventDataList.forEach(e -> sb.append(e).append(System.lineSeparator())); @@ -152,41 +158,46 @@ public class SimulatorController { } @GetMapping("config") - public ResponseEntity getConfig() { + public ResponseEntity<Map<String,Object>> getConfig() { SimulatorConfig configToGet = simulatorService.getConfiguration(); return buildResponse(OK, ImmutableMap.of("simulatorConfig", configToGet)); } @PutMapping("config") - public ResponseEntity updateConfig(@Valid @RequestBody SimulatorConfig newConfig) { + public ResponseEntity<Map<String,Object>> updateConfig(@Valid @RequestBody SimulatorConfig newConfig) { SimulatorConfig updatedConfig = simulatorService.updateConfiguration(newConfig); return buildResponse(OK, ImmutableMap.of("simulatorConfig", updatedConfig)); } @PostMapping("cancel/{jobName}") - public ResponseEntity cancelEvent(@PathVariable String jobName) throws SchedulerException { - LOGGER.info(ENTRY, "Cancel called on {}.", jobName); + public ResponseEntity<Map<String,Object>> cancelEvent(@PathVariable String jobName) throws SchedulerException { + String jobNameNoBreakingCharacters = replaceBreakingCharacters(jobName); + LOGGER.info(ENTRY, "Cancel called on {}.", jobNameNoBreakingCharacters); boolean isCancelled = simulatorService.cancelEvent(jobName); return createCancelEventResponse(isCancelled); } @PostMapping("cancel") - public ResponseEntity cancelAllEvent() throws SchedulerException { + public ResponseEntity<Map<String,Object>> cancelAllEvent() throws SchedulerException { LOGGER.info(ENTRY, "Cancel called on all jobs"); boolean isCancelled = simulatorService.cancelAllEvents(); return createCancelEventResponse(isCancelled); } @PostMapping("event") - public ResponseEntity sendEventDirectly(@RequestHeader HttpHeaders headers, @Valid @RequestBody FullEvent event) - throws IOException, GeneralSecurityException{ + public ResponseEntity<Map<String,Object>> sendEventDirectly(@RequestHeader HttpHeaders headers, @Valid @RequestBody FullEvent event) + throws IOException, GeneralSecurityException { logContextHeaders(headers, "/simulator/event"); LOGGER.info(ENTRY, "Trying to send one-time event directly to VES Collector"); simulatorService.triggerOneTimeEvent(event); return buildResponse(ACCEPTED, ImmutableMap.of(MESSAGE, "One-time direct event sent successfully")); } - private ResponseEntity processRequest(SimulatorRequest triggerEventRequest) + private String replaceBreakingCharacters(String jobName) { + return jobName.replaceAll(BREAKING_CHARACTER_REGEX, "_"); + } + + private ResponseEntity<Map<String,Object>> processRequest(SimulatorRequest triggerEventRequest) throws IOException, SchedulerException, GeneralSecurityException { String jobName = simulatorService.triggerEvent(triggerEventRequest); @@ -194,7 +205,7 @@ public class SimulatorController { return buildResponse(OK, ImmutableMap.of(MESSAGE, "Request started", "jobName", jobName)); } - private ResponseEntity buildResponse(HttpStatus endStatus, Map<String, Object> parameters) { + private ResponseEntity<Map<String,Object>> buildResponse(HttpStatus endStatus, Map<String, Object> parameters) { ResponseBuilder builder = ResponseBuilder .status(endStatus) .put(TIMESTAMP, DateUtil.getTimestamp(responseDateFormat)); @@ -209,7 +220,7 @@ public class SimulatorController { MDC.put(SERVICE_NAME, serviceName); } - private ResponseEntity createCancelEventResponse(boolean isCancelled) { + private ResponseEntity<Map<String,Object>> createCancelEventResponse(boolean isCancelled) { if (isCancelled) { return buildResponse(OK, ImmutableMap.of(MESSAGE, "Event(s) was cancelled")); } else { diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/TemplateController.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/TemplateController.java index 444e23b..7eaa9ff 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/TemplateController.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/TemplateController.java @@ -30,8 +30,6 @@ import org.onap.pnfsimulator.rest.model.TemplateRequest; import org.onap.pnfsimulator.rest.model.SearchExp; import org.onap.pnfsimulator.template.Template; import org.onap.pnfsimulator.template.search.IllegalJsonValueException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -53,7 +51,6 @@ public class TemplateController { static final String TEMPLATE_NOT_FOUND_MSG = "A template with given name does not exist"; static final String CANNOT_OVERRIDE_TEMPLATE_MSG = "Cannot overwrite existing template. Use override=true to override"; private final Storage<Template> service; - private static final Logger LOG = LoggerFactory.getLogger(TemplateController.class); @Autowired public TemplateController(Storage<Template> service) { @@ -61,7 +58,7 @@ public class TemplateController { } @GetMapping("list") - public ResponseEntity<?> list() { + public ResponseEntity<List<Template>> list() { return new ResponseEntity<>(service.getAll(), HttpStatus.OK); } @@ -77,7 +74,7 @@ public class TemplateController { } @PostMapping("upload") - public ResponseEntity<?> upload( + public ResponseEntity<String> upload( @RequestBody @Valid TemplateRequest templateRequest, @RequestParam(required = false) boolean override) { String msg = ""; @@ -91,7 +88,7 @@ public class TemplateController { } @PostMapping("search") - public ResponseEntity<?> searchByCriteria(@RequestBody SearchExp queryJson) { + public ResponseEntity<List<String>> searchByCriteria(@RequestBody SearchExp queryJson) { try { List<String> templateNames = service.getIdsByContentCriteria(queryJson.getSearchExpr()); return new ResponseEntity<>(templateNames, HttpStatus.OK); diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java index 5fca25a..1fdd7cf 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java @@ -50,7 +50,7 @@ public class ResponseBuilder { return this; } - public ResponseEntity build() { + public ResponseEntity<Map<String,Object>> build() { if (body.isEmpty()) { return ResponseEntity.status(httpStatus).build(); diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/DBTemplateReader.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/DbTemplateReader.java index 6c11254..878591b 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/DBTemplateReader.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/DbTemplateReader.java @@ -23,27 +23,29 @@ package org.onap.pnfsimulator.simulator; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; + import java.io.IOException; + import org.onap.pnfsimulator.template.Template; import org.onap.pnfsimulator.template.TemplateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class DBTemplateReader implements TemplateReader { - private final TemplateService service; - private final Gson gson; +public class DbTemplateReader implements TemplateReader { + private final TemplateService service; + private final Gson gson; - @Autowired - public DBTemplateReader(TemplateService service, Gson gson) { - this.service = service; - this.gson = gson; - } + @Autowired + public DbTemplateReader(TemplateService service, Gson gson) { + this.service = service; + this.gson = gson; + } - @Override - public JsonObject readTemplate(String templateName) throws IOException { - Template template = service.get(templateName).orElseThrow(() -> new IOException("Template does not exist")); - JsonElement jsonElement = gson.toJsonTree(template.getContent()); - return jsonElement.getAsJsonObject(); - } + @Override + public JsonObject readTemplate(String templateName) throws IOException { + Template template = service.get(templateName).orElseThrow(() -> new IOException("Template does not exist")); + JsonElement jsonElement = gson.toJsonTree(template.getContent()); + return jsonElement.getAsJsonObject(); + } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/EventNotFoundException.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/EventNotFoundException.java index 4f43d8c..01f6508 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/EventNotFoundException.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/EventNotFoundException.java @@ -21,8 +21,9 @@ package org.onap.pnfsimulator.simulator; public class EventNotFoundException extends RuntimeException { - private static final String NOT_FOUND = "Not found an event with id: "; - public EventNotFoundException(String eventId) { - super(NOT_FOUND + eventId); - } + private static final String NOT_FOUND = "Not found an event with id: "; + + public EventNotFoundException(String eventId) { + super(NOT_FOUND + eventId); + } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/IncrementProvider.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/IncrementProvider.java index ea87ae6..4a7cf02 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/IncrementProvider.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/IncrementProvider.java @@ -22,5 +22,5 @@ package org.onap.pnfsimulator.simulator; @FunctionalInterface public interface IncrementProvider { - int getAndIncrement(String id); + int getAndIncrement(String id); } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/IncrementProviderImpl.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/IncrementProviderImpl.java index 16c0a0e..9d4d3ec 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/IncrementProviderImpl.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/IncrementProviderImpl.java @@ -27,21 +27,21 @@ import org.springframework.stereotype.Service; @Service public class IncrementProviderImpl implements IncrementProvider { - private final EventDataRepository repository; + private final EventDataRepository repository; - @Autowired - public IncrementProviderImpl(EventDataRepository repository) { - this.repository = repository; - } + @Autowired + public IncrementProviderImpl(EventDataRepository repository) { + this.repository = repository; + } - @Override - public int getAndIncrement(String id) { - EventData eventData = repository.findById(id) - .orElseThrow(() -> new EventNotFoundException(id)); - int value = eventData.getIncrementValue() + 1; - eventData.setIncrementValue(value); - repository.save(eventData); - return value; - } + @Override + public int getAndIncrement(String id) { + EventData eventData = repository.findById(id) + .orElseThrow(() -> new EventNotFoundException(id)); + int value = eventData.getIncrementValue() + 1; + eventData.setIncrementValue(value); + repository.save(eventData); + return value; + } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/KeywordsExtractor.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/KeywordsExtractor.java index 23c383f..2dc52a1 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/KeywordsExtractor.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/KeywordsExtractor.java @@ -32,6 +32,7 @@ import static org.onap.pnfsimulator.simulator.KeywordsValueProvider.getTimestamp import static org.onap.pnfsimulator.simulator.keywords.NonParameterKeywordPatterns.$nonParameterKeyword; import static org.onap.pnfsimulator.simulator.keywords.SingleParameterKeywordPatterns.$singleParameterKeyword; import static org.onap.pnfsimulator.simulator.keywords.TwoParameterKeywordPatterns.$twoParameterKeyword; + import io.vavr.API.Match.Pattern1; import org.onap.pnfsimulator.simulator.keywords.Keyword; import org.onap.pnfsimulator.simulator.keywords.NonParameterKeyword; @@ -44,43 +45,53 @@ public class KeywordsExtractor { String substituteStringKeyword(String text, int increment) { return Match(text).of( - Case(isRandomStringParamKeyword(), - spk -> spk.substituteKeyword(getRandomString().apply(spk.getAdditionalParameter()))), - Case(isRandomStringNonParamKeyword(), - npk -> npk.substituteKeyword(getRandomLimitedString().apply())), - Case(isRandomIntegerParamKeyword(), - tpk -> tpk.substituteKeyword(getRandomInteger().apply(tpk.getAdditionalParameter1(), tpk.getAdditionalParameter2()))), - Case(isRandomIntegerNonParamKeyword(), - npk -> npk.substituteKeyword(getRandomLimitedInteger().apply())), - Case(isIncrementKeyword(), - ik -> ik.substituteKeyword(String.valueOf(increment))), - Case(isTimestampNonParamKeyword(), - npk -> npk.substituteKeyword(getEpochSecond().apply())), - Case( - $(), - () -> text - )); + Case(isRandomStringParamKeyword(), + spk -> spk.substituteKeyword(getRandomString().apply(spk.getAdditionalParameter())) + ), + Case(isRandomStringNonParamKeyword(), + npk -> npk.substituteKeyword(getRandomLimitedString().apply()) + ), + Case(isRandomIntegerParamKeyword(), + tpk -> tpk.substituteKeyword(getRandomInteger().apply( + tpk.getAdditionalParameter1(), + tpk.getAdditionalParameter2() + ) + ) + ), + Case(isRandomIntegerNonParamKeyword(), + npk -> npk.substituteKeyword(getRandomLimitedInteger().apply()) + ), + Case(isIncrementKeyword(), + ik -> ik.substituteKeyword(String.valueOf(increment)) + ), + Case(isTimestampNonParamKeyword(), + npk -> npk.substituteKeyword(getEpochSecond().apply()) + ), + Case( + $(), + () -> text + )); } Long substitutePrimitiveKeyword(String text) { return Match(text).of( - Case(isRandomPrimitiveIntegerParamKeyword(), - tpk -> - getRandomPrimitiveInteger().apply(tpk.getAdditionalParameter1(), tpk.getAdditionalParameter2())), - Case(isTimestampPrimitiveNonParamKeyword(), - tpk -> - getTimestampPrimitive().apply()), - Case( - $(), - () -> 0L - )); + Case(isRandomPrimitiveIntegerParamKeyword(), + tpk -> + getRandomPrimitiveInteger().apply(tpk.getAdditionalParameter1(), tpk.getAdditionalParameter2())), + Case(isTimestampPrimitiveNonParamKeyword(), + tpk -> + getTimestampPrimitive().apply()), + Case( + $(), + () -> 0L + )); } boolean isPrimitive(String text) { return Match(text).of( - Case(isRandomPrimitiveIntegerParamKeyword(), () -> true), - Case(isTimestampPrimitiveNonParamKeyword(), () -> true), - Case($(), () -> false)); + Case(isRandomPrimitiveIntegerParamKeyword(), () -> true), + Case(isTimestampPrimitiveNonParamKeyword(), () -> true), + Case($(), () -> false)); } private Pattern1<String, SingleParameterKeyword> isRandomStringParamKeyword() { diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorService.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorService.java index 155c0ff..02f50e4 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorService.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorService.java @@ -22,10 +22,6 @@ package org.onap.pnfsimulator.simulator; import com.google.common.base.Strings; import com.google.gson.JsonObject; -import java.io.IOException; -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.Optional; import org.onap.pnfsimulator.event.EventData; import org.onap.pnfsimulator.event.EventDataService; import org.onap.pnfsimulator.rest.model.FullEvent; @@ -33,7 +29,7 @@ import org.onap.pnfsimulator.rest.model.SimulatorParams; import org.onap.pnfsimulator.rest.model.SimulatorRequest; import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; import org.onap.pnfsimulator.simulator.client.HttpClientAdapterImpl; -import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; import org.onap.pnfsimulator.simulator.scheduler.EventScheduler; import org.onap.pnfsimulator.simulatorconfig.SimulatorConfig; import org.onap.pnfsimulator.simulatorconfig.SimulatorConfigService; @@ -41,6 +37,10 @@ import org.quartz.SchedulerException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Optional; + @Service public class SimulatorService { @@ -48,14 +48,14 @@ public class SimulatorService { private final TemplateReader templateReader; private final EventDataService eventDataService; private final EventScheduler eventScheduler; - private final SSLAuthenticationHelper sslAuthenticationHelper; + private final SslAuthenticationHelper sslAuthenticationHelper; private SimulatorConfigService simulatorConfigService; private static final JsonObject EMPTY_JSON_OBJECT = new JsonObject(); @Autowired public SimulatorService(TemplatePatcher templatePatcher, TemplateReader templateReader, EventScheduler eventScheduler, EventDataService eventDataService, - SimulatorConfigService simulatorConfigService, SSLAuthenticationHelper sslAuthenticationHelper) { + SimulatorConfigService simulatorConfigService, SslAuthenticationHelper sslAuthenticationHelper) { this.templatePatcher = templatePatcher; this.templateReader = templateReader; this.eventDataService = eventDataService; diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/TemplateReader.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/TemplateReader.java index bf06381..2471c08 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/TemplateReader.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/TemplateReader.java @@ -21,8 +21,9 @@ package org.onap.pnfsimulator.simulator; import com.google.gson.JsonObject; + import java.io.IOException; public interface TemplateReader { - JsonObject readTemplate(String templateName) throws IOException; + JsonObject readTemplate(String templateName) throws IOException; } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java index 6ea1157..7ddef86 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java @@ -20,22 +20,13 @@ package org.onap.pnfsimulator.simulator.client; -import static org.onap.pnfsimulator.logging.MDCVariables.REQUEST_ID; -import static org.onap.pnfsimulator.logging.MDCVariables.X_INVOCATION_ID; -import static org.onap.pnfsimulator.logging.MDCVariables.X_ONAP_REQUEST_ID; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.GeneralSecurityException; -import java.util.UUID; - import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; -import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; import org.onap.pnfsimulator.simulator.client.utils.ssl.SslSupportLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +34,15 @@ import org.slf4j.MDC; import org.slf4j.Marker; import org.slf4j.MarkerFactory; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.util.UUID; + +import static org.onap.pnfsimulator.logging.MdcVariables.REQUEST_ID; +import static org.onap.pnfsimulator.logging.MdcVariables.X_INVOCATION_ID; +import static org.onap.pnfsimulator.logging.MdcVariables.X_ONAP_REQUEST_ID; + public class HttpClientAdapterImpl implements HttpClientAdapter { private static final int CONNECTION_TIMEOUT = 1000; @@ -55,14 +55,15 @@ public class HttpClientAdapterImpl implements HttpClientAdapter { .setSocketTimeout(CONNECTION_TIMEOUT) .build(); private static final Marker INVOKE = MarkerFactory.getMarker("INVOKE"); - private SslSupportLevel sslSupportLevel; + private SslSupportLevel sslSupportLevel; private HttpClient client; private final String targetUrl; - public HttpClientAdapterImpl(String targetUrl, SSLAuthenticationHelper sslAuthenticationHelper) + public HttpClientAdapterImpl(String targetUrl, SslAuthenticationHelper sslAuthenticationHelper) throws IOException, GeneralSecurityException { - this.sslSupportLevel = sslAuthenticationHelper.isClientCertificateEnabled() ? - SslSupportLevel.CLIENT_CERT_AUTH : SslSupportLevel.getSupportLevelBasedOnProtocol(targetUrl); + this.sslSupportLevel = sslAuthenticationHelper.isClientCertificateEnabled() + ? SslSupportLevel.CLIENT_CERT_AUTH + : SslSupportLevel.getSupportLevelBasedOnProtocol(targetUrl); this.client = sslSupportLevel.getClient(CONFIG, sslAuthenticationHelper); this.targetUrl = targetUrl; } @@ -82,11 +83,11 @@ public class HttpClientAdapterImpl implements HttpClientAdapter { EntityUtils.consumeQuietly(response.getEntity()); LOGGER.info(INVOKE, "Message sent, ves response code: {}", response.getStatusLine()); } catch (IOException e) { - LOGGER.warn("Error sending message to ves: " + e.getMessage(), e.getCause()); + LOGGER.warn("Error sending message to ves: {}", e.getMessage(), e.getCause()); } } - public SslSupportLevel getSslSupportLevel(){ + public SslSupportLevel getSslSupportLevel() { return sslSupportLevel; } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SSLAuthenticationHelper.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslAuthenticationHelper.java index eda17ef..ee5fdb7 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SSLAuthenticationHelper.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslAuthenticationHelper.java @@ -29,7 +29,7 @@ import org.springframework.stereotype.Component; @ConfigurationProperties(prefix = "ssl") @RefreshScope @Primary -public class SSLAuthenticationHelper implements Serializable { +public class SslAuthenticationHelper implements Serializable { private boolean clientCertificateEnabled; private String clientCertificateDir; diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevel.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevel.java index 264a7d1..393a6c5 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevel.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevel.java @@ -40,16 +40,13 @@ import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; -import java.security.KeyManagementException; import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; import java.util.Optional; public enum SslSupportLevel { NONE { - public HttpClient getClient(RequestConfig requestConfig, SSLAuthenticationHelper sslAuthenticationHelper) { + public HttpClient getClient(RequestConfig requestConfig, SslAuthenticationHelper sslAuthenticationHelper) { LOGGER.info("<!-----IN SslSupportLevel.NONE, Creating BasicHttpClient for http protocol----!>"); return HttpClientBuilder .create() @@ -58,7 +55,7 @@ public enum SslSupportLevel { } }, ALWAYS_TRUST { - public HttpClient getClient(RequestConfig requestConfig, SSLAuthenticationHelper sslAuthenticationHelper) + public HttpClient getClient(RequestConfig requestConfig, SslAuthenticationHelper sslAuthenticationHelper) throws GeneralSecurityException, IOException { LoggerFactory.getLogger(SslSupportLevel.class).info("<!-----IN SslSupportLevel.ALWAYS_TRUST, Creating client with SSL support for https protocol----!>"); HttpClient client; @@ -71,7 +68,7 @@ public enum SslSupportLevel { .build(); } catch (GeneralSecurityException e) { - LOGGER.error("Could not initialize client due to SSL exception: {}. Default client without SSL support will be used instead.\nCause: {}", e.getMessage(), e.getCause()); + LOGGER.error("Could not initialize client due to SSL exception: {}. Default client without SSL support will be used instead.\nCause: {}", e.getMessage(), e.getCause().toString()); client = NONE.getClient(requestConfig, sslAuthenticationHelper); } return client; @@ -79,7 +76,7 @@ public enum SslSupportLevel { }, CLIENT_CERT_AUTH { @Override - public HttpClient getClient(RequestConfig requestConfig, SSLAuthenticationHelper sslAuthenticationHelper) + public HttpClient getClient(RequestConfig requestConfig, SslAuthenticationHelper sslAuthenticationHelper) throws GeneralSecurityException, IOException { SSLContext sslContext = SSLContexts.custom() @@ -114,7 +111,7 @@ public enum SslSupportLevel { return "https".equals(new URL(url).getProtocol()) ? SslSupportLevel.ALWAYS_TRUST : SslSupportLevel.NONE; } - public abstract HttpClient getClient(RequestConfig config, SSLAuthenticationHelper sslAuthenticationHelper) + public abstract HttpClient getClient(RequestConfig config, SslAuthenticationHelper sslAuthenticationHelper) throws GeneralSecurityException, IOException; } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/keywords/Keyword.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/keywords/Keyword.java index edafe8f..1bb1332 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/keywords/Keyword.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/keywords/Keyword.java @@ -21,10 +21,12 @@ package org.onap.pnfsimulator.simulator.keywords; import io.vavr.Function1; import io.vavr.Function2; + import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.stream.Collectors; + import lombok.Getter; @Getter @@ -34,7 +36,7 @@ public class Keyword { protected static final String NONLETTERS_REGEX = "([^a-zA-Z]+)"; protected static final Function1<String, String> OPTIONAL = - (regex) -> regex + "?"; + regex -> regex + "?"; private final String name; private final List<String> meaningfulParts; @@ -46,12 +48,12 @@ public class Keyword { * Returns list of independent parts inside the keyword. Current implementation assumes that customer can join keywords with integer values, so * keyword is decomposed to parts then some parts of the keyword is skipped because of replacement process. * - * @param matcher - Matcher to check find independent groups inside the keyword + * @param matcher - Matcher to check find independent groups inside the keyword * @param skipGroups Informs this method about which groups should be consider as part of the replacement process * @return list of independent parts inside the keywords */ - static List<String> extractPartsFrom(Matcher matcher, List skipGroups) { - List<String> parts = new ArrayList<String>(); + static List<String> extractPartsFrom(Matcher matcher, List<Integer> skipGroups) { + List<String> parts = new ArrayList<>(); for (int i = 1; i <= matcher.groupCount(); i++) { if (matcher.group(i) != null && !skipGroups.contains(i)) { parts.add(matcher.group(i)); diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/scheduler/EventJob.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/scheduler/EventJob.java index c4b40fc..21e0466 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/scheduler/EventJob.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/scheduler/EventJob.java @@ -25,7 +25,7 @@ import com.google.gson.JsonObject; import org.onap.pnfsimulator.simulator.KeywordsHandler; import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; import org.onap.pnfsimulator.simulator.client.HttpClientAdapterImpl; -import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; @@ -69,24 +69,28 @@ public class EventJob implements Job { LOGGER.error("Could not send event as client is not available"); } } + private Optional<HttpClientAdapter> getHttpClientAdapter(JobDataMap jobDataMap, String vesUrl) { HttpClientAdapter adapter = null; try { - adapter = (HttpClientAdapter) (jobDataMap.containsKey(CLIENT_ADAPTER) ? jobDataMap.get(CLIENT_ADAPTER) : - new HttpClientAdapterImpl(vesUrl, new SSLAuthenticationHelper())); + adapter = (HttpClientAdapter) ( + jobDataMap.containsKey(CLIENT_ADAPTER) + ? jobDataMap.get(CLIENT_ADAPTER) + : new HttpClientAdapterImpl(vesUrl, new SslAuthenticationHelper()) + ); } catch (MalformedURLException e) { LOGGER.error("Invalid format of vesServerUr: {}", vesUrl); - } catch (IOException | GeneralSecurityException e){ + } catch (IOException | GeneralSecurityException e) { LOGGER.error("Invalid configuration of client certificate"); } return Optional.ofNullable(adapter); } private void logEventDetails(String templateName, String vesUrl, String body, String jobKey) { - LOGGER.info(String.format("Job %s:Sending event to %s from template %s", - jobKey, vesUrl, templateName)); + LOGGER.info("Job {}:Sending event to {} from template {}", + jobKey, vesUrl, templateName); if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Job %s: Request body %s", jobKey, body)); + LOGGER.debug("Job {}: Request body {}", jobKey, body); } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/scheduler/EventScheduler.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/scheduler/EventScheduler.java index 08e24f8..5584cb1 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/scheduler/EventScheduler.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/scheduler/EventScheduler.java @@ -20,25 +20,10 @@ package org.onap.pnfsimulator.simulator.scheduler; -import static org.onap.pnfsimulator.simulator.scheduler.EventJob.BODY; -import static org.onap.pnfsimulator.simulator.scheduler.EventJob.CLIENT_ADAPTER; -import static org.onap.pnfsimulator.simulator.scheduler.EventJob.EVENT_ID; -import static org.onap.pnfsimulator.simulator.scheduler.EventJob.KEYWORDS_HANDLER; -import static org.onap.pnfsimulator.simulator.scheduler.EventJob.TEMPLATE_NAME; -import static org.onap.pnfsimulator.simulator.scheduler.EventJob.VES_URL; -import static org.quartz.SimpleScheduleBuilder.simpleSchedule; - import com.google.gson.JsonObject; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; import org.onap.pnfsimulator.simulator.KeywordsHandler; import org.onap.pnfsimulator.simulator.client.HttpClientAdapterImpl; -import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; import org.quartz.JobBuilder; import org.quartz.JobDataMap; import org.quartz.JobDetail; @@ -51,23 +36,37 @@ import org.quartz.TriggerBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.BODY; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.CLIENT_ADAPTER; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.EVENT_ID; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.KEYWORDS_HANDLER; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.TEMPLATE_NAME; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.VES_URL; +import static org.quartz.SimpleScheduleBuilder.simpleSchedule; + @Component public class EventScheduler { private final Scheduler scheduler; private final KeywordsHandler keywordsHandler; - private final SSLAuthenticationHelper SSLAuthenticationHelper; + private final SslAuthenticationHelper sslAuthenticationHelper; @Autowired - public EventScheduler(Scheduler scheduler, KeywordsHandler keywordsHandler, SSLAuthenticationHelper SSLAuthenticationHelper) { + public EventScheduler(Scheduler scheduler, KeywordsHandler keywordsHandler, SslAuthenticationHelper sslAuthenticationHelper) { this.scheduler = scheduler; this.keywordsHandler = keywordsHandler; - this.SSLAuthenticationHelper = SSLAuthenticationHelper; + this.sslAuthenticationHelper = sslAuthenticationHelper; } public String scheduleEvent(String vesUrl, Integer repeatInterval, Integer repeatCount, - String templateName, String eventId, JsonObject body) + String templateName, String eventId, JsonObject body) throws SchedulerException, IOException, GeneralSecurityException { JobDetail jobDetail = createJobDetail(vesUrl, templateName, eventId, body); @@ -89,10 +88,10 @@ public class EventScheduler { private SimpleTrigger createTrigger(int interval, int repeatCount) { return TriggerBuilder.newTrigger() - .withSchedule(simpleSchedule() - .withIntervalInSeconds(interval) - .withRepeatCount(repeatCount - 1)) - .build(); + .withSchedule(simpleSchedule() + .withIntervalInSeconds(interval) + .withRepeatCount(repeatCount - 1)) + .build(); } private JobDetail createJobDetail(String vesUrl, String templateName, String eventId, JsonObject body) throws IOException, GeneralSecurityException { @@ -102,20 +101,20 @@ public class EventScheduler { jobDataMap.put(EVENT_ID, eventId); jobDataMap.put(KEYWORDS_HANDLER, keywordsHandler); jobDataMap.put(BODY, body); - jobDataMap.put(CLIENT_ADAPTER, new HttpClientAdapterImpl(vesUrl, SSLAuthenticationHelper)); + jobDataMap.put(CLIENT_ADAPTER, new HttpClientAdapterImpl(vesUrl, sslAuthenticationHelper)); return JobBuilder - .newJob(EventJob.class) - .withDescription(templateName) - .usingJobData(jobDataMap) - .build(); + .newJob(EventJob.class) + .withDescription(templateName) + .usingJobData(jobDataMap) + .build(); } private List<JobKey> getActiveJobsKeys() throws SchedulerException { return scheduler.getCurrentlyExecutingJobs() - .stream() - .map(JobExecutionContext::getJobDetail) - .map(JobDetail::getKey) - .collect(Collectors.toList()); + .stream() + .map(JobExecutionContext::getJobDetail) + .map(JobDetail::getKey) + .collect(Collectors.toList()); } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/FsToDbTemplateSynchronizer.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/FsToDbTemplateSynchronizer.java index 881585b..0080813 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/FsToDbTemplateSynchronizer.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/FsToDbTemplateSynchronizer.java @@ -20,12 +20,6 @@ package org.onap.pnfsimulator.template; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.stream.Stream; - import org.bson.json.JsonParseException; import org.onap.pnfsimulator.db.Storage; import org.onap.pnfsimulator.filesystem.WatcherEventProcessor; @@ -35,6 +29,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Stream; + @Service public class FsToDbTemplateSynchronizer { @@ -66,7 +66,7 @@ public class FsToDbTemplateSynchronizer { WatcherEventProcessor.MODIFIED.processEvent(path, storage); } catch (IOException | JsonParseException e) { LOGGER - .error("Cannot synchronize template: " + path.getFileName().toString(), e); + .error("Cannot synchronize template: {}", path.getFileName(), e); } }); } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/Template.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/Template.java index c84b8d0..121d7d4 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/Template.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/Template.java @@ -44,14 +44,14 @@ public class Template extends Row { private long lmod; public Template(String name, Document content, long lmod) { - this.id = name; + this.setId(name); this.content = content; this.lmod = lmod; this.flatContent = new JsonUtils().flatten(content); } public Template(String name, String template, long lmod) { - this.id = name; + this.setId(name); this.content = Document.parse(template); this.lmod = lmod; this.flatContent = new JsonUtils().flatten(this.content); @@ -72,21 +72,21 @@ public class Template extends Row { } @Override - public boolean equals(Object o) { - if (this == o) { + public boolean equals(Object object) { + if (this == object) { return true; } - if (o == null || getClass() != o.getClass()) { + if (object == null || getClass() != object.getClass()) { return false; } - Template template = (Template) o; + Template template = (Template) object; return Objects.equals(content, template.content) - && Objects.equals(id, template.id) + && Objects.equals(getId(), template.getId()) && Objects.equals(lmod, template.lmod); } @Override public int hashCode() { - return Objects.hash(content, id); + return Objects.hash(content, getId()); } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/IllegalJsonValueException.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/IllegalJsonValueException.java index 6890382..1685536 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/IllegalJsonValueException.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/IllegalJsonValueException.java @@ -22,7 +22,7 @@ package org.onap.pnfsimulator.template.search; public class IllegalJsonValueException extends IllegalArgumentException { - IllegalJsonValueException(String s) { - super(s); + IllegalJsonValueException(String message) { + super(message); } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/viewmodel/FlatTemplateContent.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/viewmodel/FlatTemplateContent.java index 84235f7..8634052 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/viewmodel/FlatTemplateContent.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/viewmodel/FlatTemplateContent.java @@ -37,7 +37,7 @@ public class FlatTemplateContent extends Row { public FlatTemplateContent(String name, List<KeyValuePair> keyValues) { - this.id = name; + this.setId(name); this.keyValues = keyValues; } } diff --git a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/viewmodel/KeyValuePair.java b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/viewmodel/KeyValuePair.java index 5e44452..8f24334 100644 --- a/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/viewmodel/KeyValuePair.java +++ b/pnfsimulator/src/main/java/org/onap/pnfsimulator/template/search/viewmodel/KeyValuePair.java @@ -34,7 +34,7 @@ import lombok.ToString; */ public class KeyValuePair { - private String k; - private String v; + private String key; + private String value; } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java index 98c4bc5..b86a0f9 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,42 +30,42 @@ import org.onap.pnfsimulator.template.Template; public class InMemoryTemplateStorage implements Storage<Template> { - private List<Template> storage = new ArrayList<>(); + private List<Template> storage = new ArrayList<>(); - @Override - public List<Template> getAll() { - return new ArrayList<>(storage); - } + @Override + public List<Template> getAll() { + return new ArrayList<>(storage); + } - @Override - public Optional<Template> get(String name) { - return storage.stream().filter(template -> template.getId().equals(name)).findFirst(); - } + @Override + public Optional<Template> get(String name) { + return storage.stream().filter(template -> template.getId().equals(name)).findFirst(); + } - @Override - public void persist(Template template) { - if (!storage.contains(template)){ - storage.add(template); + @Override + public void persist(Template template) { + if (!storage.contains(template)) { + storage.add(template); + } } - } - @Override - public boolean tryPersistOrOverwrite(Template template, boolean overwrite) { - if (!storage.contains(template) || overwrite){ - storage.add(template); - return true; + @Override + public boolean tryPersistOrOverwrite(Template template, boolean overwrite) { + if (!storage.contains(template) || overwrite) { + storage.add(template); + return true; + } + return false; } - return false; - } - @Override - public void delete(String templateName) { - get(templateName).ifPresent(template -> storage.remove(template)); - } + @Override + public void delete(String templateName) { + get(templateName).ifPresent(template -> storage.remove(template)); + } - @Override - public List<String> getIdsByContentCriteria(JsonObject queryJson) { - throw new RuntimeException("Method is not implemented."); - } + @Override + public List<String> getIdsByContentCriteria(JsonObject queryJson) { + throw new RuntimeException("Method is not implemented."); + } } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java index 42ed4d3..9dfa002 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,6 +31,7 @@ import java.time.Instant; import java.util.Collections; import java.util.HashMap; import java.util.Optional; + import org.bson.Document; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -84,18 +85,18 @@ class WatcherEventProcessorTest { } private void verifyPersistedValue() { - Assertions.assertEquals(storage.getAll().size(), 1); + Assertions.assertEquals(1, storage.getAll().size()); Optional<Template> templateFromStorage = storage.get("test1.json"); if (templateFromStorage.isPresent()) { Template retrievedTemplate = templateFromStorage.get(); Document templateContent = retrievedTemplate.getContent(); Document flatContent = retrievedTemplate.getFlatContent(); - Assertions.assertEquals(templateContent.getString("field1"), "value1"); - Assertions.assertEquals(templateContent.getInteger("field2", 0), 2); - Assertions.assertEquals(flatContent.getInteger(":nested:key1[0]", 0), 1); - Assertions.assertEquals(flatContent.getInteger(":nested:key1[1]", 0), 2); - Assertions.assertEquals(flatContent.getInteger(":nested:key1[2]", 0), 3); - Assertions.assertEquals(flatContent.getString(":nested:key2"), "sampleValue2"); + Assertions.assertEquals("value1", templateContent.getString("field1")); + Assertions.assertEquals(2, templateContent.getInteger("field2", 0)); + Assertions.assertEquals(1, flatContent.getInteger(":nested:key1[0]", 0)); + Assertions.assertEquals(2, flatContent.getInteger(":nested:key1[1]", 0)); + Assertions.assertEquals(3, flatContent.getInteger(":nested:key1[2]", 0)); + Assertions.assertEquals("sampleValue2", flatContent.getString(":nested:key2")); } else { fail(); } @@ -113,7 +114,7 @@ class WatcherEventProcessorTest { Mockito.when(watchEvent.kind()).thenReturn(StandardWatchEventKinds.ENTRY_DELETE); WatcherEventProcessor.process(watchEvent, storage, templatesDir); // then - Assertions.assertEquals(storage.getAll().size(), 0); + Assertions.assertEquals(0, storage.getAll().size()); } private void initStubs() { diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java index dae16c7..de824a4 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java @@ -66,7 +66,8 @@ class SimulatorControllerTest { private static final String JSON_MSG_EXPRESSION = "$.message"; private static final String NEW_URL = "http://0.0.0.0:8090/eventListener/v7"; - private static final String UPDATE_SIM_CONFIG_VALID_JSON = "{\"vesServerUrl\": \"" + NEW_URL + "\"}"; + private static final String UPDATE_SIM_CONFIG_VALID_JSON = "{\"vesServerUrl\": \"" + + NEW_URL + "\"}"; private static final String SAMPLE_ID = "sampleId"; private static final Gson GSON_OBJ = new Gson(); private static String simulatorRequestBody; @@ -144,7 +145,8 @@ class SimulatorControllerTest { mockMvc .perform(put(CONFIG_ENDPOINT) .contentType(MediaType.APPLICATION_JSON) - .content("{\"vesUrl\": \"" + NEW_URL + "\"}")) + .content("{\"vesUrl\": \"" + + NEW_URL + "\"}")) .andExpect(status().isBadRequest()); } @@ -162,18 +164,18 @@ class SimulatorControllerTest { String contentAsString = mockMvc .perform(post(EVENT_ENDPOINT) .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) - .content("{\"vesServerUrl\":\"http://0.0.0.0:8080/simulator/v7\",\n" + - " \"event\":{ \n" + - " \"commonEventHeader\":{ \n" + - " \"domain\":\"notification\",\n" + - " \"eventName\":\"vFirewallBroadcastPackets\"\n" + - " },\n" + - " \"notificationFields\":{ \n" + - " \"arrayOfNamedHashMap\":[ \n" + - " { \n" + - " \"name\":\"A20161221.1031-1041.bin.gz\",\n" + - " \"hashMap\":{ \n" + - " \"fileformatType\":\"org.3GPP.32.435#measCollec\"}}]}}}")) + .content("{\"vesServerUrl\":\"http://0.0.0.0:8080/simulator/v7\",\n" + + " \"event\":{ \n" + + " \"commonEventHeader\":{ \n" + + " \"domain\":\"notification\",\n" + + " \"eventName\":\"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\":{ \n" + + " \"arrayOfNamedHashMap\":[ \n" + + " { \n" + + " \"name\":\"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\":{ \n" + + " \"fileformatType\":\"org.3GPP.32.435#measCollec\"}}]}}}")) .andExpect(status().isAccepted()).andReturn().getResponse().getContentAsString(); assertThat(contentAsString).contains("One-time direct event sent successfully"); } @@ -183,12 +185,12 @@ class SimulatorControllerTest { String contentAsString = mockMvc .perform(post(EVENT_ENDPOINT) .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) - .content("{\"vesServerUrl\": \"http://localhost:9999/eventListener\",\n" + - " \"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"eventId\": \"#RandomString(20)\",\n" + - " \"sourceName\": \"PATCHED_sourceName\",\n" + - " \"version\": 3.0\n}}}")) + .content("{\"vesServerUrl\": \"http://localhost:9999/eventListener\",\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"eventId\": \"#RandomString(20)\",\n" + + " \"sourceName\": \"PATCHED_sourceName\",\n" + + " \"version\": 3.0\n}}}")) .andExpect(status().isAccepted()).andReturn().getResponse().getContentAsString(); assertThat(contentAsString).contains("One-time direct event sent successfully"); diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java index f34d73c..17be475 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java @@ -29,9 +29,9 @@ import static org.onap.pnfsimulator.rest.TemplateController.CANNOT_OVERRIDE_TEMP import static org.onap.pnfsimulator.rest.TemplateController.TEMPLATE_NOT_FOUND_MSG; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.mockito.Mockito.times; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -52,7 +52,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; -import static org.mockito.Mockito.times; import org.mockito.MockitoAnnotations; import org.onap.pnfsimulator.db.Storage; import org.onap.pnfsimulator.rest.model.SearchExp; @@ -63,6 +62,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; + class TemplateControllerTest { private static final String LIST_URL = "/template/list"; diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java index 0d62ee9..4e8e4dc 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java @@ -25,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.Map; + import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -39,7 +40,7 @@ class ResponseBuilderTest { ResponseEntity responseEntity = ResponseBuilder.status(SAMPLE_STATUS).build(); assertAll( - () -> assertEquals(responseEntity.getStatusCode(), SAMPLE_STATUS), + () -> assertEquals(SAMPLE_STATUS, responseEntity.getStatusCode()), () -> assertNull(responseEntity.getBody()) ); } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/DbTemplateReaderTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/DbTemplateReaderTest.java new file mode 100644 index 0000000..c3f85f5 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/DbTemplateReaderTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.pnfsimulator.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.assertj.core.api.Assertions; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.pnfsimulator.template.Template; +import org.onap.pnfsimulator.template.TemplateService; + +import java.io.IOException; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DbTemplateReaderTest { + + public static final String SOME_TEMPLATE = "someTemplate"; + public static final String KEY = "key"; + public static final String VALUE = "value"; + public static final long LMOD = 10L; + private TemplateService service; + private DbTemplateReader dbTemplateReader; + + @BeforeEach + void setUp() { + this.service = mock(TemplateService.class); + this.dbTemplateReader = new DbTemplateReader(this.service, new Gson()); + } + + @Test + public void shouldReportErrorWhenTemplateDoesNotExistInTemplateService() { + // given + when(this.service.get(SOME_TEMPLATE)).thenReturn(Optional.empty()); + + // when/then + assertThrows(IOException.class, + () -> this.dbTemplateReader.readTemplate(SOME_TEMPLATE) + ); + } + + @Test + public void shouldReturnTemplateFromService() throws IOException { + // given + Template template = givenTemplate(SOME_TEMPLATE); + when(this.service.get(SOME_TEMPLATE)).thenReturn(Optional.of(template)); + + // when + final JsonObject someTemplate = this.dbTemplateReader.readTemplate(SOME_TEMPLATE); + + // then + Assertions.assertThat(someTemplate).isNotNull(); + Assertions.assertThat(someTemplate.get(KEY).getAsString()).isEqualTo(VALUE); + } + + private Template givenTemplate(String templateName) { + return new Template(templateName, new Document(KEY, VALUE), LMOD); + } +} diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java index 53f02da..b5304a7 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java @@ -27,6 +27,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Optional; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -35,44 +36,44 @@ import org.onap.pnfsimulator.event.EventData; import org.onap.pnfsimulator.event.EventDataRepository; public class IncrementProviderImplTest { - private IncrementProvider incrementProvider; + private IncrementProvider incrementProvider; - @Mock - private EventDataRepository eventDataRepositoryMock; + @Mock + private EventDataRepository eventDataRepositoryMock; - @BeforeEach - void setUp() { - eventDataRepositoryMock = mock(EventDataRepository.class); - incrementProvider = new IncrementProviderImpl(eventDataRepositoryMock); - } + @BeforeEach + void setUp() { + eventDataRepositoryMock = mock(EventDataRepository.class); + incrementProvider = new IncrementProviderImpl(eventDataRepositoryMock); + } - @Test - public void getAndIncrementTest() { - ArgumentCaptor<EventData> eventDataArgumentCaptor = ArgumentCaptor.forClass(EventData.class); - String eventId = "1"; - int initialIncrementValue = 0; - int expectedValue = initialIncrementValue + 1; - EventData eventData = EventData.builder().id(eventId).incrementValue(initialIncrementValue).build(); - Optional<EventData> optional = Optional.of(eventData); + @Test + public void getAndIncrementTest() { + ArgumentCaptor<EventData> eventDataArgumentCaptor = ArgumentCaptor.forClass(EventData.class); + String eventId = "1"; + int initialIncrementValue = 0; + int expectedValue = initialIncrementValue + 1; + EventData eventData = EventData.builder().id(eventId).incrementValue(initialIncrementValue).build(); + Optional<EventData> optional = Optional.of(eventData); - when(eventDataRepositoryMock.findById(eventId)).thenReturn(optional); + when(eventDataRepositoryMock.findById(eventId)).thenReturn(optional); - int value = incrementProvider.getAndIncrement(eventId); + int value = incrementProvider.getAndIncrement(eventId); - verify(eventDataRepositoryMock).save(eventDataArgumentCaptor.capture()); + verify(eventDataRepositoryMock).save(eventDataArgumentCaptor.capture()); - assertThat(value).isEqualTo(expectedValue); - assertThat(eventDataArgumentCaptor.getValue().getIncrementValue()).isEqualTo(expectedValue); + assertThat(value).isEqualTo(expectedValue); + assertThat(eventDataArgumentCaptor.getValue().getIncrementValue()).isEqualTo(expectedValue); - } + } - @Test + @Test public void shouldThrowOnNonExistingEvent() { - Optional<EventData> emptyOptional = Optional.empty(); - String nonExistingEventId = "THIS_DOES_NOT_EXIST"; - when(eventDataRepositoryMock.findById(nonExistingEventId)).thenReturn(emptyOptional); + Optional<EventData> emptyOptional = Optional.empty(); + String nonExistingEventId = "THIS_DOES_NOT_EXIST"; + when(eventDataRepositoryMock.findById(nonExistingEventId)).thenReturn(emptyOptional); - assertThrows(EventNotFoundException.class, - () -> incrementProvider.getAndIncrement(nonExistingEventId)); - } + assertThrows(EventNotFoundException.class, + () -> incrementProvider.getAndIncrement(nonExistingEventId)); + } } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java index f5c12c3..bf6f290 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java @@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collection; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -37,10 +38,10 @@ public class KeywordsExtractorValidTimestampTest { private KeywordsExtractor keywordsExtractor; private static final Collection VALID_TIMESTAMP_KEYWORDS = Arrays.asList(new Object[][]{ - {"#Timestamp", 10}, - {"#Timestamp12", 10 + 2}, - {"1#Timestamp", 1 + 10}, - {"1#Timestamp2", 1 + 10 +1} + {"#Timestamp", 10}, + {"#Timestamp12", 10 + 2}, + {"1#Timestamp", 1 + 10}, + {"1#Timestamp2", 1 + 10 + 1} }); public KeywordsExtractorValidTimestampTest(String keyword, Integer length) { diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java index e67d4a3..e36bb28 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java @@ -26,119 +26,121 @@ import static org.onap.pnfsimulator.simulator.KeywordsValueProvider.DEFAULT_STRI import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; + import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; + import org.junit.jupiter.api.Test; class KeywordsHandlerTest { - private static final String TEMPLATE_JSON = "{\n" + - " \"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"domain\": \"#RandomString\"\n" + - " },\n" + - " \"measurementsForVfScalingFields\": {\n" + - " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + - " \"additionalMeasurements\": {\n" + - " \"name\": \"licenseUsage\",\n" + - " \"extraFields\": {\n" + - " \"name\": \"#RandomString(4)\",\n" + - " \"value\": \"1\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - - private static final String TEMPLATE_JSON_WITH_MANY_KEYWORDS_INSIDE_SINGLE_VALUE = "{\n" + - " \"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"domain1\": \"#RandomString(1) #RandomString(2) #RandomString(3)\",\n" + - " \"domain2\": \"1 #RandomString(1) 2\"\n" + - " },\n" + - " \"measurementsForVfScalingFields\": {\n" + - " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + - " \"additionalMeasurements\": {\n" + - " \"name\": \"licenseUsage\",\n" + - " \"extraFields\": {\n" + - " \"value\": \"1\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; + private static final String TEMPLATE_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_JSON_WITH_MANY_KEYWORDS_INSIDE_SINGLE_VALUE = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain1\": \"#RandomString(1) #RandomString(2) #RandomString(3)\",\n" + + " \"domain2\": \"1 #RandomString(1) 2\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; private static final String TEMPLATE_JSON_WITH_ARRAY = "{\n" - + " \"event\": {\n" - + " \"commonEventHeader\": {\n" - + " \"domain\": \"#RandomString(1)\",\n" - + " \"version\": 2.0\n" - + " },\n" - + " \"measurementsForVfScalingFields\": {\n" - + " \"additionalMeasurements\": [\n" - + " {\n" - + " \"name\": \"licenseUsage\",\n" - + " \"arrayOfFields\": [\n" - + " {\n" - + " \"name\": \"G711AudioPort\",\n" - + " \"value\": \"1\"\n" - + " },\n" - + " {\n" - + " \"name\": [\"1\",\"2\"],\n" - + " \"value\": \"#RandomString(2)\"\n" - + " },\n" - + " {\n" - + " \"name\": \"G722AudioPort\",\n" - + " \"value\": \"1\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " ]\n" - + " }\n" - + " }\n" - + "}"; - - private static final String TEMPLATE_ONE_INCREMENT_JSON = "{\n" + - " \"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"domain\": \"#RandomString\"\n" + - " },\n" + - " \"measurementsForVfScalingFields\": {\n" + - " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + - " \"additionalMeasurements\": {\n" + - " \"name\": \"licenseUsage\",\n" + - " \"extraFields\": {\n" + - " \"name\": \"#RandomString(4)\",\n" + - " \"value\": \"#Increment\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - - private static final String TEMPLATE_WITH_SIMPLE_VALUE= "\"#RandomString(4)\""; + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString(1)\",\n" + + " \"version\": 2.0\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"additionalMeasurements\": [\n" + + " {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"arrayOfFields\": [\n" + + " {\n" + + " \"name\": \"G711AudioPort\",\n" + + " \"value\": \"1\"\n" + + " },\n" + + " {\n" + + " \"name\": [\"1\",\"2\"],\n" + + " \"value\": \"#RandomString(2)\"\n" + + " },\n" + + " {\n" + + " \"name\": \"G722AudioPort\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_ONE_INCREMENT_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"#Increment\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_WITH_SIMPLE_VALUE = "\"#RandomString(4)\""; private static final String TEMPLATE_WITH_ARRAY_OF_PRIMITIVES = "[ 1, \"#RandomString(5)\", 3]"; - private static final String TEMPLATE_TWO_INCREMENT_JSON = "{\n" + - " \"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"domain\": \"#RandomString\"\n" + - " },\n" + - " \"measurementsForVfScalingFields\": {\n" + - " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + - " \"additionalMeasurements\": {\n" + - " \"name\": \"licenseUsage\",\n" + - " \"extraFields\": {\n" + - " \"name\": \"#RandomString(4)\",\n" + - " \"value\": \"#Increment\",\n" + - " \"otherValue\": \"#Increment\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; + private static final String TEMPLATE_TWO_INCREMENT_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"#Increment\",\n" + + " \"otherValue\": \"#Increment\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; private Gson gson = new Gson(); @@ -153,15 +155,15 @@ class KeywordsHandlerTest { // then String extraFields = resultJson - .get("event").getAsJsonObject() - .get("measurementsForVfScalingFields").getAsJsonObject() - .get("additionalMeasurements").getAsJsonObject() - .get("extraFields").getAsJsonObject() - .get("name").getAsString(); + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("name").getAsString(); String newDomain = resultJson - .get("event").getAsJsonObject() - .get("commonEventHeader").getAsJsonObject() - .get("domain").getAsString(); + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain").getAsString(); assertThat(extraFields.length()).isEqualTo(4); assertThat(newDomain.length()).isEqualTo(DEFAULT_STRING_LENGTH); @@ -178,16 +180,16 @@ class KeywordsHandlerTest { // then String newDomain1 = resultJson - .get("event").getAsJsonObject() - .get("commonEventHeader").getAsJsonObject() - .get("domain1").getAsString(); + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain1").getAsString(); String newDomain2 = resultJson - .get("event").getAsJsonObject() - .get("commonEventHeader").getAsJsonObject() - .get("domain2").getAsString(); + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain2").getAsString(); - assertThat(newDomain1.length()).isEqualTo(1+1+2+1+3); - assertThat(newDomain2.length()).isEqualTo(1+1+1+1+1); + assertThat(newDomain1.length()).isEqualTo(1 + 1 + 2 + 1 + 3); + assertThat(newDomain2.length()).isEqualTo(1 + 1 + 1 + 1 + 1); } @Test @@ -225,17 +227,17 @@ class KeywordsHandlerTest { // then String actualValue = resultJson - .get("event").getAsJsonObject() - .get("measurementsForVfScalingFields").getAsJsonObject() - .get("additionalMeasurements").getAsJsonArray() - .get(0).getAsJsonObject() - .get("arrayOfFields").getAsJsonArray() - .get(1).getAsJsonObject() - .get("value").getAsString(); + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonArray() + .get(0).getAsJsonObject() + .get("arrayOfFields").getAsJsonArray() + .get(1).getAsJsonObject() + .get("value").getAsString(); String otherActualValue = resultJson - .get("event").getAsJsonObject() - .get("commonEventHeader").getAsJsonObject() - .get("domain").getAsString(); + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain").getAsString(); assertThat(otherActualValue.length()).isEqualTo(1); assertThat(actualValue.length()).isEqualTo(2); @@ -253,11 +255,11 @@ class KeywordsHandlerTest { // then String actualValue = resultJson - .get("event").getAsJsonObject() - .get("measurementsForVfScalingFields").getAsJsonObject() - .get("additionalMeasurements").getAsJsonObject() - .get("extraFields").getAsJsonObject() - .get("value").getAsString(); + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("value").getAsString(); assertThat(actualValue).isEqualTo(newIncrementedValue.toString()); } @@ -270,7 +272,7 @@ class KeywordsHandlerTest { JsonObject templateJson = gson.fromJson(TEMPLATE_TWO_INCREMENT_JSON, JsonObject.class); KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), new IncrementProvider() { Queue<Integer> sequenceOfValues = new LinkedList<>( - Arrays.asList(firstIncrementValue, secondIncrementValue)); + Arrays.asList(firstIncrementValue, secondIncrementValue)); @Override public int getAndIncrement(String id) { @@ -284,18 +286,18 @@ class KeywordsHandlerTest { // then String actualValue = resultJson - .get("event").getAsJsonObject() - .get("measurementsForVfScalingFields").getAsJsonObject() - .get("additionalMeasurements").getAsJsonObject() - .get("extraFields").getAsJsonObject() - .get("value").getAsString(); + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("value").getAsString(); String actualOtherValue = resultJson - .get("event").getAsJsonObject() - .get("measurementsForVfScalingFields").getAsJsonObject() - .get("additionalMeasurements").getAsJsonObject() - .get("extraFields").getAsJsonObject() - .get("otherValue").getAsString(); + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("otherValue").getAsString(); assertThat(actualValue).isEqualTo(secondIncrementValue.toString()); assertThat(actualOtherValue).isEqualTo(secondIncrementValue.toString()); diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java index 73e4c31..ac54237 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java @@ -25,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.onap.pnfsimulator.simulator.KeywordsValueProvider.DEFAULT_STRING_LENGTH; import java.util.Random; + import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; @@ -33,49 +34,49 @@ class KeywordsValueProviderTest { @RepeatedTest(10) void randomLimitedStringTest() { String supplierResult = KeywordsValueProvider.getRandomLimitedString().apply(); - assertEquals(supplierResult.length(), DEFAULT_STRING_LENGTH); + assertEquals(DEFAULT_STRING_LENGTH, supplierResult.length()); } @RepeatedTest(10) void randomStringTest() { int length = new Random().nextInt(15) + 1; String supplierResult = KeywordsValueProvider.getRandomString().apply(length); - assertEquals(supplierResult.length(), length); + assertEquals(length, supplierResult.length()); } @RepeatedTest(10) - void randomIntegerTest(){ + void randomIntegerTest() { int min = new Random().nextInt(10) + 1; int max = new Random().nextInt(1000) + 20; String supplierResult = KeywordsValueProvider.getRandomInteger().apply(min, max); - assertTrue(Integer.parseInt(supplierResult)>=min); - assertTrue(Integer.parseInt(supplierResult)<=max); + assertTrue(Integer.parseInt(supplierResult) >= min); + assertTrue(Integer.parseInt(supplierResult) <= max); } @Test - void randomIntegerContainsMaximalAndMinimalValuesTest(){ + void randomIntegerContainsMaximalAndMinimalValuesTest() { int anyNumber = new Random().nextInt(10) + 1; String supplierResult = KeywordsValueProvider.getRandomInteger().apply(anyNumber, anyNumber); assertEquals(Integer.parseInt(supplierResult), anyNumber); } @Test - void randomIntegerFromNegativeRangeTest(){ + void randomIntegerFromNegativeRangeTest() { String supplierResult = KeywordsValueProvider.getRandomInteger().apply(-20, -20); assertEquals(Integer.parseInt(supplierResult), -20); } @RepeatedTest(10) - void randomIntegerFromParametersWithDifferentOrdersTest(){ + void randomIntegerFromParametersWithDifferentOrdersTest() { String supplierResult = KeywordsValueProvider.getRandomInteger().apply(-20, -10); - assertTrue(Integer.parseInt(supplierResult)>=-20); - assertTrue(Integer.parseInt(supplierResult)<=-10); + assertTrue(Integer.parseInt(supplierResult) >= -20); + assertTrue(Integer.parseInt(supplierResult) <= -10); } @RepeatedTest(10) - void epochSecondGeneratedInCorrectFormatTest(){ + void epochSecondGeneratedInCorrectFormatTest() { String supplierResult = KeywordsValueProvider.getEpochSecond().apply(); - assertEquals(supplierResult.length(), 10); + assertEquals(10, supplierResult.length()); } } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java index 0196eb0..870c963 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java @@ -33,14 +33,13 @@ import org.onap.pnfsimulator.rest.model.FullEvent; import org.onap.pnfsimulator.rest.model.SimulatorParams; import org.onap.pnfsimulator.rest.model.SimulatorRequest; import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; -import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; import org.onap.pnfsimulator.simulator.scheduler.EventScheduler; import org.onap.pnfsimulator.simulatorconfig.SimulatorConfig; import org.onap.pnfsimulator.simulatorconfig.SimulatorConfigService; import org.quartz.SchedulerException; import java.io.IOException; -import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; @@ -59,32 +58,32 @@ class SimulatorServiceTest { private static final String VES_URL = "http://0.0.0.0:8080"; private static final Gson GSON = new Gson(); - private static final JsonObject VALID_PATCH = GSON.fromJson("{\"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"sourceName\": \"SomeCustomSource\"}}}\n", JsonObject.class); - private static JsonObject VALID_FULL_EVENT = GSON.fromJson("{\"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"domain\": \"notification\",\n" + - " \"eventName\": \"vFirewallBroadcastPackets\"\n" + - " },\n" + - " \"notificationFields\": {\n" + - " \"arrayOfNamedHashMap\": [{\n" + - " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + - " \"hashMap\": {\n" + - " \"fileformatType\": \"org.3GPP.32.435#measCollec\"}}]}}}", JsonObject.class); - private static JsonObject FULL_EVENT_WITH_KEYWORDS = GSON.fromJson("{\"event\":{ \n" + - " \"commonEventHeader\":{ \n" + - " \"domain\":\"notification\",\n" + - " \"eventName\":\"#RandomString(20)\",\n" + - " \"eventOrderNo\":\"#Increment\"}}}", JsonObject.class); + private static final JsonObject VALID_PATCH = GSON.fromJson("{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"sourceName\": \"SomeCustomSource\"}}}\n", JsonObject.class); + private static JsonObject VALID_FULL_EVENT = GSON.fromJson("{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"notification\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\": {\n" + + " \"arrayOfNamedHashMap\": [{\n" + + " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileformatType\": \"org.3GPP.32.435#measCollec\"}}]}}}", JsonObject.class); + private static JsonObject FULL_EVENT_WITH_KEYWORDS = GSON.fromJson("{\"event\":{ \n" + + " \"commonEventHeader\":{ \n" + + " \"domain\":\"notification\",\n" + + " \"eventName\":\"#RandomString(20)\",\n" + + " \"eventOrderNo\":\"#Increment\"}}}", JsonObject.class); private static final String SOME_CUSTOM_SOURCE = "SomeCustomSource"; - private static final String CLOSED_LOOP_VNF ="ClosedLoopVNF"; + private static final String CLOSED_LOOP_VNF = "ClosedLoopVNF"; private static final String SAMPLE_ID = "sampleId"; private static final EventData SAMPLE_EVENT = EventData.builder().id("1").build(); private final ArgumentCaptor<JsonObject> bodyCaptor = ArgumentCaptor.forClass(JsonObject.class); private final ArgumentCaptor<Integer> intervalCaptor = ArgumentCaptor.forClass(Integer.class); private final ArgumentCaptor<Integer> repeatCountCaptor = ArgumentCaptor - .forClass(Integer.class); + .forClass(Integer.class); private final ArgumentCaptor<String> templateNameCaptor = ArgumentCaptor.forClass(String.class); private final ArgumentCaptor<String> eventIdCaptor = ArgumentCaptor.forClass(String.class); private final ArgumentCaptor<String> vesUrlCaptor = ArgumentCaptor.forClass(String.class); @@ -104,7 +103,7 @@ class SimulatorServiceTest { simulatorConfigService = mock(SimulatorConfigService.class); simulatorService = new SimulatorService(templatePatcher, templateReader, - eventScheduler, eventDataService, simulatorConfigService, new SSLAuthenticationHelper()); + eventScheduler, eventDataService, simulatorConfigService, new SslAuthenticationHelper()); } @Test @@ -112,7 +111,7 @@ class SimulatorServiceTest { String templateName = "validExampleMeasurementEvent.json"; SimulatorParams simulatorParams = new SimulatorParams(VES_URL, 1, 1); SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams, - templateName, VALID_PATCH); + templateName, VALID_PATCH); doReturn(SAMPLE_EVENT).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); @@ -125,8 +124,8 @@ class SimulatorServiceTest { void shouldTriggerEventWithDefaultVesUrlWhenNotProvidedInRequest() throws IOException, SchedulerException, GeneralSecurityException { String templateName = "validExampleMeasurementEvent.json"; SimulatorRequest simulatorRequest = new SimulatorRequest( - new SimulatorParams("", 1, 1), - templateName, VALID_PATCH); + new SimulatorParams("", 1, 1), + templateName, VALID_PATCH); URL inDbVesUrl = new URL("http://0.0.0.0:8080/eventListener/v6"); doReturn(SAMPLE_EVENT).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); @@ -140,23 +139,24 @@ class SimulatorServiceTest { @Test void shouldThrowJsonSyntaxWhenInvalidJson() { //given - JsonObject patch = GSON.fromJson("{\n" + - " \"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"sourceName\": \"" + SOME_CUSTOM_SOURCE + "\"\n" + - " }\n" + - " }\n" + - "}\n", JsonObject.class); + JsonObject patch = GSON.fromJson("{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"sourceName\": \"" + + SOME_CUSTOM_SOURCE + "\"\n" + + " }\n" + + " }\n" + + "}\n", JsonObject.class); EventData eventData = EventData.builder().id("1").build(); SimulatorParams simulatorParams = new SimulatorParams(VES_URL, 1, 1); SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams, - "invalidJsonStructureEvent.json", patch); + "invalidJsonStructureEvent.json", patch); doReturn(eventData).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); //when assertThrows(JsonSyntaxException.class, - () -> simulatorService.triggerEvent(simulatorRequest)); + () -> simulatorService.triggerEvent(simulatorRequest)); } @Test @@ -177,7 +177,7 @@ class SimulatorServiceTest { @Test void shouldSuccessfullySendOneTimeEventWithVesUrlWhenPassed() throws IOException, GeneralSecurityException { - SimulatorService spiedTestedService = spy(new SimulatorService(templatePatcher,templateReader, eventScheduler, eventDataService, simulatorConfigService, new SSLAuthenticationHelper())); + SimulatorService spiedTestedService = spy(new SimulatorService(templatePatcher, templateReader, eventScheduler, eventDataService, simulatorConfigService, new SslAuthenticationHelper())); HttpClientAdapter adapterMock = mock(HttpClientAdapter.class); doNothing().when(adapterMock).send(eventContentCaptor.capture()); @@ -193,7 +193,7 @@ class SimulatorServiceTest { @Test void shouldSubstituteKeywordsAndSuccessfullySendOneTimeEvent() throws IOException, GeneralSecurityException { - SimulatorService spiedTestedService = spy(new SimulatorService(templatePatcher,templateReader, eventScheduler, eventDataService, simulatorConfigService, new SSLAuthenticationHelper())); + SimulatorService spiedTestedService = spy(new SimulatorService(templatePatcher, templateReader, eventScheduler, eventDataService, simulatorConfigService, new SslAuthenticationHelper())); HttpClientAdapter adapterMock = mock(HttpClientAdapter.class); doNothing().when(adapterMock).send(eventContentCaptor.capture()); @@ -210,18 +210,18 @@ class SimulatorServiceTest { private void assertEventHasExpectedStructure(String expectedVesUrl, String templateName, String sourceNameString) throws SchedulerException, IOException, GeneralSecurityException { verify(eventScheduler, times(1)).scheduleEvent(vesUrlCaptor.capture(), intervalCaptor.capture(), - repeatCountCaptor.capture(), templateNameCaptor.capture(), eventIdCaptor.capture(), bodyCaptor.capture()); + repeatCountCaptor.capture(), templateNameCaptor.capture(), eventIdCaptor.capture(), bodyCaptor.capture()); assertThat(vesUrlCaptor.getValue()).isEqualTo(expectedVesUrl); assertThat(intervalCaptor.getValue()).isEqualTo(1); assertThat(repeatCountCaptor.getValue()).isEqualTo(1); assertThat(templateNameCaptor.getValue()).isEqualTo(templateName); String actualSourceName = GSON.fromJson(bodyCaptor.getValue(), JsonObject.class) - .get("event").getAsJsonObject() - .get("commonEventHeader").getAsJsonObject() - .get("sourceName").getAsString(); + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("sourceName").getAsString(); assertThat(actualSourceName).isEqualTo(sourceNameString); verify(eventDataService) - .persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), - any(JsonObject.class)); + .persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), + any(JsonObject.class)); } } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java index 52e0d6a..818c8be 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java @@ -31,23 +31,23 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThat; class TemplatePatcherTest { - private static final String TEMPLATE_JSON = "{\n" + - " \"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"domain\": \"measurementsForVfScaling\"\n" + - " },\n" + - " \"measurementsForVfScalingFields\": {\n" + - " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + - " \"additionalMeasurements\": {\n" + - " \"name\": \"licenseUsage\",\n" + - " \"extraFields\": {\n" + - " \"name\": \"G711AudioPort\",\n" + - " \"value\": \"1\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; + private static final String TEMPLATE_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"measurementsForVfScaling\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"G711AudioPort\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; private TemplatePatcher templatePatcher; private Gson gson = new Gson(); @@ -109,9 +109,9 @@ class TemplatePatcherTest { .get("commonEventHeader").getAsJsonObject() .get("domain"); assertThat(newDomain.isJsonObject()).isTrue(); - JsonObject newDomainJO = newDomain.getAsJsonObject(); - AssertionsForInterfaceTypes.assertThat(newDomainJO.keySet()).containsExactly("extraFields"); - JsonObject newDomainExtraFields = newDomainJO.get("extraFields").getAsJsonObject(); + JsonObject newDomainJsonObject = newDomain.getAsJsonObject(); + AssertionsForInterfaceTypes.assertThat(newDomainJsonObject.keySet()).containsExactly("extraFields"); + JsonObject newDomainExtraFields = newDomainJsonObject.get("extraFields").getAsJsonObject(); AssertionsForInterfaceTypes.assertThat(newDomainExtraFields.keySet()).containsExactly("name", "value"); } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java index 63c1b72..9eaab5c 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java @@ -26,7 +26,7 @@ import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; import java.io.IOException; import java.net.MalformedURLException; @@ -59,17 +59,18 @@ class HttpClientAdapterImplTest { } @Test - void sendShouldSuccessfullySendRequestGivenValidUrlUsingHTTPS() throws IOException { + void sendShouldSuccessfullySendRequestGivenValidUrlUsingHttps() throws IOException { assertAdapterSentRequest("https://valid-url:8443"); } @Test - void shouldThrowExceptionWhenMalformedVesUrlPassed(){ - assertThrows(MalformedURLException.class, () -> new HttpClientAdapterImpl("http://blablabla:VES-PORT", new SSLAuthenticationHelper())); + void shouldThrowExceptionWhenMalformedVesUrlPassed() { + assertThrows(MalformedURLException.class, () -> new HttpClientAdapterImpl("http://blablabla:VES-PORT", new SslAuthenticationHelper())); } + @Test - void shouldCreateAdapterWithClientNotSupportingSSLConnection() throws IOException, GeneralSecurityException { - HttpClientAdapter adapterWithHttps = new HttpClientAdapterImpl(HTTPS_URL, new SSLAuthenticationHelper()); + void shouldCreateAdapterWithClientNotSupportingSslConnection() throws IOException, GeneralSecurityException { + HttpClientAdapter adapterWithHttps = new HttpClientAdapterImpl(HTTPS_URL, new SslAuthenticationHelper()); try { adapterWithHttps.send("sample"); } catch (Exception actualException) { @@ -79,7 +80,7 @@ class HttpClientAdapterImplTest { @Test void shouldCreateAdapterWithClientSupportingPlainConnectionOnly() throws IOException, GeneralSecurityException { - HttpClientAdapter adapterWithHttps = new HttpClientAdapterImpl(HTTP_URL, new SSLAuthenticationHelper()); + HttpClientAdapter adapterWithHttps = new HttpClientAdapterImpl(HTTP_URL, new SslAuthenticationHelper()); try { adapterWithHttps.send("sample"); } catch (Exception actualException) { diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevelTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevelTest.java index ff41c44..3a7dbf2 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevelTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevelTest.java @@ -35,17 +35,17 @@ class SslSupportLevelTest { @Test void testShouldReturnAlwaysTrustSupportLevelForHttpsUrl() throws MalformedURLException { SslSupportLevel actualSupportLevel = SslSupportLevel.getSupportLevelBasedOnProtocol(HTTPS_URL); - assertEquals(actualSupportLevel, SslSupportLevel.ALWAYS_TRUST); + assertEquals(SslSupportLevel.ALWAYS_TRUST, actualSupportLevel); } @Test void testShouldReturnNoneSupportLevelForHttpUrl() throws MalformedURLException { SslSupportLevel actualSupportLevel = SslSupportLevel.getSupportLevelBasedOnProtocol(HTTP_URL); - assertEquals(actualSupportLevel, SslSupportLevel.NONE); + assertEquals(SslSupportLevel.NONE, actualSupportLevel); } @Test - void testShouldRaiseExceptionWhenInvalidUrlPassed(){ + void testShouldRaiseExceptionWhenInvalidUrlPassed() { assertThrows(MalformedURLException.class, () -> SslSupportLevel.getSupportLevelBasedOnProtocol("http://bla:VES-PORT/")); } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/keywords/TwoParameterKeywordTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/keywords/TwoParameterKeywordTest.java new file mode 100644 index 0000000..6477fbf --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/keywords/TwoParameterKeywordTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.simulator.keywords; + + +import io.vavr.Tuple1; +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; + +class TwoParameterKeywordTest { + @Test + public void whenGivenKeywordShouldReturnTwoParameterKeywordObjectWithParsedValues() { + //given + final String expectedName = "TEST"; + final Integer expectedParam1 = 123; + final Integer expectedParam2 = 456; + + String keyword = "#" + expectedName + "(" + expectedParam1 + "," + expectedParam2 + ")"; + + //when + Tuple1<TwoParameterKeyword> keywordTuple = TwoParameterKeyword.twoParameterKeyword(keyword); + TwoParameterKeyword twoParameterKeyword = keywordTuple._1(); + + //then + assertEquals(twoParameterKeyword.getName(), expectedName); + assertEquals(twoParameterKeyword.getAdditionalParameter1(), expectedParam1); + assertEquals(twoParameterKeyword.getAdditionalParameter2(), expectedParam2); + } +}
\ No newline at end of file diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java index 25ed84c..fed6bb6 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java @@ -69,14 +69,14 @@ class EventJobTest { assertThat(bodyCaptor.getValue()).isEqualTo(body.toString()); } - private JobExecutionContext createMockJobExecutionContext(String templateName, String eventId, String vesURL, + private JobExecutionContext createMockJobExecutionContext(String templateName, String eventId, String vesUrl, JsonObject body, HttpClientAdapter clientAdapter) { JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(TEMPLATE_NAME, templateName); jobDataMap.put(KEYWORDS_HANDLER, new KeywordsHandler(new KeywordsExtractor(), (id) -> 1)); jobDataMap.put(EVENT_ID, eventId); - jobDataMap.put(VES_URL, vesURL); + jobDataMap.put(VES_URL, vesUrl); jobDataMap.put(BODY, body); jobDataMap.put(CLIENT_ADAPTER, clientAdapter); diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java index 84df5e9..d7cabb7 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java @@ -28,7 +28,6 @@ import static org.mockito.Mockito.when; import com.google.gson.JsonObject; import java.io.IOException; -import java.net.MalformedURLException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; @@ -39,7 +38,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; @@ -57,7 +56,7 @@ class EventSchedulerTest { Scheduler quartzScheduler; @Mock - SSLAuthenticationHelper sslAuthenticationHelper; + SslAuthenticationHelper sslAuthenticationHelper; @BeforeEach void setUp() { diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java index 0746960..fd41045 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,7 +28,7 @@ import org.junit.Assert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; -import org.mockito.Mock;; +import org.mockito.Mock; import org.onap.pnfsimulator.template.search.viewmodel.FlatTemplateContent; import org.onap.pnfsimulator.template.search.TemplateSearchHelper; import org.springframework.data.mongodb.core.MongoTemplate; @@ -112,7 +112,7 @@ class TemplateServiceTest { } @Test - void shouldReturnNamesForGivenComposedSearchCriteria(){ + void shouldReturnNamesForGivenComposedSearchCriteria() { JsonObject composedCriteriaObject = GSON.fromJson("{\"eventName\": \"pnfRegistration_Nokia_5gDu\", \"sequence\": 1}", JsonObject.class); List<FlatTemplateContent> arr = Lists.newArrayList(new FlatTemplateContent("sampleId", null)); diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java index fa0bed1..aac15a6 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,41 +38,41 @@ class JsonUtilsTest { utils = new JsonUtils(); } - private static final String NOTIFICATION_JSON = "{\n\"event\": {\n" + - " \"commonEventHeader\": {\n" + - " \"domain\": \"notification\",\n" + - " \"eventName\": \"vFirewallBroadcastPackets\"\n" + - " },\n" + - " \"notificationFields\": {\n" + - " \"changeIdentifier\": \"PM_MEAS_FILES\",\n" + - " \"arrayOfNamedHashMap\": [{\n" + - " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + - " \"hashMap\": {\n" + - " \"fileformatType\": \"org.3GPP.32.435#measCollec\",\n" + - " \"fileFormatVersion\": \"V10\"\n"+ - " }\n" + - " }, {\n" + - " \"name\": \"A20161222.1042-1102.bin.gz\",\n" + - " \"hashMap\": {\n" + - " \"fileFormatType\": \"org.3GPP.32.435#measCollec\",\n" + - " \"fileFormatVersion\": \"1.0.0\"\n" + - " }\n" + - " }],\n" + - " \"notificationFieldsVersion\": \"2.0\"\n}\n\n}}"; - private static final String EXPECTED_FLATTENED_NOTIFICATION = "{" + - " \":event:commonEventHeader:domain\" : \"notification\"," + - " \":event:commonEventHeader:eventName\" : \"vFirewallBroadcastPackets\"," + - " \":event:notificationFields:changeIdentifier\" : \"PM_MEAS_FILES\"," + - " \":event:notificationFields:arrayOfNamedHashMap[0]:name\" : \"A20161221.1031-1041.bin.gz\"," + - " \":event:notificationFields:arrayOfNamedHashMap[0]:hashMap:fileformatType\" : \"org.3GPP.32.435#measCollec\"," + - " \":event:notificationFields:arrayOfNamedHashMap[0]:hashMap:fileFormatVersion\" : \"V10\"," + - " \":event:notificationFields:arrayOfNamedHashMap[1]:name\" : \"A20161222.1042-1102.bin.gz\"," + - " \":event:notificationFields:arrayOfNamedHashMap[1]:hashMap:fileFormatType\" : \"org.3GPP.32.435#measCollec\"," + - " \":event:notificationFields:arrayOfNamedHashMap[1]:hashMap:fileFormatVersion\" : \"1.0.0\"," + - " \":event:notificationFields:notificationFieldsVersion\" : \"2.0\" }"; + private static final String NOTIFICATION_JSON = "{\n\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"notification\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\": {\n" + + " \"changeIdentifier\": \"PM_MEAS_FILES\",\n" + + " \"arrayOfNamedHashMap\": [{\n" + + " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileformatType\": \"org.3GPP.32.435#measCollec\",\n" + + " \"fileFormatVersion\": \"V10\"\n" + + " }\n" + + " }, {\n" + + " \"name\": \"A20161222.1042-1102.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileFormatType\": \"org.3GPP.32.435#measCollec\",\n" + + " \"fileFormatVersion\": \"1.0.0\"\n" + + " }\n" + + " }],\n" + + " \"notificationFieldsVersion\": \"2.0\"\n}\n\n}}"; + private static final String EXPECTED_FLATTENED_NOTIFICATION = "{" + + " \":event:commonEventHeader:domain\" : \"notification\"," + + " \":event:commonEventHeader:eventName\" : \"vFirewallBroadcastPackets\"," + + " \":event:notificationFields:changeIdentifier\" : \"PM_MEAS_FILES\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:name\" : \"A20161221.1031-1041.bin.gz\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:hashMap:fileformatType\" : \"org.3GPP.32.435#measCollec\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:hashMap:fileFormatVersion\" : \"V10\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:name\" : \"A20161222.1042-1102.bin.gz\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:hashMap:fileFormatType\" : \"org.3GPP.32.435#measCollec\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:hashMap:fileFormatVersion\" : \"1.0.0\"," + + " \":event:notificationFields:notificationFieldsVersion\" : \"2.0\" }"; @Test - void shouldFlattenNestedJsonAndSeparateKeysWithDoubleHash(){ + void shouldFlattenNestedJsonAndSeparateKeysWithDoubleHash() { JsonObject templateJson = GSON_HELPER.fromJson(NOTIFICATION_JSON, JsonObject.class); JsonObject result = utils.flatten(templateJson); @@ -81,18 +81,18 @@ class JsonUtilsTest { } @Test - void shouldWorkOnEmptyJsonObject(){ + void shouldWorkOnEmptyJsonObject() { JsonObject result = utils.flatten(new JsonObject()); assertThat(result.toString()).isEqualTo("{}"); } @Test - void shouldFlattenObjectWithArrayValue(){ - String expectedFlattenedObjectWithArray = "{" + - " \":sample[0]\": 1," + - " \":sample[1]\": 2," + - " \":sample[2]\": 3}"; + void shouldFlattenObjectWithArrayValue() { + String expectedFlattenedObjectWithArray = "{" + + " \":sample[0]\": 1," + + " \":sample[1]\": 2," + + " \":sample[2]\": 3}"; JsonObject jsonWithPrimitivesArray = GSON_HELPER.fromJson("{\"sample\": [1, 2, 3]}", JsonObject.class); JsonObject result = utils.flatten(jsonWithPrimitivesArray); @@ -101,7 +101,7 @@ class JsonUtilsTest { } @Test - void shouldFlattenObjectWithEmptyArrayValue(){ + void shouldFlattenObjectWithEmptyArrayValue() { String expectedFlattenedObjectWithEmptyArray = "{\":sample\": []}"; JsonObject jsonWithEmptyArrayValue = GSON_HELPER.fromJson("{\"sample\": []}", JsonObject.class); @@ -111,7 +111,7 @@ class JsonUtilsTest { } @Test - void shouldFlattenNestedObjectWithEmptyObjectValue(){ + void shouldFlattenNestedObjectWithEmptyObjectValue() { String expectedFlattenedNestedObjectWithEmptyObject = "{\":sample:key\": {}}"; JsonObject nestedJsonWithEmptyObject = GSON_HELPER.fromJson("{\"sample\": {\"key\":{}}}", JsonObject.class); @@ -121,12 +121,12 @@ class JsonUtilsTest { } @Test - void shouldFlattenObjectWithDifferentDataTypes(){ + void shouldFlattenObjectWithDifferentDataTypes() { String jsonWithDifferentDataTypes = "{ \"topLevelKey\": {\"sampleInt\": 1, \"sampleBool\": false, \"sampleDouble\": 10.0, \"sampleString\": \"str\"}}"; - String expectedResult = "{\":topLevelKey:sampleInt\": 1," + - " \":topLevelKey:sampleBool\": \"false\"," + - " \":topLevelKey:sampleDouble\": 10.0," + - " \":topLevelKey:sampleString\": \"str\"}"; + String expectedResult = "{\":topLevelKey:sampleInt\": 1," + + " \":topLevelKey:sampleBool\": \"false\"," + + " \":topLevelKey:sampleDouble\": 10.0," + + " \":topLevelKey:sampleString\": \"str\"}"; JsonObject templateJson = GSON_HELPER.fromJson(jsonWithDifferentDataTypes, JsonObject.class); JsonObject result = utils.flatten(templateJson); @@ -135,10 +135,10 @@ class JsonUtilsTest { } @Test - void shouldHandleNullValues(){ + void shouldHandleNullValues() { String jsonWithNullValue = "{ \"topLevelKey\": {\"sampleNull\": null, \"sampleString\": \"str\"}}"; - String expectedResult = "{\":topLevelKey:sampleNull\": null," + - " \":topLevelKey:sampleString\": \"str\"}"; + String expectedResult = "{\":topLevelKey:sampleNull\": null," + + " \":topLevelKey:sampleString\": \"str\"}"; JsonObject templateJson = GSON_HELPER.fromJson(jsonWithNullValue, JsonObject.class); JsonObject result = utils.flatten(templateJson); @@ -147,7 +147,7 @@ class JsonUtilsTest { } @Test - void shouldFlattenBsonDocument(){ + void shouldFlattenBsonDocument() { Document documentInput = Document.parse(NOTIFICATION_JSON); Document result = utils.flatten(documentInput); @@ -156,7 +156,7 @@ class JsonUtilsTest { } @Test - void shouldNotChangeEmptyBsonDocument(){ + void shouldNotChangeEmptyBsonDocument() { Document input = Document.parse("{}"); Document result = utils.flatten(input); diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java index aeef870..13ea7c6 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -72,7 +72,7 @@ class TemplateSearchHelperTest { } @Test - void shouldReturnNamesForGivenComposedSearchCriteria(){ + void shouldReturnNamesForGivenComposedSearchCriteria() { String expectedComposedQueryString = "{\"$and\":[{\"keyValues\":{\"$elemMatch\":{\"k\":{\"$regex\":\":eventName(?:(\\\\[[\\\\d]+\\\\]))?$\",\"$options\":\"iu\"},\"v\":{\"$regex\":\"^\\\\QpnfRegistration_Nokia_5gDu\\\\E$\",\"$options\":\"iu\"}}}},{\"keyValues\":{\"$elemMatch\":{\"k\":{\"$regex\":\":sequence(?:(\\\\[[\\\\d]+\\\\]))?$\",\"$options\":\"iu\"},\"v\":1.0}}}]}"; Query expectedQuery = new BasicQuery(expectedComposedQueryString); @@ -105,7 +105,7 @@ class TemplateSearchHelperTest { } @Test - void shouldGetQueryForEmptyJson(){ + void shouldGetQueryForEmptyJson() { JsonObject jsonObject = GSON.fromJson("{}", JsonObject.class); String expectedComposedQueryString = "{}"; @@ -123,7 +123,7 @@ class TemplateSearchHelperTest { @Test - void shouldGetQueryWithAllTypeValues(){ + void shouldGetQueryWithAllTypeValues() { JsonObject jsonObject = GSON.fromJson("{\"stringKey\": \"stringValue\", \"numberKey\": 16.00, \"boolKey\": false}", JsonObject.class); helper.getIdsOfDocumentMatchingCriteria(jsonObject); @@ -147,13 +147,13 @@ class TemplateSearchHelperTest { } @Test - void shouldThrowExceptionWhenNullIsPresentAsCriteriaValue(){ + void shouldThrowExceptionWhenNullIsPresentAsCriteriaValue() { JsonObject jsonObject = GSON.fromJson("{\"stringKey\": \"stringValue\", \"nullKey\": null}", JsonObject.class); assertThrows(IllegalJsonValueException.class, () -> helper.getIdsOfDocumentMatchingCriteria(jsonObject)); } - private void assertJsonPreparedKeyHasCorrectStructure(Document actual, String expectedPattern){ + private void assertJsonPreparedKeyHasCorrectStructure(Document actual, String expectedPattern) { assertThat(actual.get("k").toString()).isEqualTo(Pattern.compile(String.format(":%s(?:(\\[[\\d]+\\]))?$", expectedPattern)).toString()); } diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java index 31bcf1c..6de86e0 100644 --- a/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,42 +31,42 @@ class PrimitiveValueCriteriaBuilderTest { private PrimitiveValueCriteriaBuilder builder = new PrimitiveValueCriteriaBuilder(); @Test - void testShouldAddRegexLikeCriteriaForStringType(){ + void testShouldAddRegexLikeCriteriaForStringType() { Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive("sample")); assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : { \"$regex\" : \"^\\\\Qsample\\\\E$\", \"$options\" : \"iu\" } }"); } @Test - void testShouldAddRegexLikeAndEscapeStringWithMetaChars(){ + void testShouldAddRegexLikeAndEscapeStringWithMetaChars() { Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive("[1,2,3,4,5]")); assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : { \"$regex\" : \"^\\\\Q[1,2,3,4,5]\\\\E$\", \"$options\" : \"iu\" } }"); } @Test - void testShouldAddRegexLikeCriteriaForIntType(){ + void testShouldAddRegexLikeCriteriaForIntType() { Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(1)); assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 1.0 }"); } @Test - void testShouldAddRegexLikeCriteriaForLongType(){ + void testShouldAddRegexLikeCriteriaForLongType() { Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(Long.MAX_VALUE)); assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 9.223372036854776E18 }"); } @Test - void testShouldAddRegexLikeCriteriaForDoubleType(){ + void testShouldAddRegexLikeCriteriaForDoubleType() { Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(2.5)); assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 2.5 }"); } @Test - void testShouldAddRegexLikeCriteriaForBooleanType(){ + void testShouldAddRegexLikeCriteriaForBooleanType() { Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(true)); assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : \"true\" }"); @@ -36,22 +36,283 @@ <version>1.0.0-SNAPSHOT</version> <modules> <module>pnfsimulator</module> - <module>netconfsimulator</module> - <module>deployment</module> + <module>netconfsimulator</module> + <module>deployment</module> </modules> + <properties> <nexusproxy>https://nexus.onap.org</nexusproxy> <snapshotNexusPath>/content/repositories/snapshots/</snapshotNexusPath> <releaseNexusPath>/content/repositories/releases/</releaseNexusPath> <stagingNexusPath>/content/repositories/staging/</stagingNexusPath> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <maven.compiler.source>1.8</maven.compiler.source> - <maven.compiler.target>1.8</maven.compiler.target> + <maven.compiler.source>11</maven.compiler.source> + <maven.compiler.target>11</maven.compiler.target> <docker-maven-plugin.version>0.31.0</docker-maven-plugin.version> <skipDockerPush>true</skipDockerPush> - <sonar.coverage.jacoco.xmlReportPaths>${project.reporting.outputDirectory}/jacoco-ut/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths> + <sonar.coverage.jacoco.xmlReportPaths>${project.reporting.outputDirectory}/jacoco-ut/jacoco.xml + </sonar.coverage.jacoco.xmlReportPaths> + + <!-- Compile DEPENDENCIES VERSION --> + + <maven-checkstyle-plugin.version>2.17</maven-checkstyle-plugin.version> + <docker-maven-plugin-io-fabric.version>0.31.0</docker-maven-plugin-io-fabric.version> + <spring-boot-starter.version>2.1.6.RELEASE</spring-boot-starter.version> + <spring-boot-starter-web.version>2.1.6.RELEASE</spring-boot-starter-web.version> + <spring-boot-starter-websocket.version>2.1.6.RELEASE</spring-boot-starter-websocket.version> + <spring-boot-starter-actuator.version>2.1.0.RELEASE</spring-boot-starter-actuator.version> + <spring-boot-starter-data-mongodb.version>2.1.0.RELEASE</spring-boot-starter-data-mongodb.version> + <spring-cloud-config-client.version>2.1.4.RELEASE</spring-cloud-config-client.version> + <lombok.version>1.18.2</lombok.version> + <jnc.version>1.0</jnc.version> + <spring-kafka.version>2.2.7.RELEASE</spring-kafka.version> + <commons-cli.version>1.4</commons-cli.version> + <javax.websocket-api.version>1.1</javax.websocket-api.version> + <apache.httpclient.version>4.5.6</apache.httpclient.version> + <httpmime.version>4.5.6</httpmime.version> + <springfox-swagger2.version>2.9.2</springfox-swagger2.version> + <springfox-swagger-ui.version>2.9.2</springfox-swagger-ui.version> + <logback-core.version>1.2.3</logback-core.version> + <slf4j-api.version>1.7.25</slf4j-api.version> + <commons-io.version>2.6</commons-io.version> + <json.version>20180130</json.version> + <gson.version>2.8.2</gson.version> + <commons-lang3.version>3.7</commons-lang3.version> + <jackson-datatype-jdk8.version>2.9.7</jackson-datatype-jdk8.version> + <jackson-datatype-jsr310.version>2.9.7</jackson-datatype-jsr310.version> + <vavr-match.version>0.9.2</vavr-match.version> + <vavr.version>0.9.2</vavr.version> + <quartz.version>2.2.1</quartz.version> + <quartz-jobs.version>2.2.1</quartz-jobs.version> + <guava.version>21.0</guava.version> + <logback-classic.version>1.2.3</logback-classic.version> + + <!-- TEST DEPENDENCIES VERSION --> + + <assertj-core.version>3.9.1</assertj-core.version> + <mockito-core.version>2.18.3</mockito-core.version> + <junit-jupiter-engine.version>5.3.1</junit-jupiter-engine.version> + <junit-vintage-engine.version>5.3.1</junit-vintage-engine.version> + <junit.version>4.12</junit.version> + <spring.boot.version>2.1.6.RELEASE</spring.boot.version> + <spring.kafka.version>2.2.7.RELEASE</spring.kafka.version> + <before-after-spring-test-runner.version>0.1.0</before-after-spring-test-runner.version> + <docker-compose-rule-junit4.version>0.29.1</docker-compose-rule-junit4.version> + <spring-test.version>5.0.4.RELEASE</spring-test.version> + <junit-jupiter-migrationsupport.version>5.1.0</junit-jupiter-migrationsupport.version> </properties> + <dependencyManagement> + <dependencies> + + <!-- Compile DEPENDENCIES --> + + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter</artifactId> + <version>${spring-boot-starter.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + <version>${spring-boot-starter-web.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-websocket</artifactId> + <version>${spring-boot-starter-websocket.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-mongodb</artifactId> + <version>${spring-boot-starter-data-mongodb.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-actuator</artifactId> + <version>${spring-boot-starter-actuator.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-config-client</artifactId> + <version>${spring-cloud-config-client.version}</version> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <version>${lombok.version}</version> + </dependency> + <dependency> + <groupId>org.onosproject</groupId> + <artifactId>jnc</artifactId> + <version>${jnc.version}</version> + </dependency> + <dependency> + <groupId>javax.websocket</groupId> + <artifactId>javax.websocket-api</artifactId> + <version>${javax.websocket-api.version}</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>${apache.httpclient.version}</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpmime</artifactId> + <version>${httpmime.version}</version> + </dependency> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger2</artifactId> + <version>${springfox-swagger2.version}</version> + </dependency> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger-ui</artifactId> + <version>${springfox-swagger-ui.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.kafka</groupId> + <artifactId>spring-kafka</artifactId> + <version>${spring-kafka.version}</version> + </dependency> + <dependency> + <groupId>commons-cli</groupId> + <artifactId>commons-cli</artifactId> + <version>${commons-cli.version}</version> + </dependency> + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-core</artifactId> + <version>${logback-core.version}</version> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <version>${slf4j-api.version}</version> + </dependency> + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>${commons-io.version}</version> + </dependency> + <dependency> + <groupId>org.json</groupId> + <artifactId>json</artifactId> + <version>${json.version}</version> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>${gson.version}</version> + </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + <version>${commons-lang3.version}</version> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.datatype</groupId> + <artifactId>jackson-datatype-jdk8</artifactId> + <version>${jackson-datatype-jdk8.version}</version> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.datatype</groupId> + <artifactId>jackson-datatype-jsr310</artifactId> + <version>${jackson-datatype-jsr310.version}</version> + </dependency> + <dependency> + <groupId>io.vavr</groupId> + <artifactId>vavr-match</artifactId> + <version>${vavr-match.version}</version> + </dependency> + <dependency> + <groupId>io.vavr</groupId> + <artifactId>vavr</artifactId> + <version>${vavr.version}</version> + </dependency> + <dependency> + <groupId>org.quartz-scheduler</groupId> + <artifactId>quartz</artifactId> + <version>${quartz.version}</version> + </dependency> + <dependency> + <groupId>org.quartz-scheduler</groupId> + <artifactId>quartz-jobs</artifactId> + <version>${quartz-jobs.version}</version> + </dependency> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + <version>${guava.version}</version> + </dependency> + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-classic</artifactId> + <version>${logback-classic.version}</version> + </dependency> + + <!-- TEST DEPENDENCIES --> + + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <version>${assertj-core.version}</version> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>${mockito-core.version}</version> + </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <version>${junit-jupiter-engine.version}</version> + </dependency> + <dependency> + <groupId>org.junit.vintage</groupId> + <artifactId>junit-vintage-engine</artifactId> + <version>${junit-vintage-engine.version}</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>${junit.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + <version>${spring.boot.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.kafka</groupId> + <artifactId>spring-kafka-test</artifactId> + <version>${spring.kafka.version}</version> + </dependency> + <dependency> + <groupId>org.bitbucket.radistao.test</groupId> + <artifactId>before-after-spring-test-runner</artifactId> + <version>${before-after-spring-test-runner.version}</version> + </dependency> + <dependency> + <groupId>com.palantir.docker.compose</groupId> + <artifactId>docker-compose-rule-junit4</artifactId> + <version>${docker-compose-rule-junit4.version}</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> + <version>${spring-test.version}</version> + </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-migrationsupport</artifactId> + <version>${junit-jupiter-migrationsupport.version}</version> + </dependency> + </dependencies> + </dependencyManagement> + <profiles> <profile> <id>tests</id> @@ -68,7 +329,7 @@ <plugins> <plugin> <artifactId>maven-checkstyle-plugin</artifactId> - <version>2.17</version> + <version>${maven-checkstyle-plugin.version}</version> <configuration> <suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation> <suppressionsFileExpression>checkstyle.suppressions.file</suppressionsFileExpression> @@ -77,12 +338,11 @@ <plugin> <groupId>io.fabric8</groupId> <artifactId>docker-maven-plugin</artifactId> - <version>0.31.0</version> + <version>${docker-maven-plugin-io-fabric.version}</version> </plugin> </plugins> </build> - <distributionManagement> <repository> <id>ecomp-releases</id> |