From 432696535f996211186269c78e36ab5a6c073997 Mon Sep 17 00:00:00 2001 From: Pawel Kadlubanski Date: Fri, 15 Jun 2018 16:13:45 +0200 Subject: Add netconf support to pnfsimulator. Issue-ID: INT-458 Change-Id: Iebc9cf2a9f35c92dc354d1c6e857dc8345c1172f Signed-off-by: Pawel Kadlubanski --- test/mocks/pnfsimulator/.gitignore | 4 + test/mocks/pnfsimulator/.gitlab-ci.yml | 9 + test/mocks/pnfsimulator/body.json | 18 -- test/mocks/pnfsimulator/config/config.json | 23 ++ test/mocks/pnfsimulator/config/netconf.env | 5 + test/mocks/pnfsimulator/docker-compose.dev.yml | 24 ++ test/mocks/pnfsimulator/docker-compose.yml | 24 ++ .../pnfsimulator/netconf/pnf-simulator.data.xml | 4 + test/mocks/pnfsimulator/netconf/pnf-simulator.yang | 9 + test/mocks/pnfsimulator/pom.xml | 320 ++++++++++++--------- test/mocks/pnfsimulator/simulator.sh | 157 +++++++--- .../src/main/java/org/onap/pnfsimulator/Main.java | 36 +-- .../org/onap/pnfsimulator/cli/SimulatorParams.java | 65 ----- .../pnfsimulator/cli/SimulatorParamsProvider.java | 61 ---- .../pnfsimulator/message/MessageConstants.java | 7 +- .../onap/pnfsimulator/message/MessageProvider.java | 16 +- .../NetconfConfigurationCheckingTask.java | 62 ++++ .../netconfmonitor/NetconfMonitorService.java | 67 +++++ .../NetconfMonitorServiceConfiguration.java | 99 +++++++ .../netconf/NetconfConfigurationCache.java | 33 +++ .../netconf/NetconfConfigurationReader.java | 40 +++ .../netconf/NetconfConfigurationWriter.java | 51 ++++ .../netconf/NetconfConnectionParams.java | 44 +++ .../netconf/NetconfSessionFactory.java | 39 +++ .../pnfsimulator/rest/SimulatorController.java | 162 +++++++++++ .../org/onap/pnfsimulator/rest/util/DateUtil.java | 35 +++ .../pnfsimulator/rest/util/ResponseBuilder.java | 61 ++++ .../org/onap/pnfsimulator/simulator/Simulator.java | 47 ++- .../pnfsimulator/simulator/SimulatorFactory.java | 31 +- .../simulator/client/HttpClientAdapter.java | 76 +++++ .../simulator/client/HttpClientProvider.java | 76 ----- .../simulator/validation/ParamsValidator.java | 70 ++++- .../simulator/validation/ValidationException.java | 20 ++ .../src/main/resources/application.properties | 1 + .../pnfsimulator/src/main/resources/log4j2.xml | 9 +- .../pnfsimulator/SimulatorParamsProviderTest.java | 31 -- .../java/org/onap/pnfsimulator/SimulatorTest.java | 12 - .../pnfsimulator/message/MessageProviderTest.java | 20 +- .../rest/util/ResponseBuilderTest.java | 59 ++++ 39 files changed, 1389 insertions(+), 538 deletions(-) create mode 100644 test/mocks/pnfsimulator/.gitignore create mode 100644 test/mocks/pnfsimulator/.gitlab-ci.yml delete mode 100644 test/mocks/pnfsimulator/body.json create mode 100644 test/mocks/pnfsimulator/config/config.json create mode 100644 test/mocks/pnfsimulator/config/netconf.env create mode 100644 test/mocks/pnfsimulator/docker-compose.dev.yml create mode 100644 test/mocks/pnfsimulator/docker-compose.yml create mode 100644 test/mocks/pnfsimulator/netconf/pnf-simulator.data.xml create mode 100644 test/mocks/pnfsimulator/netconf/pnf-simulator.yang delete mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParams.java delete mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParamsProvider.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java create 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/rest/SimulatorController.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java create mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java delete mode 100644 test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientProvider.java create mode 100644 test/mocks/pnfsimulator/src/main/resources/application.properties delete mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/SimulatorParamsProviderTest.java delete mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/SimulatorTest.java create mode 100644 test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java (limited to 'test/mocks') diff --git a/test/mocks/pnfsimulator/.gitignore b/test/mocks/pnfsimulator/.gitignore new file mode 100644 index 000000000..3fa204a3b --- /dev/null +++ b/test/mocks/pnfsimulator/.gitignore @@ -0,0 +1,4 @@ +.idea +target +*.iml +logs diff --git a/test/mocks/pnfsimulator/.gitlab-ci.yml b/test/mocks/pnfsimulator/.gitlab-ci.yml new file mode 100644 index 000000000..4320a5725 --- /dev/null +++ b/test/mocks/pnfsimulator/.gitlab-ci.yml @@ -0,0 +1,9 @@ +image: archive.docker-registry.eecloud.nsn-net.net/imp/matryoshka:latest + +stages: + - build + +build: + stage: build + script: + - mvn clean package diff --git a/test/mocks/pnfsimulator/body.json b/test/mocks/pnfsimulator/body.json deleted file mode 100644 index e0de14a73..000000000 --- a/test/mocks/pnfsimulator/body.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"testDuration": "10", -"messageInterval": "1", -"pnfSerialNumber": "val1", -"pnfVendorName": "val2", -"pnfOamIpv4Address": "val3", -"pnfOamIpv6Address": "val4", -"pnfFamily": "val5", -"pnfModelNumber": "val6", -"pnfSoftwareVersion": "val7", -"pnfType": "val8", -"eventName": "val9", -"nfNamingCode": "val10", -"nfcNamingCode": "val11", -"sourceName": "val12", -"sourceId": "val13", -"reportingEntityName": "val14" -} diff --git a/test/mocks/pnfsimulator/config/config.json b/test/mocks/pnfsimulator/config/config.json new file mode 100644 index 000000000..b7eb1cc12 --- /dev/null +++ b/test/mocks/pnfsimulator/config/config.json @@ -0,0 +1,23 @@ +{ + "simulatorParams": { + "vesServerUrl": "http://10.154.187.70:8080/eventListener/v5", + "testDuration": "10", + "messageInterval": "1" + }, + "messageParams": { + "pnfSerialNumber": "val1", + "pnfVendorName": "val2", + "pnfOamIpv4Address": "val3", + "pnfOamIpv6Address": "val4", + "pnfFamily": "val5", + "pnfModelNumber": "val6", + "pnfSoftwareVersion": "val7", + "pnfType": "val8", + "eventName": "val9", + "nfNamingCode": "val10", + "nfcNamingCode": "val11", + "sourceName": "val12", + "sourceId": "val13", + "reportingEntityName": "val14" + } +} diff --git a/test/mocks/pnfsimulator/config/netconf.env b/test/mocks/pnfsimulator/config/netconf.env new file mode 100644 index 000000000..6cf310a27 --- /dev/null +++ b/test/mocks/pnfsimulator/config/netconf.env @@ -0,0 +1,5 @@ +NETCONF_ADDRESS=netopeer +NETCONF_PORT=830 +NETCONF_MODEL=pnf-simulator +NETCONF_MAIN_CONTAINER=config +TZ=Europe/Warsaw diff --git a/test/mocks/pnfsimulator/docker-compose.dev.yml b/test/mocks/pnfsimulator/docker-compose.dev.yml new file mode 100644 index 000000000..c389eee65 --- /dev/null +++ b/test/mocks/pnfsimulator/docker-compose.dev.yml @@ -0,0 +1,24 @@ +version: '3' + +services: + pnf-simulator: + container_name: pnf-simulator + image: pnf-simulator:latest + ports: + - "5000:5000" + volumes: + - ./logs:/var/log + env_file: + - ./config/netconf.env + depends_on: + - netopeer + + netopeer: + container_name: netopeer + image: sysrepo/sysrepo-netopeer2:latest + ports: + - "830:830" + env_file: + - ./config/netconf.env + volumes: + - ./netconf:/netconf diff --git a/test/mocks/pnfsimulator/docker-compose.yml b/test/mocks/pnfsimulator/docker-compose.yml new file mode 100644 index 000000000..af9494a2a --- /dev/null +++ b/test/mocks/pnfsimulator/docker-compose.yml @@ -0,0 +1,24 @@ +version: '3' + +services: + pnf-simulator: + container_name: pnf-simulator + image: nexus3.onap.org:10003/onap/pnf-simulator:latest + ports: + - "5000:5000" + volumes: + - ./logs:/var/log + env_file: + - ./config/netconf.env + depends_on: + - netopeer + + netopeer: + container_name: netopeer + image: sysrepo/sysrepo-netopeer2:latest + ports: + - "830:830" + env_file: + - ./config/netconf.env + volumes: + - ./netconf:/netconf diff --git a/test/mocks/pnfsimulator/netconf/pnf-simulator.data.xml b/test/mocks/pnfsimulator/netconf/pnf-simulator.data.xml new file mode 100644 index 000000000..83f80c451 --- /dev/null +++ b/test/mocks/pnfsimulator/netconf/pnf-simulator.data.xml @@ -0,0 +1,4 @@ + + 10 + 1 + diff --git a/test/mocks/pnfsimulator/netconf/pnf-simulator.yang b/test/mocks/pnfsimulator/netconf/pnf-simulator.yang new file mode 100644 index 000000000..dda65545a --- /dev/null +++ b/test/mocks/pnfsimulator/netconf/pnf-simulator.yang @@ -0,0 +1,9 @@ +module pnf-simulator { + namespace "http://nokia.com/pnf-simulator"; + prefix config; + container config { + config true; + leaf testDuration {type uint32;} + leaf messageInterval {type uint32;} + } +} diff --git a/test/mocks/pnfsimulator/pom.xml b/test/mocks/pnfsimulator/pom.xml index f607424da..c0e1ad825 100644 --- a/test/mocks/pnfsimulator/pom.xml +++ b/test/mocks/pnfsimulator/pom.xml @@ -1,154 +1,198 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - org.onap.pnfsimulator - pnf-simulator - 1.1.0-SNAPSHOT - - pnf-simulator + org.onap.pnfsimulator + pnf-simulator + 2.0.0-SNAPSHOT + pnf-simulator UTF-8 1.8 1.8 org.onap.pnfsimulator.Main - latest + latest libs - ${project.build.directory}/${dependency.directory.name} + + ${project.build.directory}/${dependency.directory.name} + nexus3.onap.org:10003 - - - org.apache.logging.log4j - log4j-core - 2.11.0 - - - commons-io - commons-io - 2.6 - - - org.json - json - 20180130 - - - org.apache.httpcomponents - httpclient - 4.5.5 - - - com.google.guava - guava - 21.0 - - - commons-cli - commons-cli - 1.4 - - - org.junit.jupiter - junit-jupiter-engine - 5.1.1 - test - - - org.assertj - assertj-core - 3.9.1 - test - - - org.apache.commons - commons-lang3 - 3.7 - - + + + org.springframework.boot + spring-boot-starter + 2.0.2.RELEASE + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-web + 2.0.2.RELEASE + + + org.springframework.boot + spring-boot-starter-log4j2 + 2.0.2.RELEASE + + + org.apache.logging.log4j + log4j-api + 2.11.0 + + + org.apache.logging.log4j + log4j-core + 2.11.0 + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.11.0 + + + org.apache.logging.log4j + log4j-jul + 2.11.0 + runtime + + + commons-io + commons-io + 2.6 + + + org.json + json + 20180130 + + + org.apache.httpcomponents + httpclient + 4.5.5 + + + com.google.guava + guava + 21.0 + + + commons-cli + commons-cli + 1.4 + + + org.junit.jupiter + junit-jupiter-engine + 5.1.1 + test + + + org.assertj + assertj-core + 3.9.1 + test + + + org.apache.commons + commons-lang3 + 3.7 + + + org.onosproject + jnc + 1.0 + + - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${maven.compiler.source} - ${maven.compiler.target} - true - true - - - - maven-surefire-plugin - 2.19 - - - org.junit.platform - junit-platform-surefire-provider - 1.1.1 - - - - true - true - - - - org.apache.maven.plugins - maven-dependency-plugin - - ${dependency.directory.location} - runtime - true - - - - copy-external-dependencies - package - - copy-dependencies - - - - - - com.spotify - docker-maven-plugin - 1.0.0 - - ${onap.nexus.dockerregistry.daily}/onap/${project.artifactId} - latest - ${project.version}-latest - ${onap.nexus.dockerregistry.daily} - openjdk:8-jdk-alpine - java -cp ${dependency.directory.name}/*:${project.build.finalName}.jar ${simulator.main.class} - - - ${dependency.directory.name} - ${dependency.directory.location} - - - / - ${project.build.directory} - ${project.build.finalName}.jar - - - - - - build-image - package - - build - - - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + true + true + + + + maven-surefire-plugin + 2.19 + + + org.junit.platform + junit-platform-surefire-provider + 1.1.1 + + + + true + true + + + + org.apache.maven.plugins + maven-dependency-plugin + + ${dependency.directory.location} + runtime + true + + + + copy-external-dependencies + package + + copy-dependencies + + + + + + com.spotify + docker-maven-plugin + 1.0.0 + + ${project.artifactId} + ${docker.image.tag} + ${onap.nexus.dockerregistry.daily} + openjdk:8-jre-alpine + + java -cp ${dependency.directory.name}/*:${project.build.finalName}.jar ${simulator.main.class} + + + + ${dependency.directory.name} + ${dependency.directory.location} + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + build-image + package + + build + + + + + + diff --git a/test/mocks/pnfsimulator/simulator.sh b/test/mocks/pnfsimulator/simulator.sh index ff3c07c12..cf16e2400 100755 --- a/test/mocks/pnfsimulator/simulator.sh +++ b/test/mocks/pnfsimulator/simulator.sh @@ -2,10 +2,15 @@ set -euo pipefail -CONTAINER_NAME=pnf-simulator -CONFIG_FILE_PATH=/config/body.json -SIMULATOR_DOCKER_HUB=nexus3.onap.org:10003/onap -SIMULATOR_TAG=1.1.0-SNAPSHOT-latest +COMPOSE_FILE_NAME=docker-compose.yml +DEV_COMPOSE_FILE_NAME=docker-compose.dev.yml +NETOPEER_CONTAINER_NAME=netopeer +SIMULATOR_CONTAINER_NAME=pnf-simulator +SIMULATOR_PORT=5000 +SIMULATOR_START_URL=http://localhost:$SIMULATOR_PORT/simulator/start +SIMULATOR_STOP_URL=http://localhost:$SIMULATOR_PORT/simulator/stop +SIMULATOR_STATUS_URL=http://localhost:$SIMULATOR_PORT/simulator/status +RUNNING_COMPOSE_CONFIG=$COMPOSE_FILE_NAME function main(){ @@ -15,17 +20,21 @@ function main(){ "build") build_image;; "start") - start_simulator $2 $CONFIG_FILE_PATH $SIMULATOR_DOCKER_HUB/pnf-simulator:$SIMULATOR_TAG;; + start $COMPOSE_FILE_NAME;; "start-dev") - start_simulator $2 $CONFIG_FILE_PATH pnf-simulator:$SIMULATOR_TAG;; + start $DEV_COMPOSE_FILE_NAME;; + "start-debug") + start_netconf_server $DEV_COMPOSE_FILE_NAME;; "stop") + stop;; + "run-simulator") + run_simulator;; + "stop-simulator") stop_simulator;; "status") - print_status;; - "logs") - get_logs;; - "help") - print_help;; + get_status;; + "clear-logs") + clear_logs;; *) print_help;; esac @@ -33,76 +42,142 @@ function main(){ function build_image(){ if [ -f pom.xml ]; then - mvn clean package + mvn clean package else echo "pom.xml file not found" exit 1 fi } -function start_simulator(){ +function start_netconf_server() { + docker-compose -f $1 up -d $NETOPEER_CONTAINER_NAME + echo + echo "NETCONF server container's logs:" + docker exec $NETOPEER_CONTAINER_NAME /bin/bash -c "sysrepoctl --install --yang=/netconf/\$NETCONF_MODEL.yang --owner=netconf:nogroup --permissions=777" + docker exec $NETOPEER_CONTAINER_NAME /bin/bash -c "sysrepocfg --import=/netconf/\$NETCONF_MODEL.data.xml --datastore=startup --format=xml --level=3 \$NETCONF_MODEL" + docker exec -d $NETOPEER_CONTAINER_NAME /bin/bash -c "/opt/dev/sysrepo/build/examples/application_example \$NETCONF_MODEL" + echo +} - stop_and_remove_container || true +function start(){ - if [ $(docker run -d --name $CONTAINER_NAME -v $(pwd):/config -e VES_ADDRESS=$1 -e CONFIG_FILE_PATH=$2 $3) > /dev/null ]; then - echo "Simulator started" + if [[ $(running_containers) ]]; then + echo "Simulator containers are already up" else - echo "Failed to start simulator" + echo "Starting simulator containers using netconf model specified in config/netconf.env" + + archive_logs + start_netconf_server $1 + docker-compose -f $1 up -d $SIMULATOR_CONTAINER_NAME + RUNNING_COMPOSE_CONFIG=$1 fi } -function stop_and_remove_container(){ - docker rm -f $CONTAINER_NAME 1> /dev/null +function running_containers(){ + docker-compose -f $COMPOSE_FILE_NAME ps -q && docker-compose -f $DEV_COMPOSE_FILE_NAME ps -q } -function stop_simulator(){ - if [ $(docker kill $CONTAINER_NAME) > /dev/null ]; then - echo "Simulator stopped" +function stop(){ + + if [[ $(running_containers) ]]; then + docker-compose -f $RUNNING_COMPOSE_CONFIG down else - echo "Failed to stop simulator" + echo "Simulator containers are already down" fi +} +function run_simulator(){ +cat << EndOfMessage +Simulator response: +$(curl -s -X POST -H "Content-Type: application/json" -d @config/config.json $SIMULATOR_START_URL | json_pp) +EndOfMessage } -function print_status(){ +function stop_simulator(){ cat << EndOfMessage +Simulator response: +$(curl -s -X POST $SIMULATOR_STOP_URL | json_pp) +EndOfMessage +} -Simulator container status: +function get_status(){ -$(docker ps -a -f name=$CONTAINER_NAME) + if [[ $(running_containers) ]]; then + print_status + else + echo "Simulator containers are down" + fi +} +function print_status(){ +cat << EndOfMessage +$(docker-compose -f $RUNNING_COMPOSE_CONFIG ps) + +Simulator response: +$(curl -s -X GET $SIMULATOR_STATUS_URL | json_pp) EndOfMessage } function print_help(){ cat << EndOfMessage - Available options: build - locally builds simulator image from existing code -start - starts simulator using remote docker image and connects to given VES server -start-dev - starts simulator using local docker image and connects to given VES server -stop - stops simulator -status - prints container status -logs - prints logs -help - prints this message +start - starts simulator and netopeer2 containers using remote simulator image and specified model name +start-dev - starts simulator and netopeer2 containers using remote simulator image +start-debug - starts only netopeer2 container +run-simulator - starts sending PNF registration messages with parameters specified in config.json +stop-simulator - stop sending PNF registration messages +stop - stops both containers +status - prints simulator status +clear-logs - deletes log folder Starting simulation: -Use "./simulator.sh start". It will download required docker image from the internet and start simulator using body.json file -To stop simulation use "./simulator.sh stop" command. To check simulator's status use "./simulator.sh status". -If you want to change message parameters simply edit body.json file then run simulator again. +- Setup environment with "./simulator.sh start". It will download required docker images from the internet and run them on docker machine +- To start the simulation use "./simulator.sh run-simulator", which will start sending PNF registration messages with parameters specified in config.json + +To stop simulation use "./simulator.sh stop-simulator" command. To check simulator's status use "./simulator.sh status". +If you want to change message parameters simply edit config.json, then start the simulation with "./simulator.sh run-simulator" again +Logs are written to logs/pnf-simulator.log. After each "start/start-dev" old log files are moved to the archive FOR DEVELOPERS 1. Build local simulator image using "./simulator.sh build" -2. Run simulation with "./simulator.sh start-dev" - -If you change the source code you have to rebuild image with "./simulator.sh build" and run "./simulator.sh start-dev" again +2. Run containers with "./simulator.sh start-dev" +If you change the source code you have to rebuild image with "./simulator.sh build" and run "./simulator.sh start/start-dev" again EndOfMessage } -function get_logs(){ - docker logs --tail all $CONTAINER_NAME +function archive_logs(){ + + if [ -d logs ]; then + echo "Moving log file to archive" + DIR_PATH=logs/archive/simulator[$(timestamp)] + mkdir -p $DIR_PATH + if [ -f logs/pnfsimulator.log ]; then + mv logs/pnfsimulator.log $DIR_PATH + fi + + if [ -f logs/*.xml ]; then + mv logs/*.xml $DIR_PATH + fi + + else + mkdir logs + fi +} + +function clear_logs(){ + + if [[ $(running_containers) ]]; then + echo "Cannot delete logs when simulator is running" + else + rm -rf logs + fi +} + +function timestamp(){ + date "+%Y-%m-%d_%T" } main $@ \ No newline at end of file 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 37f1b21c9..0e9fe4d3d 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 @@ -20,38 +20,14 @@ package org.onap.pnfsimulator; -import java.io.IOException; -import org.apache.commons.cli.ParseException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.onap.pnfsimulator.cli.SimulatorParamsProvider; -import org.onap.pnfsimulator.cli.SimulatorParams; -import org.onap.pnfsimulator.message.MessageProvider; -import org.onap.pnfsimulator.simulator.SimulatorFactory; -import org.onap.pnfsimulator.simulator.validation.ParamsValidator; -import org.onap.pnfsimulator.simulator.validation.ValidationException; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; +@SpringBootApplication +@EnableAsync public class Main { - - private static Logger logger = LogManager.getLogger(Main.class); - private static SimulatorFactory simulatorFactory = - new SimulatorFactory(MessageProvider.getInstance()); - public static void main(String[] args) { - - try { - - SimulatorParams params = new SimulatorParamsProvider().parse(args); - simulatorFactory - .create(params.getVesAddress(), params.getConfigFilePath()) - .start(); - - } catch (IOException e) { - logger.error("Invalid config file format", e); - } catch (ParseException e) { - logger.error("Invalid cli params", e); - } catch (ValidationException e){ - logger.error(e); - } + SpringApplication.run(Main.class, args); } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParams.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParams.java deleted file mode 100644 index 2ca0b5e7b..000000000 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParams.java +++ /dev/null @@ -1,65 +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.cli; - -import java.util.Objects; - -public class SimulatorParams { - - private String vesAddress; - private String configFilePath; - - public SimulatorParams(String vesAddress, String configFilePath) { - this.vesAddress = vesAddress; - this.configFilePath = configFilePath; - } - - public String getVesAddress() { - return vesAddress; - } - - public String getConfigFilePath() { - return configFilePath; - } - - @Override - public String toString() { - return String.format("VES address=%s, Configuration file=%s", vesAddress, configFilePath); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof SimulatorParams)) { - return false; - } - SimulatorParams params = (SimulatorParams) o; - return Objects.equals(vesAddress, params.vesAddress) && - Objects.equals(configFilePath, params.configFilePath); - } - - @Override - public int hashCode() { - return Objects.hash(vesAddress, configFilePath); - } -} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParamsProvider.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParamsProvider.java deleted file mode 100644 index ab705e907..000000000 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParamsProvider.java +++ /dev/null @@ -1,61 +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.cli; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; - -public class SimulatorParamsProvider { - - private static final String CLI_VAR_VES_ADDRESS = "address"; - private static final String CLI_VAR_CONFIG_FILE_PATH = "config"; - private static final String ENV_VAR_VES_ADDRESS = "VES_ADDRESS"; - private static final String ENV_VAR_CONFIG_FILE_PATH = "CONFIG_FILE_PATH"; - - private Options options; - private CommandLineParser parser; - - public SimulatorParamsProvider() { - createOptions(); - parser = new DefaultParser(); - } - - public SimulatorParams parse(String[] arg) throws ParseException { - CommandLine line = parser.parse(options, arg); - return new SimulatorParams( - line.getOptionValue(CLI_VAR_VES_ADDRESS, System.getenv().get(ENV_VAR_VES_ADDRESS)), - line.getOptionValue(CLI_VAR_CONFIG_FILE_PATH, System.getenv().get(ENV_VAR_CONFIG_FILE_PATH))); - } - - private void createOptions() { - options = new Options(); - - Option vesCollectorUlrOpt = new Option(CLI_VAR_VES_ADDRESS, true, "VES collector URL"); - options.addOption(vesCollectorUlrOpt); - - Option simulatorConfigFilePathOpt = new Option(CLI_VAR_CONFIG_FILE_PATH, true, "Simulator configuration file location."); - options.addOption(simulatorConfigFilePathOpt); - } -} 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 5805a88c7..8e7c6fcfd 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 @@ -17,7 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - + package org.onap.pnfsimulator.message; public final class MessageConstants { @@ -36,12 +36,15 @@ public final class MessageConstants { public static final String PNF_LAST_SERVICE_DATE = "pnfLastServiceDate"; public static final String PNF_MANUFACTURE_DATE = "pnfManufactureDate"; + public static final String SIMULATOR_PARAMS_CONTAINER = "simulatorParams"; + public static final String MESSAGE_PARAMS_CONTAINER = "messageParams"; + // mandatory public static final String PNF_OAM_IPV4_ADDRESS = "pnfOamIpv4Address"; public static final String PNF_OAM_IPV6_ADDRESS = "pnfOamIpv6Address"; public static final String PNF_SERIAL_NUMBER = "pnfSerialNumber"; public static final String PNF_VENDOR_NAME = "pnfVendorName"; - + public static final String VES_SERVER_URL = "vesServerUrl"; public static final String PNF_PREFIX = "pnf"; public static final String COMMON_EVENT_HEADER = "commonEventHeader"; public static final String OTHER_FIELDS = "otherFields"; 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 94f5fc167..44ca9666c 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 @@ -39,24 +39,16 @@ import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import java.util.Map; import java.util.UUID; - -import com.google.common.base.Preconditions; import org.json.JSONObject; public class MessageProvider { - private static MessageProvider instance; + public JSONObject createMessage(JSONObject params) { - public static MessageProvider getInstance() { - if (instance == null) { - instance = new MessageProvider(); + if(params == null){ + throw new IllegalArgumentException("Params object cannot be null"); } - return instance; - } - public JSONObject createMessage(JSONObject params) { - - Preconditions.checkArgument(params != null, "Params object cannot be null"); Map paramsMap = params.toMap(); JSONObject root = new JSONObject(); JSONObject commonEventHeader = generateConstantCommonEventHeader(); @@ -74,7 +66,6 @@ public class MessageProvider { JSONObject event = new JSONObject(); event.put(COMMON_EVENT_HEADER, commonEventHeader); event.put(OTHER_FIELDS, otherFields); - root.put(EVENT, event); return root; } @@ -93,7 +84,6 @@ public class MessageProvider { commonEventHeader.put(START_EPOCH_MICROSEC, timestamp); commonEventHeader.put(INTERNAL_HEADER_FIELDS, new JSONObject()); commonEventHeader.put(VERSION, 3); - commonEventHeader.put("functionalRole", "test_rola"); return commonEventHeader; } 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 new file mode 100644 index 000000000..b4eda0a79 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java @@ -0,0 +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.netconfmonitor; + +import com.tailf.jnc.JNCException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +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; + +public class NetconfConfigurationCheckingTask extends TimerTask { + private static final Logger LOGGER = LogManager.getLogger(NetconfConfigurationCheckingTask.class); + + private final NetconfConfigurationReader reader; + private final NetconfConfigurationWriter writer; + private final NetconfConfigurationCache cache; + + public NetconfConfigurationCheckingTask(NetconfConfigurationReader reader, + NetconfConfigurationWriter writer, + NetconfConfigurationCache cache) { + this.reader = reader; + this.writer = writer; + this.cache = cache; + } + + @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); + } + } +} 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 new file mode 100644 index 000000000..c4d6198f7 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java @@ -0,0 +1,67 @@ +/*- + * ============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.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; +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 long timePeriod = 1000L; + private static final long startDelay = 0; + + private Timer timer; + private NetconfConfigurationReader reader; + private NetconfConfigurationWriter writer; + private NetconfConfigurationCache cache; + + @Autowired + public NetconfMonitorService(Timer timer, + NetconfConfigurationReader reader, + NetconfConfigurationWriter writer, + NetconfConfigurationCache cache) { + this.timer = timer; + this.reader = reader; + this.writer = writer; + this.cache = cache; + } + + @PostConstruct + public void start() throws IOException, JNCException { + setStartConfiguration(); + 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); + } +} 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 new file mode 100644 index 000000000..82ea85aee --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java @@ -0,0 +1,99 @@ +/*- + * ============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 java.io.IOException; +import java.util.Map; +import java.util.Timer; + +@Configuration +public class NetconfMonitorServiceConfiguration { + private static final Logger LOGGER = LogManager.getLogger(NetconfMonitorServiceConfiguration.class); + private static final Map enviroment = System.getenv(); + + private static final String LOG_PATH = "/var/log"; + + private static final String NETCONF_ADDRESS = "NETCONF_ADDRESS"; + private static final String NETCONF_PORT = "NETCONF_PORT"; + 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 int DEFAULT_NETCONF_PORT = 830; + private static final String DEFAULT_NETCONF_MODEL = "pnf-simulator"; + private static final String DEFAULT_NETCONF_MAIN_CONTAINER = "config"; + + private static final String DEFAULT_NETCONF_USER = "netconf"; + private static final String DEFAULT_NETCONF_PASSWORD = "netconf"; + + @Bean + public Timer timer() { + return new Timer("NetconfMonitorServiceTimer"); + } + + @Bean + public NetconfConfigurationCache configurationCache() { + return new NetconfConfigurationCache(); + } + + @Bean + public NetconfConfigurationReader configurationReader() throws IOException, JNCException { + NetconfConnectionParams params = createConnectionParams(); + LOGGER.info("Configuration params are : {}", params); + NetconfSession session = NetconfSessionFactory.create(params); + return new NetconfConfigurationReader(session, buildModelPath()); + } + + @Bean + public NetconfConfigurationWriter netconfConfigurationWriter() { + return new NetconfConfigurationWriter(LOG_PATH); + } + + private String buildModelPath() { + return String.format("/%s:%s", + enviroment.getOrDefault(NETCONF_MODEL, DEFAULT_NETCONF_MODEL), + enviroment.getOrDefault(NETCONF_MAIN_CONTAINER, DEFAULT_NETCONF_MAIN_CONTAINER)); + } + + private NetconfConnectionParams createConnectionParams() { + return new NetconfConnectionParams( + 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) { + 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 new file mode 100644 index 000000000..820234620 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java @@ -0,0 +1,33 @@ +/*- + * ============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() { + return configuration; + } + + public void update(String configuration) { + this.configuration = configuration; + } +} 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 new file mode 100644 index 000000000..e8979254d --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java @@ -0,0 +1,40 @@ +/*- + * ============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; + + public NetconfConfigurationReader(NetconfSession session, String netconfModelPath) { + this.session = session; + this.netconfModelPath = netconfModelPath; + } + + public String read() throws IOException, JNCException { + return session.getConfig(netconfModelPath).first().toXMLString(); + } +} 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 new file mode 100644 index 000000000..4c3d53e39 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java @@ -0,0 +1,51 @@ +/*- + * ============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 org.onap.pnfsimulator.rest.util.DateUtil; + +public class NetconfConfigurationWriter { + private static final Logger LOGGER = LogManager.getLogger(NetconfConfigurationWriter.class); + private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); + private String pathToLog; + + public NetconfConfigurationWriter(String pathToLog) { + this.pathToLog = pathToLog; + } + + public void writeToFile(String configuration) { + String fileName = String.format("%s/config[%s].xml", pathToLog, DateUtil.getTimestamp(dateFormat)); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) { + writer.write(configuration); + LOGGER.info("Configuration wrote to file {}/{} ", pathToLog, fileName); + } catch (IOException e) { + LOGGER.info("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 new file mode 100644 index 000000000..3130d2b06 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java @@ -0,0 +1,44 @@ +/*- + * ============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; + public final String password; + + public NetconfConnectionParams(String address, int port, String user, String password) { + this.address = address; + this.port = port; + this.user = user; + this.password = password; + } + + @Override + public String toString() { + return String.format("NetconfConnectionParams{address=%s, port=%d, user=%s, password=%s}", + 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 new file mode 100644 index 000000000..4f31af5eb --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java @@ -0,0 +1,39 @@ +/*- + * ============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 new file mode 100644 index 000000000..46a63a21c --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java @@ -0,0 +1,162 @@ +/*- + * ============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.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 java.text.DateFormat; +import java.text.SimpleDateFormat; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +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.ValidationException; +import org.springframework.http.HttpStatus; +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.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + + +@RestController +@RequestMapping("/simulator") +public class SimulatorController { + + private static final Logger LOGGER = LogManager.getLogger(Simulator.class); + private static final DateFormat RESPONSE_DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss,SSS"); + + private Simulator simulator; + + + @PostMapping("start") + public ResponseEntity start(@RequestBody String message) { + + if (simulator != null && simulator.isAlive()) { + return ResponseBuilder + .status(HttpStatus.BAD_REQUEST.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator since it's already running") + .build(); + } + + try { + 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.start(); + + } catch (JSONException e) { + + LOGGER.error("Cannot start simulator, invalid json format: " + e.getMessage()); + LOGGER.debug("Received json has invalid format:\n" + message); + return ResponseBuilder + .status(HttpStatus.BAD_REQUEST.value()) + .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"); + return ResponseBuilder + .status(HttpStatus.BAD_REQUEST.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, e.getMessage()) + .build(); + + } catch (RuntimeException e) { + + LOGGER.error("Cannot start simulator - unexpected exception", e); + return ResponseBuilder + .status(HttpStatus.INTERNAL_SERVER_ERROR.value()) + .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(); + } + + @GetMapping("status") + public ResponseEntity status() { + + if (simulator != null && simulator.isAlive()) { + + ResponseBuilder responseBuilder = ResponseBuilder + .status(HttpStatus.OK.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(SIMULATOR_STATUS, "RUNNING"); + + if (!simulator.isEndless()) { + responseBuilder.put(REMAINING_TIME, simulator.getRemainingTime()); + } + return responseBuilder.build(); + } else { + return ResponseBuilder + .status(HttpStatus.OK.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(SIMULATOR_STATUS, "NOT RUNNING") + .build(); + } + } + + @PostMapping("stop") + public ResponseEntity stop() { + + if (simulator != null && simulator.isAlive()) { + simulator.interrupt(); + + return ResponseBuilder + .status(HttpStatus.OK.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator successfully stopped") + .build(); + } else { + return ResponseBuilder + .status(HttpStatus.BAD_REQUEST.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot stop simulator, because it's not running") + .build(); + } + } +} + 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 new file mode 100644 index 000000000..73443d06e --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java @@ -0,0 +1,35 @@ +/*- + * ============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; +import java.util.Date; + +public final class DateUtil { + + private DateUtil() { + } + + public static String getTimestamp(DateFormat dateFormat) { + + return dateFormat.format(new Date()); + } +} 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 new file mode 100644 index 000000000..31d22a713 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java @@ -0,0 +1,61 @@ +/*- + * ============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.ResponseEntity; + +public class ResponseBuilder { + + public static final String TIMESTAMP = "timestamp"; + public static final String MESSAGE = "message"; + public static final String SIMULATOR_STATUS = "simulatorStatus"; + public static final String REMAINING_TIME = "remainingTime"; + + private int statusCode; + private Map body = new LinkedHashMap<>(); + + private ResponseBuilder(int statusCode) { + this.statusCode = statusCode; + } + + public static ResponseBuilder status(int statusCode) { + + return new ResponseBuilder(statusCode); + } + + public ResponseBuilder put(String key, Object value) { + + body.put(key, value); + return this; + } + + public ResponseEntity build() { + + if (body.isEmpty()) { + return ResponseEntity.status(statusCode).build(); + } + + return ResponseEntity.status(statusCode).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 ff2ca862a..0c713e127 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 @@ -25,41 +25,60 @@ import java.time.Instant; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; -import org.onap.pnfsimulator.simulator.client.HttpClientProvider; +import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; -public class Simulator { +public class Simulator extends Thread { - private static final Logger logger = LogManager.getLogger(HttpClientProvider.class); - private HttpClientProvider clientProvider; + private static final Logger LOGGER = LogManager.getLogger(Simulator.class); + private HttpClientAdapter clientProvider; 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 HttpClientProvider(vesServerUrl); + this.clientProvider = new HttpClientAdapter(vesServerUrl); + this.isEndless = duration.getSeconds() == 0; } - public void start() { - logger.info("SIMULATOR STARTED - DURATION: {}s, INTERVAL: {}s", duration.getSeconds(), interval.getSeconds()); + public void run() { + LOGGER.info("Simulation started - duration: " + getDuration() + ", interval: {}s", interval.getSeconds()); - Instant endTime = Instant.now().plus(duration); - while (runningTimeNotExceeded(endTime)) { + endTime = Instant.now().plus(duration); + boolean isEndless = isEndless(); + while (isEndless || runningTimeNotExceeded()) { try { - logger.info(()-> "MESSAGE TO BE SENT:\n" + messageBody.toString(4)); + LOGGER.debug("Message to be sent:\n" + messageBody.toString(4)); clientProvider.sendMsg(messageBody.toString()); Thread.sleep(interval.toMillis()); } catch (InterruptedException e) { - logger.error("SIMULATOR INTERRUPTED"); - break; + LOGGER.info("Simulation interrupted"); + return; } } - logger.info("SIMULATOR FINISHED"); + LOGGER.info("Simulation finished"); } - private boolean runningTimeNotExceeded(Instant endTime) { + public boolean isEndless() { + return isEndless; + } + + private String getDuration() { + return isEndless() ? "infinity" : duration.getSeconds() + "s"; + } + + private boolean runningTimeNotExceeded() { return Instant.now().isBefore(endTime); } + + public long getRemainingTime(){ + return Duration.between(Instant.now(), endTime).getSeconds(); + } + public String getMessage(){ + return messageBody.toString(4); + } } \ 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 e3a003831..7f1b0a808 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 @@ -20,15 +20,12 @@ package org.onap.pnfsimulator.simulator; +import static java.lang.Integer.*; 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 java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.util.List; -import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.onap.pnfsimulator.message.MessageProvider; import org.onap.pnfsimulator.simulator.validation.ParamsValidator; @@ -38,23 +35,23 @@ public class SimulatorFactory { private MessageProvider messageProvider; - public SimulatorFactory(MessageProvider messageProvider) { + public static SimulatorFactory usingMessageProvider(MessageProvider messageProvider) { + return new SimulatorFactory(messageProvider); + } + + private SimulatorFactory(MessageProvider messageProvider) { this.messageProvider = messageProvider; } - public Simulator create(String vesServerUrl, String configFilePath) throws IOException, ValidationException { + public Simulator create(JSONObject simulatorParams, JSONObject messageParams) throws ValidationException { - String configJson = FileUtils.readFileToString(new File(configFilePath), StandardCharsets.UTF_8); - JSONObject configObject = new JSONObject(configJson); - ParamsValidator.forObject(configObject).validate(); + ParamsValidator.forParams(simulatorParams, messageParams).validate(); - Duration duration = Duration.ofSeconds(parseJsonField(configObject, TEST_DURATION)); - Duration interval = Duration.ofSeconds(parseJsonField(configObject, MESSAGE_INTERVAL)); - JSONObject messageBody = messageProvider.createMessage(configObject); - return new Simulator(vesServerUrl, messageBody, duration, interval); - } + 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); - private int parseJsonField(JSONObject json, String fieldName) { - return Integer.parseInt((String) json.remove(fieldName)); + JSONObject messageBody = messageProvider.createMessage(messageParams); + return new Simulator(vesServerUrl, messageBody, duration, interval); } } \ 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 new file mode 100644 index 000000000..35f0b6820 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java @@ -0,0 +1,76 @@ +/*- + * ============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()); + } + } + + 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; + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientProvider.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientProvider.java deleted file mode 100644 index 54d2c9fbb..000000000 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientProvider.java +++ /dev/null @@ -1,76 +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.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 HttpClientProvider { - - private static final Logger logger = LogManager.getLogger(HttpClientProvider.class); - private static final String CONTENT_TYPE = "Content-Type"; - private static final String APPLICATION_JSON = "application/json"; - - private HttpClient client; - private String url; - - public HttpClientProvider(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()); - } - } - - 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; - } -} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ParamsValidator.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ParamsValidator.java index 6cdb781f1..3c8459473 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ParamsValidator.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ParamsValidator.java @@ -1,3 +1,23 @@ +/*- + * ============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; import static org.onap.pnfsimulator.message.MessageConstants.MESSAGE_INTERVAL; @@ -6,13 +26,15 @@ import static org.onap.pnfsimulator.message.MessageConstants.PNF_OAM_IPV6_ADDRES import static org.onap.pnfsimulator.message.MessageConstants.PNF_SERIAL_NUMBER; import static org.onap.pnfsimulator.message.MessageConstants.PNF_VENDOR_NAME; import static org.onap.pnfsimulator.message.MessageConstants.TEST_DURATION; +import static org.onap.pnfsimulator.message.MessageConstants.VES_SERVER_URL; import com.google.common.collect.ImmutableMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.function.Predicate; +import java.util.function.BiPredicate; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; @@ -20,33 +42,50 @@ import org.json.JSONObject; public class ParamsValidator { private final static String MISSING_PARAMS_MESSAGE = "Following mandatory params are missing:\n"; - private final Map> validators = ImmutableMap - .>builder() + + private final Map> simulatorParamsValidators = ImmutableMap + .>builder() + .put(VES_SERVER_URL, this::isDefined) .put(TEST_DURATION, this::isNumeric) .put(MESSAGE_INTERVAL, this::isNumeric) + .build(); + + private final Map> messageParamsValidators = ImmutableMap + .>builder() .put(PNF_SERIAL_NUMBER, this::isDefined) .put(PNF_VENDOR_NAME, this::isDefined) .put(PNF_OAM_IPV4_ADDRESS, this::isDefined) .put(PNF_OAM_IPV6_ADDRESS, this::isDefined) .build(); - private JSONObject subject; + private JSONObject simulatorParams; + private JSONObject messageParams; - private ParamsValidator(JSONObject paramsObject) { - subject = paramsObject; + private ParamsValidator(JSONObject simulatorParams, JSONObject messageParams) { + this.simulatorParams = simulatorParams; + this.messageParams = messageParams; } - public static ParamsValidator forObject(JSONObject configObject) { - return new ParamsValidator(configObject); + public static ParamsValidator forParams(JSONObject simulatorParams, JSONObject messageParams) { + return new ParamsValidator(simulatorParams, messageParams); } public void validate() throws ValidationException { - List missingParams = validators + Stream missingSimulatorParams = simulatorParamsValidators .entrySet() .stream() - .filter(entry -> !entry.getValue().test(entry.getKey())) - .map(Entry::getKey) + .filter(entry -> !entry.getValue().test(entry.getKey(), simulatorParams)) + .map(Entry::getKey); + + Stream missingMessageParams = messageParamsValidators + .entrySet() + .stream() + .filter(entry -> !entry.getValue().test(entry.getKey(), messageParams)) + .map(Entry::getKey); + + List missingParams = Stream + .concat(missingMessageParams, missingSimulatorParams) .collect(Collectors.toList()); resolveMissingIP(missingParams); @@ -63,12 +102,13 @@ public class ParamsValidator { .collect(Collectors.joining("\n")); } - private boolean isNumeric(String param) { - return isDefined(param) && StringUtils.isNumeric(subject.getString(param)); + private boolean isNumeric(String param, JSONObject container) { + return isDefined(param, container) && StringUtils.isNumeric(container.getString(param)); } - private boolean isDefined(String param) { - return subject.has(param) && !subject.getString(param).isEmpty(); + private boolean isDefined(String param, JSONObject container) { + + return container.has(param) && !container.getString(param).isEmpty(); } private void resolveMissingIP(List missingParams) { 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 9855a784e..086997f85 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,3 +1,23 @@ +/*- + * ============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/application.properties b/test/mocks/pnfsimulator/src/main/resources/application.properties new file mode 100644 index 000000000..888dcec44 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=5000 \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/resources/log4j2.xml b/test/mocks/pnfsimulator/src/main/resources/log4j2.xml index 250f41709..d3941d32d 100644 --- a/test/mocks/pnfsimulator/src/main/resources/log4j2.xml +++ b/test/mocks/pnfsimulator/src/main/resources/log4j2.xml @@ -2,17 +2,22 @@ - + - + + + + + diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/SimulatorParamsProviderTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/SimulatorParamsProviderTest.java deleted file mode 100644 index 96397eae1..000000000 --- a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/SimulatorParamsProviderTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.onap.pnfsimulator; - -import org.apache.commons.cli.ParseException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.pnfsimulator.cli.SimulatorParamsProvider; -import org.onap.pnfsimulator.cli.SimulatorParams; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Java6Assertions.assertThat; - -public class SimulatorParamsProviderTest { - - SimulatorParamsProvider parser; - - @BeforeEach - public void setUp() { - parser = new SimulatorParamsProvider(); - } - - @Test - public void whenParserReceiveArgLisWithTwoCorrectParametersShouldReturnCorrectStructOfParams() - throws ParseException { - String[] arg = new String[]{ - "-address", "http://localhost:808/eventListner/v5", - "-config", "config.json"}; - SimulatorParams params = parser.parse(arg); - assertThat(params.getConfigFilePath()).isEqualToIgnoringCase("config.json"); - assertThat(params.getVesAddress()).isEqualToIgnoringCase("http://localhost:808/eventListner/v5"); - } -} \ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/SimulatorTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/SimulatorTest.java deleted file mode 100644 index ccbb72846..000000000 --- a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/SimulatorTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.onap.pnfsimulator; - -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -public class SimulatorTest { - - @Test - public void dummyTestToCheckEnvirometn() { - Assertions.assertThat(true).isTrue(); - } -} \ No newline at end of file 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 bfd222dc2..41df397a7 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 @@ -23,7 +23,21 @@ package org.onap.pnfsimulator.message; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.onap.pnfsimulator.message.MessageConstants.*; +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_ID; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT_TYPE; +import static org.onap.pnfsimulator.message.MessageConstants.INTERNAL_HEADER_FIELDS; +import static org.onap.pnfsimulator.message.MessageConstants.LAST_EPOCH_MICROSEC; +import static org.onap.pnfsimulator.message.MessageConstants.OTHER_FIELDS; +import static org.onap.pnfsimulator.message.MessageConstants.OTHER_FIELDS_VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_LAST_SERVICE_DATE; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_MANUFACTURE_DATE; +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; @@ -39,7 +53,7 @@ public class MessageProviderTest { @BeforeAll public static void setup() { - messageProvider = MessageProvider.getInstance(); + messageProvider = new MessageProvider(); } @Test @@ -76,8 +90,8 @@ public class MessageProviderTest { public void createMessage_should_add_specified_params_to_valid_subobjects() { JSONObject params = new JSONObject(testParamsJson); JSONObject message = messageProvider.createMessage(params); - JSONObject event = message.getJSONObject(EVENT); + JSONObject commonEventHeader = event.getJSONObject(COMMON_EVENT_HEADER); JSONObject otherFields = event.getJSONObject(OTHER_FIELDS); 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 new file mode 100644 index 000000000..a8147340e --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java @@ -0,0 +1,59 @@ +/*- + * ============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 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); + } + + @Test + void checkResponseBodySize() { + builder.put("sample", "sample"); + ResponseEntity responseEntity = builder.build(); + Map body = (Map) responseEntity.getBody(); + + assertEquals(body.size(), 1); + } + + @Test + void buildProperResponseEntity() { + ResponseEntity responseEntity = builder.build(); + + assertAll( + () -> assertEquals(responseEntity.getStatusCode(), HttpStatus.OK), + () -> assertNull(responseEntity.getBody()) + ); + } + +} \ No newline at end of file -- cgit 1.2.3-korg