From ffd526656aad91b3bf165eea90bc158b3dc3e4fd Mon Sep 17 00:00:00 2001 From: Marcin Migdal Date: Thu, 2 Aug 2018 13:40:25 +0200 Subject: Preparing simulator for INT-607 Change-Id: Ibc5b9be98f46e699398a29a981053435bc09dc2a Issue-ID: INT-607 Signed-off-by: Marcin Migdal --- .../src/main/java/org/onap/pnfsimulator/Main.java | 36 ++--- .../onap/pnfsimulator/logging/MDCVariables.java | 15 ++ .../pnfsimulator/message/MessageConstants.java | 20 --- .../onap/pnfsimulator/message/MessageProvider.java | 26 +-- .../NetconfConfigurationCheckingTask.java | 49 ++---- .../netconfmonitor/NetconfMonitorService.java | 46 ++---- .../NetconfMonitorServiceConfiguration.java | 67 ++++---- .../netconf/NetconfConfigurationCache.java | 21 +-- .../netconf/NetconfConfigurationReader.java | 22 +-- .../netconf/NetconfConfigurationWriter.java | 34 +--- .../netconf/NetconfConnectionParams.java | 29 +--- .../netconf/NetconfSessionFactory.java | 39 ----- .../pnfsimulator/rest/SimulatorController.java | 148 +++++++++-------- .../org/onap/pnfsimulator/rest/util/DateUtil.java | 20 --- .../pnfsimulator/rest/util/ResponseBuilder.java | 35 +---- .../org/onap/pnfsimulator/simulator/Simulator.java | 135 ++++++++++------ .../pnfsimulator/simulator/SimulatorFactory.java | 57 +++---- .../simulator/client/HttpClientAdapter.java | 74 +-------- .../simulator/client/HttpClientAdapterImpl.java | 67 ++++++++ .../simulator/validation/JSONValidator.java | 46 ++++++ .../simulator/validation/ValidationException.java | 20 --- .../pnfsimulator/src/main/resources/logback.xml | 50 ++++++ .../pnfsimulator/message/MessageProviderTest.java | 22 +-- .../NetconfConfigurationCheckingTaskTest.java | 74 +++++++++ .../NetconfMonitorServiceConfigurationTest.java | 52 ++++++ .../netconfmonitor/NetconfMonitorServiceTest.java | 53 +++++++ .../netconf/NetconfConfigurationCacheTest.java | 18 +++ .../netconf/NetconfConfigurationReaderTest.java | 50 ++++++ .../netconf/NetconfConfigurationWriterTest.java | 47 ++++++ .../pnfsimulator/rest/SimulatorControllerTest.java | 175 +++++++++++++++++++++ .../onap/pnfsimulator/rest/util/DateUtilTest.java | 18 +++ .../rest/util/ResponseBuilderTest.java | 62 +++----- .../simulator/SimulatorFactoryTest.java | 60 +++++++ .../onap/pnfsimulator/simulator/SimulatorTest.java | 72 +++++++++ .../onap/pnfsimulator/simulator/TestMessages.java | 91 +++++++++++ .../client/HttpClientAdapterImplTest.java | 51 ++++++ .../simulator/validation/JSONValidatorTest.java | 103 ++++++++++++ .../src/test/resources/invalid-test-schema.json | 19 +++ .../src/test/resources/valid-test-schema.json | 19 +++ 39 files changed, 1406 insertions(+), 636 deletions(-) create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java delete mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java create mode 100644 test/mocks/pnfsimulator/src/main/resources/logback.xml create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTaskTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfigurationTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCacheTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReaderTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriterTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/validation/JSONValidatorTest.java create mode 100644 test/mocks/pnfsimulator/src/test/resources/invalid-test-schema.json create mode 100644 test/mocks/pnfsimulator/src/test/resources/valid-test-schema.json (limited to 'test/mocks/pnfsimulator/src') diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java index 0e9fe4d3d..9a4f55ad4 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java @@ -1,33 +1,29 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator; +import org.onap.pnfsimulator.message.MessageProvider; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class Main { + public static void main(String[] args) { SpringApplication.run(Main.class, args); } + + @Bean + public MessageProvider messageProvider() { + return new MessageProvider(); + } + + @Bean + public JSONValidator jsonValidator() { + return new JSONValidator(); + } } + + diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java new file mode 100644 index 000000000..ca65b55c9 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java @@ -0,0 +1,15 @@ +package org.onap.pnfsimulator.logging; + +public final class MDCVariables { + + public static final String X_ONAP_REQUEST_ID = "X-ONAP-RequestID"; + public static final String X_INVOCATION_ID = "X-InvocationID"; + public static final String REQUEST_ID = "RequestID"; + public static final String INVOCATION_ID = "InvocationID"; + public static final String INSTANCE_UUID = "InstanceUUID"; + public static final String RESPONSE_CODE = "ResponseCode"; + public static final String SERVICE_NAME = "ServiceName"; + + private MDCVariables() { + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java index 8e7c6fcfd..a0930a651 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.message; public final class MessageConstants { diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java index 44ca9666c..b21eed4fc 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java @@ -1,27 +1,8 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.message; import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER; import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import static org.onap.pnfsimulator.message.MessageConstants.EVENT_ID; import static org.onap.pnfsimulator.message.MessageConstants.EVENT_TYPE; import static org.onap.pnfsimulator.message.MessageConstants.INTERNAL_HEADER_FIELDS; @@ -35,7 +16,6 @@ import static org.onap.pnfsimulator.message.MessageConstants.PRIORITY; import static org.onap.pnfsimulator.message.MessageConstants.SEQUENCE; import static org.onap.pnfsimulator.message.MessageConstants.START_EPOCH_MICROSEC; import static org.onap.pnfsimulator.message.MessageConstants.VERSION; -import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import java.util.Map; import java.util.UUID; @@ -45,11 +25,11 @@ public class MessageProvider { public JSONObject createMessage(JSONObject params) { - if(params == null){ + if (params == null) { throw new IllegalArgumentException("Params object cannot be null"); } - Map paramsMap = params.toMap(); + Map paramsMap = params.toMap(); JSONObject root = new JSONObject(); JSONObject commonEventHeader = generateConstantCommonEventHeader(); JSONObject otherFields = generateConstantOtherFields(); diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java index b4eda0a79..edbb195c8 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java @@ -1,37 +1,17 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.netconfmonitor; import com.tailf.jnc.JNCException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import java.io.IOException; +import java.util.TimerTask; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; - -import java.io.IOException; -import java.util.TimerTask; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NetconfConfigurationCheckingTask extends TimerTask { - private static final Logger LOGGER = LogManager.getLogger(NetconfConfigurationCheckingTask.class); + + private static final Logger LOGGER = LoggerFactory.getLogger(NetconfConfigurationCheckingTask.class); private final NetconfConfigurationReader reader; private final NetconfConfigurationWriter writer; @@ -47,16 +27,15 @@ public class NetconfConfigurationCheckingTask extends TimerTask { @Override public void run() { - String currentConfiguration = ""; try { - currentConfiguration = reader.read(); - } catch (IOException|JNCException e) { - LOGGER.info("Error during configuration reading: {}", e.getMessage()); - } - if (!currentConfiguration.equals(cache.getConfiguration())) { - LOGGER.info("Configuration has changed, new configuration:\n\n{}", currentConfiguration); - writer.writeToFile(currentConfiguration); - cache.update(currentConfiguration); + String currentConfiguration = reader.read(); + if (!currentConfiguration.equals(cache.getConfiguration())) { + LOGGER.info("Configuration has changed, new configuration:\n\n{}", currentConfiguration); + writer.writeToFile(currentConfiguration); + cache.update(currentConfiguration); + } + } catch (IOException | JNCException e) { + LOGGER.warn("Error during configuration reading: {}", e.getMessage()); } } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java index c4d6198f7..ab6925b00 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java @@ -1,38 +1,20 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.netconfmonitor; import com.tailf.jnc.JNCException; +import java.io.IOException; +import java.util.Timer; +import javax.annotation.PostConstruct; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.annotation.PostConstruct; -import java.io.IOException; -import java.util.Timer; - @Service public class NetconfMonitorService { + private static final Logger LOGGER = LoggerFactory.getLogger(NetconfMonitorService.class); private static final long timePeriod = 1000L; private static final long startDelay = 0; @@ -53,15 +35,19 @@ public class NetconfMonitorService { } @PostConstruct - public void start() throws IOException, JNCException { + public void start() { setStartConfiguration(); - NetconfConfigurationCheckingTask task = new NetconfConfigurationCheckingTask(reader, writer, cache); + NetconfConfigurationCheckingTask task = new NetconfConfigurationCheckingTask(reader, writer, cache); timer.scheduleAtFixedRate(task, startDelay, timePeriod); } - private void setStartConfiguration() throws IOException, JNCException { - String configuration = reader.read(); - writer.writeToFile(configuration); - cache.update(configuration); + private void setStartConfiguration() { + try { + String configuration = reader.read(); + writer.writeToFile(configuration); + cache.update(configuration); + } catch (IOException | JNCException e) { + LOGGER.warn("Error during configuration reading: {}", e.getMessage()); + } } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java index 82ea85aee..be804a5dc 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java @@ -1,40 +1,25 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.netconfmonitor; import com.tailf.jnc.JNCException; import com.tailf.jnc.NetconfSession; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.onap.pnfsimulator.netconfmonitor.netconf.*; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - +import com.tailf.jnc.SSHConnection; +import com.tailf.jnc.SSHSession; import java.io.IOException; import java.util.Map; import java.util.Timer; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConnectionParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; @Configuration public class NetconfMonitorServiceConfiguration { - private static final Logger LOGGER = LogManager.getLogger(NetconfMonitorServiceConfiguration.class); + + private static final Logger LOGGER = LoggerFactory.getLogger(NetconfMonitorServiceConfiguration.class); private static final Map enviroment = System.getenv(); private static final String LOG_PATH = "/var/log"; @@ -44,7 +29,7 @@ public class NetconfMonitorServiceConfiguration { private static final String NETCONF_MODEL = "NETCONF_MODEL"; private static final String NETCONF_MAIN_CONTAINER = "NETCONF_MAIN_CONTAINER"; - private static final String DEFAULT_NETCONF_ADDRESS = "netopeer"; + private static final String DEFAULT_NETCONF_ADDRESS = "localhost"; private static final int DEFAULT_NETCONF_PORT = 830; private static final String DEFAULT_NETCONF_MODEL = "pnf-simulator"; private static final String DEFAULT_NETCONF_MAIN_CONTAINER = "config"; @@ -64,12 +49,18 @@ public class NetconfMonitorServiceConfiguration { @Bean public NetconfConfigurationReader configurationReader() throws IOException, JNCException { - NetconfConnectionParams params = createConnectionParams(); + NetconfConnectionParams params = resolveConnectionParams(); LOGGER.info("Configuration params are : {}", params); - NetconfSession session = NetconfSessionFactory.create(params); + NetconfSession session = createNetconfSession(params); return new NetconfConfigurationReader(session, buildModelPath()); } + NetconfSession createNetconfSession(NetconfConnectionParams params) throws IOException, JNCException { + SSHConnection sshConnection = new SSHConnection(params.address, params.port); + sshConnection.authenticateWithPassword(params.user, params.password); + return new NetconfSession( new SSHSession(sshConnection)); + } + @Bean public NetconfConfigurationWriter netconfConfigurationWriter() { return new NetconfConfigurationWriter(LOG_PATH); @@ -77,22 +68,24 @@ public class NetconfMonitorServiceConfiguration { private String buildModelPath() { return String.format("/%s:%s", - enviroment.getOrDefault(NETCONF_MODEL, DEFAULT_NETCONF_MODEL), - enviroment.getOrDefault(NETCONF_MAIN_CONTAINER, DEFAULT_NETCONF_MAIN_CONTAINER)); + enviroment.getOrDefault(NETCONF_MODEL, DEFAULT_NETCONF_MODEL), + enviroment.getOrDefault(NETCONF_MAIN_CONTAINER, DEFAULT_NETCONF_MAIN_CONTAINER)); } - private NetconfConnectionParams createConnectionParams() { + NetconfConnectionParams resolveConnectionParams() { return new NetconfConnectionParams( - enviroment.getOrDefault(NETCONF_ADDRESS, DEFAULT_NETCONF_ADDRESS), - resolveNetconfPort(), - DEFAULT_NETCONF_USER, - DEFAULT_NETCONF_PASSWORD); + enviroment.getOrDefault(NETCONF_ADDRESS, DEFAULT_NETCONF_ADDRESS), + resolveNetconfPort(), + DEFAULT_NETCONF_USER, + DEFAULT_NETCONF_PASSWORD); } private int resolveNetconfPort() { try { return Integer.parseInt(enviroment.get(NETCONF_PORT)); } catch (NumberFormatException e) { + LOGGER.warn("Invalid netconf port: {}. Default netconf port {} is set.", e.getMessage(), + DEFAULT_NETCONF_PORT); return DEFAULT_NETCONF_PORT; } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java index 820234620..852346db2 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java @@ -1,26 +1,7 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.netconfmonitor.netconf; public class NetconfConfigurationCache { + private String configuration = ""; public String getConfiguration() { diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java index e8979254d..8bd1a57a0 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java @@ -1,31 +1,11 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.netconfmonitor.netconf; import com.tailf.jnc.JNCException; import com.tailf.jnc.NetconfSession; - import java.io.IOException; public class NetconfConfigurationReader { + private final NetconfSession session; private final String netconfModelPath; diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java index 4c3d53e39..93934f080 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java @@ -1,37 +1,17 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.netconfmonitor.netconf; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import org.onap.pnfsimulator.rest.util.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NetconfConfigurationWriter { - private static final Logger LOGGER = LogManager.getLogger(NetconfConfigurationWriter.class); + + private static final Logger LOGGER = LoggerFactory.getLogger(NetconfConfigurationWriter.class); private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); private String pathToLog; @@ -45,7 +25,7 @@ public class NetconfConfigurationWriter { writer.write(configuration); LOGGER.info("Configuration wrote to file {}/{} ", pathToLog, fileName); } catch (IOException e) { - LOGGER.info("Failed to write configuration to file: {}", e.getMessage()); + LOGGER.warn("Failed to write configuration to file: {}", e.getMessage()); } } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java index 3130d2b06..df95269c3 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java @@ -1,26 +1,7 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.netconfmonitor.netconf; public class NetconfConnectionParams { + public final String address; public final int port; public final String user; @@ -36,9 +17,9 @@ public class NetconfConnectionParams { @Override public String toString() { return String.format("NetconfConnectionParams{address=%s, port=%d, user=%s, password=%s}", - address, - port, - user, - password); + address, + port, + user, + password); } } \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java deleted file mode 100644 index 4f31af5eb..000000000 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.pnfsimulator.netconfmonitor.netconf; - -import com.tailf.jnc.JNCException; -import com.tailf.jnc.NetconfSession; -import com.tailf.jnc.SSHConnection; -import com.tailf.jnc.SSHSession; - -import java.io.IOException; - -public final class NetconfSessionFactory { - private NetconfSessionFactory() {} - - public static NetconfSession create(NetconfConnectionParams params) throws IOException, JNCException { - SSHConnection sshConnection = new SSHConnection(params.address, params.port); - sshConnection.authenticateWithPassword(params.user, params.password); - SSHSession sshSession = new SSHSession(sshConnection); - return new NetconfSession(sshSession); - } -} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java index 46a63a21c..fd4f7a987 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java @@ -1,49 +1,47 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.rest; +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.message.MessageConstants.SIMULATOR_PARAMS_CONTAINER; import static org.onap.pnfsimulator.rest.util.ResponseBuilder.MESSAGE; import static org.onap.pnfsimulator.rest.util.ResponseBuilder.REMAINING_TIME; import static org.onap.pnfsimulator.rest.util.ResponseBuilder.SIMULATOR_STATUS; import static org.onap.pnfsimulator.rest.util.ResponseBuilder.TIMESTAMP; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.http.HttpStatus.OK; +import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.onap.pnfsimulator.message.MessageConstants; -import org.onap.pnfsimulator.message.MessageProvider; import org.onap.pnfsimulator.rest.util.DateUtil; import org.onap.pnfsimulator.rest.util.ResponseBuilder; import org.onap.pnfsimulator.simulator.Simulator; import org.onap.pnfsimulator.simulator.SimulatorFactory; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; import org.onap.pnfsimulator.simulator.validation.ValidationException; -import org.springframework.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -52,87 +50,104 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/simulator") public class SimulatorController { - private static final Logger LOGGER = LogManager.getLogger(Simulator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Simulator.class); private static final DateFormat RESPONSE_DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss,SSS"); - + private final Marker ENTRY = MarkerFactory.getMarker("ENTRY"); private Simulator simulator; + private JSONValidator validator; + private SimulatorFactory factory; - @PostMapping("start") - public ResponseEntity start(@RequestBody String message) { + @Autowired + public SimulatorController(JSONValidator validator, SimulatorFactory factory) { + this.validator = validator; + this.factory = factory; + } - if (simulator != null && simulator.isAlive()) { + @PostMapping("start") + public ResponseEntity start(@RequestHeader HttpHeaders headers, @RequestBody String message) { + MDC.put(REQUEST_ID, headers.getFirst(X_ONAP_REQUEST_ID)); + MDC.put(INVOCATION_ID, headers.getFirst(X_INVOCATION_ID)); + MDC.put(INSTANCE_UUID, UUID.randomUUID().toString()); + MDC.put(SERVICE_NAME, "/simulator/start"); + LOGGER.info(ENTRY,"Simulator starting"); + + if (isSimulatorRunning()) { + MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); return ResponseBuilder - .status(HttpStatus.BAD_REQUEST.value()) + .status(BAD_REQUEST) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(MESSAGE, "Cannot start simulator since it's already running") .build(); } try { + validator.validate(message, "json_schema/input_validator.json"); + JSONObject root = new JSONObject(message); JSONObject simulatorParams = root.getJSONObject(SIMULATOR_PARAMS_CONTAINER); JSONObject messageParams = root.getJSONObject(MessageConstants.MESSAGE_PARAMS_CONTAINER); - simulator = SimulatorFactory - .usingMessageProvider(new MessageProvider()) - .create(simulatorParams, messageParams); - + simulator = factory.create(simulatorParams, messageParams); simulator.start(); - } catch (JSONException e) { + MDC.put(RESPONSE_CODE, OK.toString()); + return ResponseBuilder + .status(OK) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator started") + .build(); - LOGGER.error("Cannot start simulator, invalid json format: " + e.getMessage()); - LOGGER.debug("Received json has invalid format:\n" + message); + } catch (JSONException e) { + MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); + LOGGER.warn("Cannot start simulator, invalid json format: {}", e.getMessage()); + LOGGER.debug("Received json has invalid format", e); return ResponseBuilder - .status(HttpStatus.BAD_REQUEST.value()) + .status(BAD_REQUEST) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(MESSAGE, "Cannot start simulator, invalid json format") .build(); - } catch (ValidationException e) { - - LOGGER.error("Cannot start simulator - missing mandatory parameters"); + } catch (ProcessingException | ValidationException | IOException e) { + MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); + LOGGER.warn("Json validation failed: {}", e.getMessage()); return ResponseBuilder - .status(HttpStatus.BAD_REQUEST.value()) + .status(BAD_REQUEST) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, e.getMessage()) + .put(MESSAGE, "Cannot start simulator - Json format is not compatible with schema definitions") .build(); - } catch (RuntimeException e) { - + } catch (Exception e) { + MDC.put(RESPONSE_CODE, INTERNAL_SERVER_ERROR.toString()); LOGGER.error("Cannot start simulator - unexpected exception", e); return ResponseBuilder - .status(HttpStatus.INTERNAL_SERVER_ERROR.value()) + .status(INTERNAL_SERVER_ERROR) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(MESSAGE, "Unexpected exception: " + e.getMessage()) .build(); } - - return ResponseBuilder - .status(HttpStatus.OK.value()) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, "Simulator started") - .build(); + finally { + MDC.clear(); + } } @GetMapping("status") public ResponseEntity status() { - - if (simulator != null && simulator.isAlive()) { - + if (isSimulatorRunning()) { ResponseBuilder responseBuilder = ResponseBuilder - .status(HttpStatus.OK.value()) + .status(OK) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(SIMULATOR_STATUS, "RUNNING"); - if (!simulator.isEndless()) { - responseBuilder.put(REMAINING_TIME, simulator.getRemainingTime()); - } - return responseBuilder.build(); + return !simulator.isEndless() ? + responseBuilder + .put(REMAINING_TIME, simulator.getRemainingTime()) + .build() : + responseBuilder + .build(); } else { return ResponseBuilder - .status(HttpStatus.OK.value()) + .status(OK) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(SIMULATOR_STATUS, "NOT RUNNING") .build(); @@ -141,22 +156,25 @@ public class SimulatorController { @PostMapping("stop") public ResponseEntity stop() { - - if (simulator != null && simulator.isAlive()) { + if (isSimulatorRunning()) { simulator.interrupt(); return ResponseBuilder - .status(HttpStatus.OK.value()) + .status(OK) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(MESSAGE, "Simulator successfully stopped") .build(); } else { return ResponseBuilder - .status(HttpStatus.BAD_REQUEST.value()) + .status(BAD_REQUEST) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(MESSAGE, "Cannot stop simulator, because it's not running") .build(); } } + + private boolean isSimulatorRunning() { + return simulator != null && simulator.isAlive(); + } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java index 73443d06e..f48611c6b 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.rest.util; import java.text.DateFormat; diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java index 31d22a713..25c040e06 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java @@ -1,27 +1,8 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.rest.util; import java.util.LinkedHashMap; import java.util.Map; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; public class ResponseBuilder { @@ -31,16 +12,16 @@ public class ResponseBuilder { public static final String SIMULATOR_STATUS = "simulatorStatus"; public static final String REMAINING_TIME = "remainingTime"; - private int statusCode; + private HttpStatus httpStatus; private Map body = new LinkedHashMap<>(); - private ResponseBuilder(int statusCode) { - this.statusCode = statusCode; + private ResponseBuilder(HttpStatus httpStatus) { + this.httpStatus = httpStatus; } - public static ResponseBuilder status(int statusCode) { + public static ResponseBuilder status(HttpStatus httpStatus) { - return new ResponseBuilder(statusCode); + return new ResponseBuilder(httpStatus); } public ResponseBuilder put(String key, Object value) { @@ -52,10 +33,10 @@ public class ResponseBuilder { public ResponseEntity build() { if (body.isEmpty()) { - return ResponseEntity.status(statusCode).build(); + return ResponseEntity.status(httpStatus).build(); } - return ResponseEntity.status(statusCode).body(body); + return ResponseEntity.status(httpStatus).body(body); } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java index 0c713e127..4051dcfb0 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java @@ -1,70 +1,62 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.simulator; import java.time.Duration; import java.time.Instant; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import java.util.Map; import org.json.JSONObject; import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; +import org.onap.pnfsimulator.simulator.client.HttpClientAdapterImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; public class Simulator extends Thread { - private static final Logger LOGGER = LogManager.getLogger(Simulator.class); - private HttpClientAdapter clientProvider; + private static final Logger LOGGER = LoggerFactory.getLogger(Simulator.class); + private final Marker EXIT = MarkerFactory.getMarker("EXIT"); + private Map contextMap = MDC.getCopyOfContextMap(); + private boolean isEndless; + private String vesUrl; + private HttpClientAdapter httpClient; private JSONObject messageBody; - private Instant endTime; private Duration duration; private Duration interval; - private final boolean isEndless; - - public Simulator(String vesServerUrl, JSONObject messageBody, Duration duration, Duration interval) { - this.messageBody = messageBody; - this.duration = duration; - this.interval = interval; - this.clientProvider = new HttpClientAdapter(vesServerUrl); - this.isEndless = duration.getSeconds() == 0; + private Instant endTime; + + private Simulator() { } - public void run() { - LOGGER.info("Simulation started - duration: " + getDuration() + ", interval: {}s", interval.getSeconds()); + public static Builder builder() { + return new Builder(); + } + public void run() { + setMdcContextMap(contextMap); + LOGGER.info("Simulation started - duration: {}, interval: {}s", getDuration(), interval.getSeconds()); endTime = Instant.now().plus(duration); - boolean isEndless = isEndless(); while (isEndless || runningTimeNotExceeded()) { try { - LOGGER.debug("Message to be sent:\n" + messageBody.toString(4)); - clientProvider.sendMsg(messageBody.toString()); + LOGGER.debug("Message to be sent:\n" + getMessage()); + httpClient.send(messageBody.toString(), vesUrl); Thread.sleep(interval.toMillis()); } catch (InterruptedException e) { LOGGER.info("Simulation interrupted"); return; } } - LOGGER.info("Simulation finished"); + LOGGER.info(EXIT, "Simulation finished"); + MDC.clear(); } - public boolean isEndless() { - return isEndless; + private void setMdcContextMap(Map mdcContextMap) { + if(mdcContextMap != null) + MDC.setContextMap(mdcContextMap); + } + + private String getMessage() { + return messageBody.toString(4); } private String getDuration() { @@ -75,10 +67,65 @@ public class Simulator extends Thread { return Instant.now().isBefore(endTime); } - public long getRemainingTime(){ + public boolean isEndless() { + return isEndless; + } + + public long getRemainingTime() { return Duration.between(Instant.now(), endTime).getSeconds(); } - public String getMessage(){ - return messageBody.toString(4); + + public static class Builder { + + private String vesUrl; + private HttpClientAdapter httpClient; + private JSONObject messageBody; + private Duration duration; + private Duration interval; + + private Builder() { + this.vesUrl = ""; + this.httpClient = new HttpClientAdapterImpl(); + this.messageBody = new JSONObject(); + this.duration = Duration.ZERO; + this.interval = Duration.ZERO; + } + + public Builder withVesUrl(String vesUrl) { + this.vesUrl = vesUrl; + return this; + } + + public Builder withCustomHttpClientAdapter(HttpClientAdapter httpClient) { + this.httpClient = httpClient; + return this; + } + + public Builder withMessageBody(JSONObject messageBody) { + this.messageBody = messageBody; + return this; + } + + public Builder withDuration(Duration duration) { + this.duration = duration; + return this; + } + + + public Builder withInterval(Duration interval) { + this.interval = interval; + return this; + } + + public Simulator build() { + Simulator simulator = new Simulator(); + simulator.vesUrl = this.vesUrl; + simulator.httpClient = this.httpClient; + simulator.messageBody = this.messageBody; + simulator.duration = this.duration; + simulator.interval = this.interval; + simulator.isEndless = duration.equals(Duration.ZERO); + return simulator; + } } } \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java index 7f1b0a808..443f1547c 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java @@ -1,57 +1,48 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.simulator; -import static java.lang.Integer.*; +import static java.lang.Integer.parseInt; import static org.onap.pnfsimulator.message.MessageConstants.MESSAGE_INTERVAL; import static org.onap.pnfsimulator.message.MessageConstants.TEST_DURATION; import static org.onap.pnfsimulator.message.MessageConstants.VES_SERVER_URL; +import com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.io.IOException; import java.time.Duration; import org.json.JSONObject; import org.onap.pnfsimulator.message.MessageProvider; -import org.onap.pnfsimulator.simulator.validation.ParamsValidator; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; import org.onap.pnfsimulator.simulator.validation.ValidationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +@Service public class SimulatorFactory { - private MessageProvider messageProvider; + private static final String DEFAULT_OUTPUT_SCHEMA_PATH = "json_schema/output_validator.json"; - public static SimulatorFactory usingMessageProvider(MessageProvider messageProvider) { - return new SimulatorFactory(messageProvider); - } + private MessageProvider messageProvider; + private JSONValidator validator; - private SimulatorFactory(MessageProvider messageProvider) { + @Autowired + public SimulatorFactory(MessageProvider messageProvider, JSONValidator validator) { this.messageProvider = messageProvider; + this.validator = validator; } - public Simulator create(JSONObject simulatorParams, JSONObject messageParams) throws ValidationException { - - ParamsValidator.forParams(simulatorParams, messageParams).validate(); - + public Simulator create(JSONObject simulatorParams, JSONObject messageParams) + throws ProcessingException, IOException, ValidationException { Duration duration = Duration.ofSeconds(parseInt(simulatorParams.getString(TEST_DURATION))); Duration interval = Duration.ofSeconds(parseInt(simulatorParams.getString(MESSAGE_INTERVAL))); - String vesServerUrl = simulatorParams.getString(VES_SERVER_URL); + String vesUrl = simulatorParams.getString(VES_SERVER_URL); JSONObject messageBody = messageProvider.createMessage(messageParams); - return new Simulator(vesServerUrl, messageBody, duration, interval); + validator.validate(messageBody.toString(), DEFAULT_OUTPUT_SCHEMA_PATH); + + return Simulator.builder() + .withVesUrl(vesUrl) + .withDuration(duration) + .withInterval(interval) + .withMessageBody(messageBody) + .build(); } } \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java index 35f0b6820..020cb8416 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java @@ -1,76 +1,6 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.simulator.client; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -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.impl.client.HttpClientBuilder; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class HttpClientAdapter { - - private static final Logger LOGGER = LogManager.getLogger(HttpClientAdapter.class); - private static final String CONTENT_TYPE = "Content-Type"; - private static final String APPLICATION_JSON = "application/json"; - - private HttpClient client; - private String url; - - public HttpClientAdapter(String url) { - - RequestConfig config = RequestConfig.custom() - .setConnectTimeout(1000) - .setConnectionRequestTimeout(1000) - .setSocketTimeout(1000) - .build(); - - this.client = HttpClientBuilder - .create() - .setDefaultRequestConfig(config) - .build(); - - this.url = url; - } - - public void sendMsg(String content) { - try { - HttpPost request = createRequest(content); - HttpResponse response = client.execute(request); - LOGGER.info("MESSAGE SENT, VES RESPONSE CODE: {}", response.getStatusLine()); - } catch (IOException e) { - LOGGER.info("ERROR SENDING MESSAGE TO VES: {}", e.getMessage()); - } - } +public interface HttpClientAdapter { - private HttpPost createRequest(String content) throws UnsupportedEncodingException { - StringEntity stringEntity = new StringEntity(content); - HttpPost request = new HttpPost(url); - request.addHeader(CONTENT_TYPE, APPLICATION_JSON); - request.setEntity(stringEntity); - return request; - } + void send(String content, String url); } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java new file mode 100644 index 000000000..c38ac3efa --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java @@ -0,0 +1,67 @@ +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.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.impl.client.HttpClientBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +public class HttpClientAdapterImpl implements HttpClientAdapter { + + private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientAdapterImpl.class); + private static final String CONTENT_TYPE = "Content-Type"; + private static final String APPLICATION_JSON = "application/json"; + private final Marker INVOKE = MarkerFactory.getMarker("INVOKE"); + private static final RequestConfig CONFIG = RequestConfig.custom() + .setConnectTimeout(1000) + .setConnectionRequestTimeout(1000) + .setSocketTimeout(1000) + .build(); + + private HttpClient client; + + public HttpClientAdapterImpl(HttpClient client) { + this.client = client; + } + + public HttpClientAdapterImpl() { + this.client = HttpClientBuilder + .create() + .setDefaultRequestConfig(CONFIG) + .build(); + } + + @Override + public void send(String content, String url) { + try { + HttpPost request = createRequest(content, url); + HttpResponse response = client.execute(request); + LOGGER.info(INVOKE, "Message sent, ves response code: {}", response.getStatusLine()); + } catch (IOException e) { + LOGGER.warn("Error sending message to ves: {}", e.getMessage()); + } + } + + private HttpPost createRequest(String content, String url) throws UnsupportedEncodingException { + HttpPost request = new HttpPost(url); + StringEntity stringEntity = new StringEntity(content); + request.addHeader(CONTENT_TYPE, APPLICATION_JSON); + request.addHeader(X_ONAP_REQUEST_ID, MDC.get(REQUEST_ID)); + request.addHeader(X_INVOCATION_ID, UUID.randomUUID().toString()); + request.setEntity(stringEntity); + return request; + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java new file mode 100644 index 000000000..37fd71a81 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java @@ -0,0 +1,46 @@ +package org.onap.pnfsimulator.simulator.validation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.github.fge.jackson.JsonLoader; +import com.github.fge.jsonschema.core.exceptions.ProcessingException; +import com.github.fge.jsonschema.core.report.LogLevel; +import com.github.fge.jsonschema.core.report.ProcessingMessage; +import com.github.fge.jsonschema.core.report.ProcessingReport; +import com.github.fge.jsonschema.main.JsonSchema; +import com.github.fge.jsonschema.main.JsonSchemaFactory; +import com.google.gson.JsonParser; +import java.io.FileReader; +import java.io.IOException; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +public class JSONValidator { + + public void validate(String data, String jsonSchemaPath) + throws ValidationException, ProcessingException, IOException { + String jsonSchema = readJsonSchemaAsString(jsonSchemaPath); + JsonNode jsonData = JsonLoader.fromString(data); + ProcessingReport report = createJsonSchema(jsonSchema).validate(jsonData); + + if (!report.isSuccess()) { + throw new ValidationException(constructValidationErrors(report)); + } + } + + private String readJsonSchemaAsString(String schemaPath) throws IOException { + try (FileReader reader = new FileReader(schemaPath)) { + return new JsonParser().parse(reader).toString(); + } + } + + private JsonSchema createJsonSchema(String schema) throws ProcessingException, IOException { + return JsonSchemaFactory.byDefault().getJsonSchema(JsonLoader.fromString(schema)); + } + + private String constructValidationErrors(ProcessingReport report) { + return StreamSupport.stream(report.spliterator(), false) + .filter(entry -> entry.getLogLevel() == LogLevel.ERROR) + .map(ProcessingMessage::getMessage) + .collect(Collectors.joining("\n")); + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java index 086997f85..9855a784e 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.simulator.validation; public class ValidationException extends Exception { diff --git a/test/mocks/pnfsimulator/src/main/resources/logback.xml b/test/mocks/pnfsimulator/src/main/resources/logback.xml new file mode 100644 index 000000000..de34b9ae3 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/resources/logback.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + %nopexception%logger + |%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX,UTC} + |%level + |%replace(%replace(%message){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%mdc){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%rootException){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%marker){'\t','\\\\t'}){'\n','\\\\n'} + |%thread + |%n + + + + + + %nopexception%logger + |%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX,UTC} + |%level + |%replace(%replace(%message){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%mdc){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%rootException){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%marker){'\t','\\\\t'}){'\n','\\\\n'} + |%thread + |%n + + ${log-path}/${outputFilename}.log + + ${archive}/${outputFilename}.%d{yyyy-MM-dd}.%i.log.zip + ${maxFileSize} + ${maxHistory} + ${totalSizeCap} + + + + + + + + diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java index 41df397a7..b08cc4ce6 100644 --- a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.message; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -25,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER; import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import static org.onap.pnfsimulator.message.MessageConstants.EVENT_ID; import static org.onap.pnfsimulator.message.MessageConstants.EVENT_TYPE; import static org.onap.pnfsimulator.message.MessageConstants.INTERNAL_HEADER_FIELDS; @@ -37,7 +18,6 @@ import static org.onap.pnfsimulator.message.MessageConstants.PRIORITY; import static org.onap.pnfsimulator.message.MessageConstants.SEQUENCE; import static org.onap.pnfsimulator.message.MessageConstants.START_EPOCH_MICROSEC; import static org.onap.pnfsimulator.message.MessageConstants.VERSION; -import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import java.util.UUID; import org.json.JSONObject; diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTaskTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTaskTest.java new file mode 100644 index 000000000..438c6a8ee --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTaskTest.java @@ -0,0 +1,74 @@ +package org.onap.pnfsimulator.netconfmonitor; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.tailf.jnc.JNCException; +import java.io.IOException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; + +class NetconfConfigurationCheckingTaskTest { + + private NetconfConfigurationCheckingTask checkingTask; + + @Mock + private NetconfConfigurationReader reader; + @Mock + private NetconfConfigurationWriter writer; + @Mock + private NetconfConfigurationCache cache; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + checkingTask = new NetconfConfigurationCheckingTask(reader, writer, cache); + } + + @Test + void run_should_update_configuration_when_changed() throws IOException, JNCException { + String configuration = "newConfiguration"; + when(reader.read()).thenReturn(configuration); + when(cache.getConfiguration()).thenReturn("oldConfiguration"); + + checkingTask.run(); + + verify(reader).read(); + verify(cache).getConfiguration(); + verify(writer).writeToFile(configuration); + verify(cache).update(configuration); + } + + @Test + void run_should_not_update_configuration_when_same() throws IOException, JNCException { + String configuration = "configuration"; + when(reader.read()).thenReturn(configuration); + when(cache.getConfiguration()).thenReturn("configuration"); + + checkingTask.run(); + + verify(reader).read(); + verify(cache).getConfiguration(); + verify(writer, never()).writeToFile(configuration); + verify(cache, never()).update(configuration); + } + + @Test + void run_should_not_take_any_action_when_failed_to_read_configuration() throws IOException, JNCException { + when(reader.read()).thenThrow(new IOException()); + + checkingTask.run(); + + verify(reader).read(); + verify(cache, never()).getConfiguration(); + verify(writer, never()).writeToFile(any()); + verify(cache, never()).update(any()); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfigurationTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfigurationTest.java new file mode 100644 index 000000000..3d3e3a87c --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfigurationTest.java @@ -0,0 +1,52 @@ +package org.onap.pnfsimulator.netconfmonitor; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import com.tailf.jnc.JNCException; +import com.tailf.jnc.NetconfSession; +import java.io.IOException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +class NetconfMonitorServiceConfigurationTest { + + private NetconfMonitorServiceConfiguration configuration; + + @Mock + private NetconfSession netconfSession; + + @BeforeEach + void setup() { + netconfSession = mock(NetconfSession.class); + configuration = spy(new NetconfMonitorServiceConfiguration()); + } + + @Test + void readNetconfConfiguration() throws IOException, JNCException { + doReturn(netconfSession).when(configuration).createNetconfSession(any()); + + assertNotNull(configuration.configurationReader()); + verify(configuration).createNetconfSession(any()); + } + + @Test + void configurationCacheIsNotNull() { + assertNotNull(configuration.configurationCache()); + } + + @Test + void netconfConfigurationWriterIsNotNull() { + assertNotNull(configuration.netconfConfigurationWriter()); + } + + @Test + void timerIsNotNull() { + assertNotNull(configuration.timer()); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceTest.java new file mode 100644 index 000000000..3562faeb1 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceTest.java @@ -0,0 +1,53 @@ +package org.onap.pnfsimulator.netconfmonitor; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.tailf.jnc.JNCException; +import java.io.IOException; +import java.util.Timer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; + +class NetconfMonitorServiceTest { + + private NetconfMonitorService service; + + @Mock + private Timer timer; + @Mock + private NetconfConfigurationReader reader; + @Mock + private NetconfConfigurationWriter writer; + @Mock + private NetconfConfigurationCache cache; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + service = new NetconfMonitorService(timer, reader, writer, cache); + } + + @Test + void startNetconfService() throws IOException, JNCException { + when(reader.read()).thenReturn("message"); + doNothing().when(writer).writeToFile(anyString()); + doNothing().when(cache).update(anyString()); + + service.start(); + + verify(cache, times(1)).update(anyString()); + verify(writer, times(1)).writeToFile(anyString()); + verify(timer, times(1)).scheduleAtFixedRate(any(), anyLong(), anyLong()); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCacheTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCacheTest.java new file mode 100644 index 000000000..ebfac011c --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCacheTest.java @@ -0,0 +1,18 @@ +package org.onap.pnfsimulator.netconfmonitor.netconf; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class NetconfConfigurationCacheTest { + + private static final String CONFIGURATION = "sampleConfiguration"; + + @Test + void changeConfigurationAfterUpdate() { + NetconfConfigurationCache configurationCache = new NetconfConfigurationCache(); + configurationCache.update(CONFIGURATION); + + assertEquals(CONFIGURATION, configurationCache.getConfiguration()); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReaderTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReaderTest.java new file mode 100644 index 000000000..451b0a65e --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReaderTest.java @@ -0,0 +1,50 @@ +package org.onap.pnfsimulator.netconfmonitor.netconf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.tailf.jnc.Element; +import com.tailf.jnc.JNCException; +import com.tailf.jnc.NetconfSession; +import com.tailf.jnc.NodeSet; +import java.io.IOException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +class NetconfConfigurationReaderTest { + + private static final String NETCONF_MODEL_PATH = ""; + private static final String EXPECTED_STRING_XML = ""; + private NetconfConfigurationReader reader; + + @Mock + private NetconfSession netconfSession; + @Mock + private NodeSet nodeSet; + @Mock + private Element element; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + reader = new NetconfConfigurationReader(netconfSession, NETCONF_MODEL_PATH); + } + + @Test + void properlyReadXML() throws IOException, JNCException { + when(netconfSession.getConfig(anyString())).thenReturn(nodeSet); + when(nodeSet.first()).thenReturn(element); + when(element.toXMLString()).thenReturn(EXPECTED_STRING_XML); + + String result = reader.read(); + + verify(netconfSession).getConfig(anyString()); + verify(nodeSet).first(); + verify(element).toXMLString(); + assertEquals(EXPECTED_STRING_XML, result); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriterTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriterTest.java new file mode 100644 index 000000000..462be4bd5 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriterTest.java @@ -0,0 +1,47 @@ +package org.onap.pnfsimulator.netconfmonitor.netconf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import org.apache.commons.io.FileUtils; +import org.junit.Rule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.rules.TemporaryFolder; + +@EnableRuleMigrationSupport +class NetconfConfigurationWriterTest { + + private static final String TEST_CONFIGURATION = "test-configuration"; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + void writeToFile_should_write_sample_config_when_directory_exists() throws IOException { + File file = temporaryFolder.newFolder("temp"); + NetconfConfigurationWriter configurationWriter = new NetconfConfigurationWriter(file.getPath()); + + configurationWriter.writeToFile(TEST_CONFIGURATION); + + File[] files = file.listFiles(); + assertEquals(1, files.length); + + String content = FileUtils.readFileToString(files[0], "UTF-8"); + assertEquals(TEST_CONFIGURATION, content); + } + + @Test + void writeToFile_should_not_write_config_when_directory_doesnt_exist() { + String logFolderPath = "/not/existing/logs"; + NetconfConfigurationWriter configurationWriter = new NetconfConfigurationWriter(logFolderPath); + + configurationWriter.writeToFile(TEST_CONFIGURATION); + + assertFalse(Files.exists(Paths.get(logFolderPath))); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java new file mode 100644 index 000000000..9a56bcc7d --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java @@ -0,0 +1,175 @@ +package org.onap.pnfsimulator.rest; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +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.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.simulator.Simulator; +import org.onap.pnfsimulator.simulator.SimulatorFactory; +import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; +import org.onap.pnfsimulator.simulator.validation.ValidationException; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +class SimulatorControllerTest { + + private static final String START_URL = "/simulator/start"; + private static final String STOP_URL = "/simulator/stop"; + private static final String STATUS_URL = "/simulator/status"; + private static final String JSON_MSG_EXPRESSION = "$.message"; + private static final String JSON_STATUS_EXPRESSION = "$.simulatorStatus"; + private static final String PROPER_JSON = "{\n" + + " \"simulatorParams\": {\n" + + " \"vesServerUrl\": \"http://10.154.187.70:8080/eventListener/v5\",\n" + + " \"testDuration\": \"10\",\n" + + " \"messageInterval\": \"1\"\n" + + " },\n" + + " \"messageParams\": {\n" + + " \"pnfSerialNumber\": \"val1\",\n" + + " \"pnfVendorName\": \"val2\",\n" + + " \"pnfOamIpv4Address\": \"val3\",\n" + + " \"pnfOamIpv6Address\": \"val4\",\n" + + " \"pnfFamily\": \"val5\",\n" + + " \"pnfModelNumber\": \"val6\",\n" + + " \"pnfSoftwareVersion\": \"val7\",\n" + + " \"pnfType\": \"val8\",\n" + + " \"eventName\": \"val9\",\n" + + " \"nfNamingCode\": \"val10\",\n" + + " \"nfcNamingCode\": \"val11\",\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + " }\n" + + "}"; + private static final String WRONG_JSON = "{\n" + + " \"mes\": {\n" + + " \"vesServerUrl\": \"http://10.154.187.70:8080/eventListener/v5\",\n" + + " \"testDuration\": \"10\",\n" + + " \"messageInterval\": \"1\"\n" + + " },\n" + + " \"messageParams\": {\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + " }\n" + + "}\n"; + + private MockMvc mockMvc; + + @InjectMocks + private SimulatorController controller; + + @Mock + private SimulatorFactory factory; + @Mock + private JSONValidator validator; + + private Simulator simulator; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + simulator = createEndlessSimulator(); + mockMvc = MockMvcBuilders + .standaloneSetup(controller) + .build(); + } + + private Simulator createEndlessSimulator() { + return spy(Simulator.builder() + .withCustomHttpClientAdapter(mock(HttpClientAdapter.class)) + .withInterval(Duration.ofMinutes(1)) + .build()); + } + + @Test + void wrongJSONFormatOnStart() throws Exception { + when(factory.create(any(), any())).thenReturn(simulator); + doThrow(new ValidationException("")).when(validator).validate(anyString(), anyString()); + + mockMvc.perform(post("/simulator/start").content(WRONG_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("Cannot start simulator - Json format " + + "is not compatible with schema definitions")); + verify(validator).validate(anyString(), anyString()); + } + + @Test + void startSimulatorProperly() throws Exception { + startSimulator(); + + verify(validator).validate(anyString(), anyString()); + verify(factory).create(any(), any()); + verify(simulator).start(); + } + + @Test + void notStartWhenAlreadyRunning() throws Exception { + startSimulator(); + + mockMvc + .perform(post(START_URL).content(PROPER_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Cannot start simulator since it's already running")); + } + + @Test + void stopSimulatorWhenRunning() throws Exception { + startSimulator(); + + mockMvc + .perform(post(STOP_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Simulator successfully stopped")); + } + + @Test + void getNotRunningMessageWhenOff() throws Exception { + mockMvc + .perform(post(STOP_URL)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Cannot stop simulator, because it's not running")); + } + + @Test + void getRunningStatusWhenOn() throws Exception { + startSimulator(); + + mockMvc + .perform(get(STATUS_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_STATUS_EXPRESSION).value("RUNNING")); + } + + @Test + void getNotRunningStatusWhenOff() throws Exception { + mockMvc + .perform(get(STATUS_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_STATUS_EXPRESSION).value("NOT RUNNING")); + } + + private void startSimulator() throws Exception { + when(factory.create(any(), any())).thenReturn(simulator); + + mockMvc + .perform(post(START_URL).content(PROPER_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Simulator started")); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java new file mode 100644 index 000000000..6dc84499d --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java @@ -0,0 +1,18 @@ +package org.onap.pnfsimulator.rest.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import org.junit.jupiter.api.Test; + +class DateUtilTest { + + @Test + void getFormattedDate() { + Calendar currentCalendar = Calendar.getInstance(); + String expectedResult = String.valueOf(currentCalendar.get(Calendar.YEAR)); + + assertEquals(expectedResult, DateUtil.getTimestamp(new SimpleDateFormat("yyyy"))); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java index a8147340e..8dc825cda 100644 --- a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java @@ -1,59 +1,45 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.pnfsimulator.rest.util; -import org.junit.jupiter.api.BeforeEach; +import static org.junit.jupiter.api.Assertions.assertAll; +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; -import java.util.Map; -import static org.junit.jupiter.api.Assertions.*; public class ResponseBuilderTest { - private static final int SAMPLE_STATUS_CODE = 200; - private ResponseBuilder builder; - @BeforeEach - void setup() { - builder = ResponseBuilder.status(SAMPLE_STATUS_CODE); - } + private static final HttpStatus SAMPLE_STATUS = HttpStatus.OK; @Test - void checkResponseBodySize() { - builder.put("sample", "sample"); - ResponseEntity responseEntity = builder.build(); - Map body = (Map) responseEntity.getBody(); + void response_should_have_empty_body_when_built_immediately() { + ResponseEntity responseEntity = ResponseBuilder.status(SAMPLE_STATUS).build(); - assertEquals(body.size(), 1); + assertAll( + () -> assertEquals(responseEntity.getStatusCode(), SAMPLE_STATUS), + () -> assertNull(responseEntity.getBody()) + ); } @Test - void buildProperResponseEntity() { - ResponseEntity responseEntity = builder.build(); + void builder_should_set_response_status_and_body() { + String key = "key"; + String value = "value"; + ResponseEntity response = ResponseBuilder + .status(SAMPLE_STATUS) + .put(key, value) + .build(); + + Map body = (Map) response.getBody(); assertAll( - () -> assertEquals(responseEntity.getStatusCode(), HttpStatus.OK), - () -> assertNull(responseEntity.getBody()) + () -> assertEquals(SAMPLE_STATUS, response.getStatusCode()), + () -> assertEquals(value, body.get(key)) ); } + } \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java new file mode 100644 index 000000000..da4c97b30 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java @@ -0,0 +1,60 @@ +package org.onap.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_MESSAGE_PARAMS_1; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_MESSAGE_PARAMS_2; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_MESSAGE_PARAMS_3; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_SIMULATOR_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_MESSAGE_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_SIMULATOR_PARAMS; + +import com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.io.IOException; +import org.json.JSONException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.onap.pnfsimulator.message.MessageProvider; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; +import org.onap.pnfsimulator.simulator.validation.ValidationException; + +class SimulatorFactoryTest { + + + private SimulatorFactory simulatorFactory; + + @BeforeEach + void setUp() { + simulatorFactory = new SimulatorFactory(new MessageProvider(), new JSONValidator()); + } + + @Test + void should_successfully_create_simulator_given_valid_params_and_valid_output_message() + throws ValidationException, IOException, ProcessingException { + assertNotNull(simulatorFactory.create(VALID_SIMULATOR_PARAMS, VALID_MESSAGE_PARAMS)); + } + + @Test + void should_throw_given_invalid_params() { + assertThrows( + JSONException.class, + () -> simulatorFactory.create(INVALID_SIMULATOR_PARAMS, VALID_MESSAGE_PARAMS)); + } + + @Test + void should_throw_given_valid_params_and_invalid_output_message() { + + assertThrows( + ValidationException.class, + () -> simulatorFactory.create(VALID_SIMULATOR_PARAMS, INVALID_MESSAGE_PARAMS_1)); + + assertThrows( + ValidationException.class, + () -> simulatorFactory.create(VALID_SIMULATOR_PARAMS, INVALID_MESSAGE_PARAMS_2)); + + assertThrows( + ValidationException.class, + () -> simulatorFactory.create(VALID_SIMULATOR_PARAMS, INVALID_MESSAGE_PARAMS_3)); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorTest.java new file mode 100644 index 000000000..86baac740 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorTest.java @@ -0,0 +1,72 @@ +package org.onap.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; + +import java.time.Duration; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.mockito.Mockito; +import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; + +class SimulatorTest { + + private static final String TEST_VES_URL = "http://test-ves-url"; + + @Test + void builder_should_create_endless_simulator_when_duration_not_specified() { + Simulator simulator = Simulator + .builder() + .withDuration(Duration.ofSeconds(1)) + .withVesUrl(TEST_VES_URL).build(); + + assertFalse(simulator.isEndless()); + + simulator = Simulator + .builder() + .withVesUrl(TEST_VES_URL).build(); + + assertTrue(simulator.isEndless()); + } + + @Test + void simulator_should_send_given_message() { + + JSONObject messageBody = new JSONObject("{\"key\":\"val\"}"); + HttpClientAdapter httpClientMock = Mockito.mock(HttpClientAdapter.class); + + Simulator simulator = Simulator.builder() + .withDuration(Duration.ofMillis(100)) + .withInterval(Duration.ofMillis(10)) + .withMessageBody(messageBody) + .withCustomHttpClientAdapter(httpClientMock) + .withVesUrl(TEST_VES_URL).build(); + + simulator.start(); + + assertTimeout(Duration.ofMillis(150), (Executable) simulator::join); + verify(httpClientMock, atLeast(2)).send(messageBody.toString(), TEST_VES_URL); + } + + @Test + void simulator_should_stop_when_interrupted() { + + JSONObject messageBody = new JSONObject("{\"key\":\"val\"}"); + HttpClientAdapter httpClientMock = Mockito.mock(HttpClientAdapter.class); + + Simulator simulator = Simulator.builder() + .withInterval(Duration.ofSeconds(1)) + .withMessageBody(messageBody) + .withCustomHttpClientAdapter(httpClientMock) + .withVesUrl(TEST_VES_URL).build(); + + simulator.start(); + simulator.interrupt(); + + assertTimeout(Duration.ofSeconds(1), (Executable) simulator::join); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java new file mode 100644 index 000000000..26249ad6c --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java @@ -0,0 +1,91 @@ +package org.onap.pnfsimulator.simulator; + +import org.json.JSONObject; + +final class TestMessages { + + static final JSONObject VALID_SIMULATOR_PARAMS = new JSONObject( + "{\n" + + " \"vesServerUrl\": \"http://10.42.111.42:8080/eventListener/v5\",\n" + + " \"testDuration\": \"10\",\n" + + " \"messageInterval\": \"1\"\n" + + "}"); + + + static final JSONObject VALID_MESSAGE_PARAMS = new JSONObject( + "{\n" + + " \"pnfSerialNumber\": \"val1\",\n" + + " \"pnfVendorName\": \"val2\",\n" + + " \"pnfOamIpv4Address\": \"val3\",\n" + + " \"pnfOamIpv6Address\": \"val4\",\n" + + " \"pnfFamily\": \"val5\",\n" + + " \"pnfModelNumber\": \"val6\",\n" + + " \"pnfSoftwareVersion\": \"val7\",\n" + + " \"pnfType\": \"val8\",\n" + + " \"eventName\": \"val9\",\n" + + " \"nfNamingCode\": \"val10\",\n" + + " \"nfcNamingCode\": \"val11\",\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + "}"); + + static final JSONObject INVALID_SIMULATOR_PARAMS = new JSONObject( + "{\n" + + " \"vesServerUrl\": \"http://10.42.111.42:8080/eventListener/v5\",\n" + + " \"messageInterval\": \"1\"\n" + + "}"); + + + static final JSONObject INVALID_MESSAGE_PARAMS_1 = new JSONObject( + "{\n" + + " \"pnfSerialNumber\": \"val1\",\n" + + " \"pnfVendorName\": \"val2\",\n" + + " \"pnfFamily\": \"val5\",\n" + + " \"pnfModelNumber\": \"val6\",\n" + + " \"pnfSoftwareVersion\": \"val7\",\n" + + " \"pnfType\": \"val8\",\n" + + " \"eventName\": \"val9\",\n" + + " \"nfNamingCode\": \"val10\",\n" + + " \"nfcNamingCode\": \"val11\",\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + "}"); + + static final JSONObject INVALID_MESSAGE_PARAMS_2 = new JSONObject( + "{\n" + + " \"pnfVendorName\": \"val2\",\n" + + " \"pnfOamIpv4Address\": \"val3\",\n" + + " \"pnfOamIpv6Address\": \"val4\",\n" + + " \"pnfFamily\": \"val5\",\n" + + " \"pnfModelNumber\": \"val6\",\n" + + " \"pnfSoftwareVersion\": \"val7\",\n" + + " \"pnfType\": \"val8\",\n" + + " \"eventName\": \"val9\",\n" + + " \"nfNamingCode\": \"val10\",\n" + + " \"nfcNamingCode\": \"val11\",\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + "}"); + + static final JSONObject INVALID_MESSAGE_PARAMS_3 = new JSONObject( + "{\n" + + " \"pnfSerialNumber\": \"val1\",\n" + + " \"pnfOamIpv4Address\": \"val3\",\n" + + " \"pnfFamily\": \"val5\",\n" + + " \"pnfModelNumber\": \"val6\",\n" + + " \"pnfSoftwareVersion\": \"val7\",\n" + + " \"pnfType\": \"val8\",\n" + + " \"eventName\": \"val9\",\n" + + " \"nfNamingCode\": \"val10\",\n" + + " \"nfcNamingCode\": \"val11\",\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + "}"); + + private TestMessages() { + } +} diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java new file mode 100644 index 000000000..48596b3d9 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java @@ -0,0 +1,51 @@ +package org.onap.pnfsimulator.simulator.client; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.io.IOException; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +class HttpClientAdapterImplTest { + + private HttpClientAdapter adapter; + + @Mock + private HttpClient httpClient; + @Mock + private HttpResponse httpResponse; + + @BeforeEach + void setup() { + initMocks(this); + adapter = new HttpClientAdapterImpl(httpClient); + } + + @Test + void send_should_successfully_send_request_given_valid_url() throws IOException { + doReturn(httpResponse).when(httpClient).execute(any()); + + adapter.send("test-msg", "http://valid-url"); + + verify(httpClient).execute(any()); + verify(httpResponse).getStatusLine(); + } + + @Test + void send_should_not_send_request_given_invalid_url() throws IOException { + doThrow(new IOException("test")).when(httpClient).execute(any()); + + adapter.send("test-msg", "http://invalid-url"); + + verify(httpClient).execute(any()); + verify(httpResponse, never()).getStatusLine(); + } +} diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/validation/JSONValidatorTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/validation/JSONValidatorTest.java new file mode 100644 index 000000000..d7398d089 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/validation/JSONValidatorTest.java @@ -0,0 +1,103 @@ +package org.onap.pnfsimulator.simulator.validation; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.github.fge.jsonschema.core.exceptions.InvalidSchemaException; +import com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.io.IOException; +import java.net.URL; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class JSONValidatorTest { + + private final static String VALID_SCHEMA_NAME = "valid-test-schema.json"; + private final static String INVALID_SCHEMA_NAME = "invalid-test-schema.json"; + + private JSONValidator validator; + + @BeforeEach + void setUp() { + validator = new JSONValidator(); + } + + @Test + void validate_should_not_throw_given_valid_json() throws ProcessingException, IOException, ValidationException { + validator.validate(getValidJsonString(), getResourcePath(VALID_SCHEMA_NAME)); + } + + @Test + void validate_should_not_throw_when_optional_parameter_missing() + throws ProcessingException, IOException, ValidationException { + + String invalidJsonString = new JSONObject() + .put("key1", "value1") + .put("key2", "value2") + .toString(); + + validator.validate(invalidJsonString, getResourcePath(VALID_SCHEMA_NAME)); + } + + @Test + void validate_should_throw_when_mandatory_parameter_missing() { + + String invalidJsonString = new JSONObject() + .put("key1", "value1") + .put("key3", "value3") + .toString(); + + assertThrows( + ValidationException.class, + () -> validator.validate(invalidJsonString, getResourcePath(VALID_SCHEMA_NAME))); + } + + @Test + void validate_should_throw_when_invalid_json_format() { + String invalidJsonString = "{" + + "\"key1\": \"value1\"" + + "\"key2\": \"value2" + + "}"; + + assertThrows( + IOException.class, + () -> validator.validate(invalidJsonString, getResourcePath(VALID_SCHEMA_NAME))); + } + + @Test + void validate_should_throw_when_invalid_schema_format() { + assertThrows( + InvalidSchemaException.class, + () -> validator.validate(getValidJsonString(), getResourcePath(INVALID_SCHEMA_NAME))); + } + + @Test + void validate_should_throw_when_invalid_schema_path() { + + assertThrows( + IOException.class, + () -> validator.validate(getValidJsonString(), "/not/existing/path/schema.json")); + } + + private String getResourcePath(String schemaFileName) { + URL result = getClass() + .getClassLoader() + .getResource(schemaFileName); + + if (result == null) { + throw new IllegalArgumentException("Given file doesn't exist"); + } else { + return result + .toString() + .replace("file:", ""); + } + } + + private String getValidJsonString() { + return new JSONObject() + .put("key1", "value1") + .put("key2", "value2") + .put("key3", "value3") + .toString(); + } +} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/invalid-test-schema.json b/test/mocks/pnfsimulator/src/test/resources/invalid-test-schema.json new file mode 100644 index 000000000..8c37c822b --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/invalid-test-schema.json @@ -0,0 +1,19 @@ +{ + "type": "object", + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "key1": { + "type": "string" + }, + "key2": { + "type": "string" + }, + "key3": { + "type": "string" + }, + "required": [ + "key1", + "key2" + ] + } +} diff --git a/test/mocks/pnfsimulator/src/test/resources/valid-test-schema.json b/test/mocks/pnfsimulator/src/test/resources/valid-test-schema.json new file mode 100644 index 000000000..26e48a5e8 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/valid-test-schema.json @@ -0,0 +1,19 @@ +{ + "type": "object", + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "key1": { + "type": "string" + }, + "key2": { + "type": "string" + }, + "key3": { + "type": "string" + } + }, + "required": [ + "key1", + "key2" + ] +} -- cgit 1.2.3-korg