diff options
48 files changed, 2269 insertions, 838 deletions
diff --git a/test/mocks/pnfsimulator/config/config.json b/test/mocks/pnfsimulator/config/config.json index b7eb1cc12..ca2854269 100644 --- a/test/mocks/pnfsimulator/config/config.json +++ b/test/mocks/pnfsimulator/config/config.json @@ -1,6 +1,6 @@ { "simulatorParams": { - "vesServerUrl": "http://10.154.187.70:8080/eventListener/v5", + "vesServerUrl": "http://VES-HOST:VES-PORT/eventListener/v5", "testDuration": "10", "messageInterval": "1" }, diff --git a/test/mocks/pnfsimulator/docker-compose.dev.yml b/test/mocks/pnfsimulator/docker-compose.dev.yml index c389eee65..5112df0e4 100644 --- a/test/mocks/pnfsimulator/docker-compose.dev.yml +++ b/test/mocks/pnfsimulator/docker-compose.dev.yml @@ -3,11 +3,12 @@ version: '3' services: pnf-simulator: container_name: pnf-simulator - image: pnf-simulator:latest + image: onap/pnf-simulator:latest ports: - "5000:5000" volumes: - ./logs:/var/log + - ./json_schema:/json_schema env_file: - ./config/netconf.env depends_on: @@ -21,4 +22,4 @@ services: env_file: - ./config/netconf.env volumes: - - ./netconf:/netconf + - ./netconf:/netconf
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/docker-compose.yml b/test/mocks/pnfsimulator/docker-compose.yml index af9494a2a..cfc086357 100644 --- a/test/mocks/pnfsimulator/docker-compose.yml +++ b/test/mocks/pnfsimulator/docker-compose.yml @@ -8,6 +8,7 @@ services: - "5000:5000" volumes: - ./logs:/var/log + - ./json_schema:/json_schema env_file: - ./config/netconf.env depends_on: @@ -21,4 +22,4 @@ services: env_file: - ./config/netconf.env volumes: - - ./netconf:/netconf + - ./netconf:/netconf
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/json_schema/input_validator.json b/test/mocks/pnfsimulator/json_schema/input_validator.json new file mode 100644 index 000000000..df4efb53d --- /dev/null +++ b/test/mocks/pnfsimulator/json_schema/input_validator.json @@ -0,0 +1,193 @@ +{ + "$id": "http://example.com/example.json", + "type": "object", + "definitions": {}, + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "simulatorParams": { + "$id": "/properties/simulatorParams", + "type": "object", + "properties": { + "vesServerUrl": { + "$id": "/properties/simulatorParams/properties/vesServerUrl", + "type": "string", + "title": "The Vesserverurl Schema ", + "default": "", + "examples": [ + "http://10.154.187.70:8080/eventListener/v5" + ] + }, + "testDuration": { + "$id": "/properties/simulatorParams/properties/testDuration", + "type": "string", + "title": "The Testduration Schema ", + "default": "", + "examples": [ + "10" + ] + }, + "messageInterval": { + "$id": "/properties/simulatorParams/properties/messageInterval", + "type": "string", + "title": "The Messageinterval Schema ", + "default": "", + "examples": [ + "1" + ] + } + } + }, + "messageParams": { + "$id": "/properties/messageParams", + "type": "object", + "properties": { + "pnfSerialNumber": { + "$id": "/properties/messageParams/properties/pnfSerialNumber", + "type": "string", + "title": "The Pnfserialnumber Schema ", + "default": "", + "examples": [ + "val1" + ] + }, + "pnfVendorName": { + "$id": "/properties/messageParams/properties/pnfVendorName", + "type": "string", + "title": "The Pnfvendorname Schema ", + "default": "", + "examples": [ + "val2" + ] + }, + "pnfOamIpv4Address": { + "$id": "/properties/messageParams/properties/pnfOamIpv4Address", + "type": "string", + "title": "The Pnfoamipv4address Schema ", + "default": "", + "examples": [ + "val3" + ] + }, + "pnfOamIpv6Address": { + "$id": "/properties/messageParams/properties/pnfOamIpv6Address", + "type": "string", + "title": "The Pnfoamipv6address Schema ", + "default": "", + "examples": [ + "val4" + ] + }, + "pnfFamily": { + "$id": "/properties/messageParams/properties/pnfFamily", + "type": "string", + "title": "The Pnffamily Schema ", + "default": "", + "examples": [ + "val5" + ] + }, + "pnfModelNumber": { + "$id": "/properties/messageParams/properties/pnfModelNumber", + "type": "string", + "title": "The Pnfmodelnumber Schema ", + "default": "", + "examples": [ + "val6" + ] + }, + "pnfSoftwareVersion": { + "$id": "/properties/messageParams/properties/pnfSoftwareVersion", + "type": "string", + "title": "The Pnfsoftwareversion Schema ", + "default": "", + "examples": [ + "val7" + ] + }, + "pnfType": { + "$id": "/properties/messageParams/properties/pnfType", + "type": "string", + "title": "The Pnftype Schema ", + "default": "", + "examples": [ + "val8" + ] + }, + "eventName": { + "$id": "/properties/messageParams/properties/eventName", + "type": "string", + "title": "The Eventname Schema ", + "default": "", + "examples": [ + "val9" + ] + }, + "nfNamingCode": { + "$id": "/properties/messageParams/properties/nfNamingCode", + "type": "string", + "title": "The Nfnamingcode Schema ", + "default": "", + "examples": [ + "val10" + ] + }, + "nfcNamingCode": { + "$id": "/properties/messageParams/properties/nfcNamingCode", + "type": "string", + "title": "The Nfcnamingcode Schema ", + "default": "", + "examples": [ + "val11" + ] + }, + "sourceName": { + "$id": "/properties/messageParams/properties/sourceName", + "type": "string", + "title": "The Sourcename Schema ", + "default": "", + "examples": [ + "val12" + ] + }, + "sourceId": { + "$id": "/properties/messageParams/properties/sourceId", + "type": "string", + "title": "The Sourceid Schema ", + "default": "", + "examples": [ + "val13" + ] + }, + "reportingEntityName": { + "$id": "/properties/messageParams/properties/reportingEntityName", + "type": "string", + "title": "The Reportingentityname Schema ", + "default": "", + "examples": [ + "val14" + ] + } + }, + "required": [ + "pnfSerialNumber", + "pnfVendorName" + ], + "anyOf": [ + { + "required": [ + "pnfOamIpv4Address" + ] + }, + { + "required": [ + "pnfOamIpv6Address" + ] + } + ] + } + }, + "required": [ + "simulatorParams", + "messageParams" + ] +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/json_schema/output_validator.json b/test/mocks/pnfsimulator/json_schema/output_validator.json new file mode 100644 index 000000000..569bbce6f --- /dev/null +++ b/test/mocks/pnfsimulator/json_schema/output_validator.json @@ -0,0 +1,286 @@ +{ + "$id": "http://example.com/example.json", + "type": "object", + "definitions": {}, + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "event": { + "$id": "/properties/event", + "type": "object", + "properties": { + "commonEventHeader": { + "$id": "/properties/event/properties/commonEventHeader", + "type": "object", + "properties": { + "sourceId": { + "$id": "/properties/event/properties/commonEventHeader/properties/sourceId", + "type": "string", + "title": "The Sourceid Schema ", + "default": "", + "examples": [ + "<<SerialNumber>>" + ] + }, + "startEpochMicrosec": { + "$id": "/properties/event/properties/commonEventHeader/properties/startEpochMicrosec", + "type": "integer", + "title": "The Startepochmicrosec Schema ", + "default": 0, + "examples": [ + 1519837825682 + ] + }, + "eventId": { + "$id": "/properties/event/properties/commonEventHeader/properties/eventId", + "type": "string", + "title": "The Eventid Schema ", + "default": "", + "examples": [ + "<<SerialNumber>>-reg" + ] + }, + "nfcNamingCode": { + "$id": "/properties/event/properties/commonEventHeader/properties/nfcNamingCode", + "type": "string", + "title": "The Nfcnamingcode Schema ", + "default": "", + "examples": [ + "5DU" + ] + }, + "internalHeaderFields": { + "$id": "/properties/event/properties/commonEventHeader/properties/internalHeaderFields", + "type": "object", + "properties": { + "collectorTimeStamp": { + "$id": "/properties/event/properties/commonEventHeader/properties/internalHeaderFields/properties/collectorTimeStamp", + "type": "string", + "title": "The Collectortimestamp Schema ", + "default": "", + "examples": [ + "Fri, 04 27 2018 09:01:10 GMT" + ] + } + } + }, + "eventType": { + "$id": "/properties/event/properties/commonEventHeader/properties/eventType", + "type": "string", + "title": "The Eventtype Schema ", + "default": "", + "examples": [ + "pnfRegistration" + ] + }, + "priority": { + "$id": "/properties/event/properties/commonEventHeader/properties/priority", + "type": "string", + "title": "The Priority Schema ", + "default": "", + "examples": [ + "Normal" + ] + }, + "version": { + "$id": "/properties/event/properties/commonEventHeader/properties/version", + "type": "integer", + "title": "The Version Schema ", + "default": 0, + "examples": [ + 3 + ] + }, + "reportingEntityName": { + "$id": "/properties/event/properties/commonEventHeader/properties/reportingEntityName", + "type": "string", + "title": "The Reportingentityname Schema ", + "default": "", + "examples": [ + "5GRAN_DU" + ] + }, + "sequence": { + "$id": "/properties/event/properties/commonEventHeader/properties/sequence", + "type": "integer", + "title": "The Sequence Schema ", + "default": 0, + "examples": [ + 0 + ] + }, + "domain": { + "$id": "/properties/event/properties/commonEventHeader/properties/domain", + "type": "string", + "title": "The Domain Schema ", + "default": "", + "examples": [ + "other" + ] + }, + "lastEpochMicrosec": { + "$id": "/properties/event/properties/commonEventHeader/properties/lastEpochMicrosec", + "type": "integer", + "title": "The Lastepochmicrosec Schema ", + "default": 0, + "examples": [ + 1519837825682 + ] + }, + "eventName": { + "$id": "/properties/event/properties/commonEventHeader/properties/eventName", + "type": "string", + "title": "The Eventname Schema ", + "default": "", + "examples": [ + "pnfRegistration_5GDU" + ] + }, + "sourceName": { + "$id": "/properties/event/properties/commonEventHeader/properties/sourceName", + "type": "string", + "title": "The Sourcename Schema ", + "default": "", + "examples": [ + "5GRAN_DU" + ] + }, + "nfNamingCode": { + "$id": "/properties/event/properties/commonEventHeader/properties/nfNamingCode", + "type": "string", + "title": "The Nfnamingcode Schema ", + "default": "", + "examples": [ + "5GRAN" + ] + } + } + }, + "otherFields": { + "$id": "/properties/event/properties/otherFields", + "type": "object", + "properties": { + "pnfLastServiceDate": { + "$id": "/properties/event/properties/otherFields/properties/pnfLastServiceDate", + "type": "integer", + "title": "The Pnflastservicedate Schema ", + "default": 0, + "examples": [ + 1517206400 + ] + }, + "pnfOamIpv6Address": { + "$id": "/properties/event/properties/otherFields/properties/pnfOamIpv6Address", + "type": "string", + "title": "The Pnfoamipv6address Schema ", + "default": "", + "examples": [ + "<<NONE>>" + ] + }, + "pnfVendorName": { + "$id": "/properties/event/properties/otherFields/properties/pnfVendorName", + "type": "string", + "title": "The Pnfvendorname Schema ", + "default": "", + "examples": [ + "Nokia" + ] + }, + "pnfModelNumber": { + "$id": "/properties/event/properties/otherFields/properties/pnfModelNumber", + "type": "string", + "title": "The Pnfmodelnumber Schema ", + "default": "", + "examples": [ + "AJ02" + ] + }, + "pnfFamily": { + "$id": "/properties/event/properties/otherFields/properties/pnfFamily", + "type": "string", + "title": "The Pnffamily Schema ", + "default": "", + "examples": [ + "BBU" + ] + }, + "pnfType": { + "$id": "/properties/event/properties/otherFields/properties/pnfType", + "type": "string", + "title": "The Pnftype Schema ", + "default": "", + "examples": [ + "AirScale" + ] + }, + "otherFieldsVersion": { + "$id": "/properties/event/properties/otherFields/properties/otherFieldsVersion", + "type": "integer", + "title": "The Otherfieldsversion Schema ", + "default": 0, + "examples": [ + 1 + ] + }, + "pnfOamIpv4Address": { + "$id": "/properties/event/properties/otherFields/properties/pnfOamIpv4Address", + "type": "string", + "title": "The Pnfoamipv4address Schema ", + "default": "", + "examples": [ + "10.16.123.234" + ] + }, + "pnfSoftwareVersion": { + "$id": "/properties/event/properties/otherFields/properties/pnfSoftwareVersion", + "type": "string", + "title": "The Pnfsoftwareversion Schema ", + "default": "", + "examples": [ + "v4.5.0.1" + ] + }, + "pnfSerialNumber": { + "$id": "/properties/event/properties/otherFields/properties/pnfSerialNumber", + "type": "string", + "title": "The Pnfserialnumber Schema ", + "default": "", + "examples": [ + "QTFCOC540002E" + ] + }, + "pnfManufactureDate": { + "$id": "/properties/event/properties/otherFields/properties/pnfManufactureDate", + "type": "integer", + "title": "The Pnfmanufacturedate Schema ", + "default": 0, + "examples": [ + 1516406400 + ] + } + }, + "required": [ + "pnfSerialNumber", + "pnfVendorName" + ], + "anyOf": [ + { + "required": [ + "pnfOamIpv4Address" + ] + }, + { + "required": [ + "pnfOamIpv6Address" + ] + } + ] + } + }, + "required": [ + "commonEventHeader", + "otherFields" + ] + } + } +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/netconf/pnf-simulator.data.xml b/test/mocks/pnfsimulator/netconf/pnf-simulator.data.xml index 83f80c451..9d648bba7 100644 --- a/test/mocks/pnfsimulator/netconf/pnf-simulator.data.xml +++ b/test/mocks/pnfsimulator/netconf/pnf-simulator.data.xml @@ -1,4 +1,4 @@ <config xmlns="http://nokia.com/pnf-simulator"> - <testDuration>10</testDuration> - <messageInterval>1</messageInterval> + <itemValue1>42</itemValue1> + <itemValue2>35</itemValue2> </config> diff --git a/test/mocks/pnfsimulator/netconf/pnf-simulator.yang b/test/mocks/pnfsimulator/netconf/pnf-simulator.yang index dda65545a..d7fc2f26e 100644 --- a/test/mocks/pnfsimulator/netconf/pnf-simulator.yang +++ b/test/mocks/pnfsimulator/netconf/pnf-simulator.yang @@ -3,7 +3,7 @@ module pnf-simulator { prefix config; container config { config true; - leaf testDuration {type uint32;} - leaf messageInterval {type uint32;} + leaf itemValue1 {type uint32;} + leaf itemValue2 {type uint32;} } } diff --git a/test/mocks/pnfsimulator/pom.xml b/test/mocks/pnfsimulator/pom.xml index 0af1f6f6d..bd203bbf6 100644 --- a/test/mocks/pnfsimulator/pom.xml +++ b/test/mocks/pnfsimulator/pom.xml @@ -1,197 +1,377 @@ <?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> +<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> - <groupId>org.onap.pnfsimulator</groupId> - <artifactId>pnf-simulator</artifactId> - <version>2.0.0-SNAPSHOT</version> - <name>pnf-simulator</name> + <groupId>org.onap.pnfsimulator</groupId> + <artifactId>pnf-simulator</artifactId> + <version>2.0.0-SNAPSHOT</version> - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <maven.compiler.source>1.8</maven.compiler.source> - <maven.compiler.target>1.8</maven.compiler.target> - <simulator.main.class>org.onap.pnfsimulator.Main</simulator.main.class> - <docker.image.tag>latest</docker.image.tag> - <dependency.directory.name>libs</dependency.directory.name> - <dependency.directory.location> - ${project.build.directory}/${dependency.directory.name} - </dependency.directory.location> - <onap.nexus.dockerregistry.daily>nexus3.onap.org:10003</onap.nexus.dockerregistry.daily> - </properties> + <name>pnf-simulator</name> - <dependencies> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter</artifactId> - <version>2.0.2.RELEASE</version> - <exclusions> - <exclusion> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-logging</artifactId> - </exclusion> - </exclusions> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-web</artifactId> - <version>2.0.2.RELEASE</version> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-log4j2</artifactId> - <version>2.0.2.RELEASE</version> - </dependency> - <dependency> - <groupId>org.apache.logging.log4j</groupId> - <artifactId>log4j-api</artifactId> - <version>2.11.0</version> - </dependency> - <dependency> - <groupId>org.apache.logging.log4j</groupId> - <artifactId>log4j-core</artifactId> - <version>2.11.0</version> - </dependency> - <dependency> - <groupId>org.apache.logging.log4j</groupId> - <artifactId>log4j-slf4j-impl</artifactId> - <version>2.11.0</version> - </dependency> - <dependency> - <groupId>org.apache.logging.log4j</groupId> - <artifactId>log4j-jul</artifactId> - <version>2.11.0</version> - <scope>runtime</scope> - </dependency> - <dependency> - <groupId>commons-io</groupId> - <artifactId>commons-io</artifactId> - <version>2.6</version> - </dependency> - <dependency> - <groupId>org.json</groupId> - <artifactId>json</artifactId> - <version>20180130</version> - </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - <version>4.5.5</version> - </dependency> - <dependency> - <groupId>com.google.guava</groupId> - <artifactId>guava</artifactId> - <version>21.0</version> - </dependency> - <dependency> - <groupId>commons-cli</groupId> - <artifactId>commons-cli</artifactId> - <version>1.4</version> - </dependency> - <dependency> - <groupId>org.junit.jupiter</groupId> - <artifactId>junit-jupiter-engine</artifactId> - <version>5.1.1</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.assertj</groupId> - <artifactId>assertj-core</artifactId> - <version>3.9.1</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-lang3</artifactId> - <version>3.7</version> - </dependency> - <dependency> - <groupId>org.onosproject</groupId> - <artifactId>jnc</artifactId> - <version>1.0</version> - </dependency> - </dependencies> + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <maven.compiler.source>1.8</maven.compiler.source> + <maven.compiler.target>1.8</maven.compiler.target> + <maven.build.timestamp.format>yyyyMMdd'T'HHmmss</maven.build.timestamp.format> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>${maven.compiler.source}</source> - <target>${maven.compiler.target}</target> - <showWarnings>true</showWarnings> - <showDeprecation>true</showDeprecation> - </configuration> - </plugin> - <plugin> - <artifactId>maven-surefire-plugin</artifactId> - <version>2.19</version> - <dependencies> - <dependency> - <groupId>org.junit.platform</groupId> - <artifactId>junit-platform-surefire-provider</artifactId> - <version>1.1.1</version> - </dependency> - </dependencies> - <configuration> - <detail>true</detail> - <printSummary>true</printSummary> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-dependency-plugin</artifactId> - <configuration> - <outputDirectory>${dependency.directory.location}</outputDirectory> - <includeScope>runtime</includeScope> - <silent>true</silent> - </configuration> - <executions> - <execution> - <id>copy-external-dependencies</id> - <phase>package</phase> - <goals> - <goal>copy-dependencies</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>com.spotify</groupId> - <artifactId>docker-maven-plugin</artifactId> - <version>1.0.0</version> - <configuration> - <imageName>${onap.nexus.dockerregistry.daily}/onap/${project.artifactId}</imageName> - <imageTags>latest</imageTags> - <imageTags>${project.version}-latest</imageTags> - <serverId>${onap.nexus.dockerregistry.daily}</serverId> - <baseImage>openjdk:8-jdk-alpine</baseImage> - <cmd>java -cp ${dependency.directory.name}/*:${project.build.finalName}.jar ${simulator.main.class}</cmd> - <resources> - <resource> - <targetPath>${dependency.directory.name}</targetPath> - <directory>${dependency.directory.location}</directory> - </resource> - <resource> - <targetPath>/</targetPath> - <directory>${project.build.directory}</directory> - <include>${project.build.finalName}.jar</include> - </resource> - </resources> - </configuration> - <executions> - <execution> - <id>build-image</id> - <phase>package</phase> - <goals> - <goal>build</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - </build> -</project> + <simulator.main.class>org.onap.pnfsimulator.Main</simulator.main.class> + <docker.image.tag>latest</docker.image.tag> + <junit.jupiter.version>5.1.0</junit.jupiter.version> + <junit.vintage.version>5.1.0</junit.vintage.version> + <docker.image.name>onap/${project.artifactId}</docker.image.name> + + <dependency.directory.name>libs</dependency.directory.name> + <dependency.directory.location>${project.build.directory}/${dependency.directory.name} + </dependency.directory.location> + + <onap.nexus.dockerregistry.daily>nexus3.onap.org:10003</onap.nexus.dockerregistry.daily> + </properties> + + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter</artifactId> + <version>2.0.2.RELEASE</version> + <exclusions> + <exclusion> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-logging</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + <version>2.0.2.RELEASE</version> + </dependency> + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-classic</artifactId> + <version>1.2.3</version> + </dependency> + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-core</artifactId> + <version>1.2.3</version> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <version>1.7.25</version> + </dependency> + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>2.6</version> + </dependency> + <dependency> + <groupId>org.json</groupId> + <artifactId>json</artifactId> + <version>20180130</version> + </dependency> + <dependency> + <groupId>org.everit.json</groupId> + <artifactId>org.everit.json.schema</artifactId> + <version>1.3.0</version> + </dependency> + <dependency> + <groupId>com.github.fge</groupId> + <artifactId>json-schema-validator</artifactId> + <version>2.2.6</version> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.8.2</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.5</version> + </dependency> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + <version>21.0</version> + </dependency> + <dependency> + <groupId>commons-cli</groupId> + <artifactId>commons-cli</artifactId> + <version>1.4</version> + </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + <version>3.7</version> + </dependency> + <dependency> + <groupId>org.onosproject</groupId> + <artifactId>jnc</artifactId> + <version>1.0</version> + </dependency> + <dependency> + <groupId>org.onosproject</groupId> + <artifactId>jnc</artifactId> + <version>1.0</version> + </dependency> + + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-api</artifactId> + <version>${junit.jupiter.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <version>5.1.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-migrationsupport</artifactId> + <version>${junit.jupiter.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.junit.vintage</groupId> + <artifactId>junit-vintage-engine</artifactId> + <version>${junit.vintage.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <version>3.9.1</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.sshd</groupId> + <artifactId>sshd-core</artifactId> + <version>0.9.0</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>2.18.3</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> + <version>5.0.4.RELEASE</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + <version>2.0.1.RELEASE</version> + <scope>test</scope> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>${maven.compiler.source}</source> + <target>${maven.compiler.target}</target> + <showWarnings>true</showWarnings> + <showDeprecation>true</showDeprecation> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jar-plugin</artifactId> + <configuration> + <archive> + <manifestEntries> + <Main-Class>${simulator.main.class}</Main-Class> + <Build-Time>${maven.build.timestamp}</Build-Time> + </manifestEntries> + </archive> + </configuration> + </plugin> + <plugin> + <groupId>pl.project13.maven</groupId> + <artifactId>git-commit-id-plugin</artifactId> + <version>2.2.4</version> + <executions> + <execution> + <id>get-commit-info</id> + <goals> + <goal>revision</goal> + </goals> + </execution> + </executions> + <configuration> + <dotGitDirectory>${project.basedir}/.git</dotGitDirectory> + <generateGitPropertiesFile>true</generateGitPropertiesFile> + <includeOnlyProperties>git.commit.id.abbrev</includeOnlyProperties> + </configuration> + </plugin> + <plugin> + <artifactId>maven-surefire-plugin</artifactId> + <version>2.19</version> + <dependencies> + <dependency> + <groupId>org.junit.platform</groupId> + <artifactId>junit-platform-surefire-provider</artifactId> + <version>1.1.1</version> + </dependency> + </dependencies> + <configuration> + <detail>true</detail> + <printSummary>true</printSummary> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + <configuration> + <outputDirectory>${dependency.directory.location}</outputDirectory> + <includeScope>runtime</includeScope> + <silent>true</silent> + </configuration> + <executions> + <execution> + <id>copy-external-dependencies</id> + <phase>package</phase> + <goals> + <goal>copy-dependencies</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>com.spotify</groupId> + <artifactId>docker-maven-plugin</artifactId> + <version>1.0.0</version> + <configuration> + <serverId>${onap.nexus.dockerregistry.daily}</serverId> + <imageName>${docker.image.name}</imageName> + <imageTags> + <tag>latest</tag> + </imageTags> + <baseImage>openjdk:8-jre-alpine</baseImage> + <cmd>java -cp ${dependency.directory.name}/*:${project.build.finalName}.jar ${simulator.main.class}</cmd> + <resources> + <resource> + <targetPath>${dependency.directory.name}</targetPath> + <directory>${dependency.directory.location}</directory> + </resource> + <resource> + <targetPath>/</targetPath> + <directory>${project.build.directory}</directory> + <include>${project.build.finalName}.jar</include> + </resource> + </resources> + </configuration> + <executions> + <execution> + <id>build-image</id> + <phase>package</phase> + <goals> + <goal>build</goal> + </goals> + </execution> + <execution> + <id>tag-and-push-image-latest</id> + <phase>deploy</phase> + <goals> + <goal>tag</goal> + </goals> + <configuration> + <image>${docker.image.name}:latest</image> + <newName>${onap.nexus.dockerregistry.daily}/${docker.image.name}:latest</newName> + <pushImage>true</pushImage> + </configuration> + </execution> + <execution> + <id>tag-and-push-image-with-version</id> + <phase>deploy</phase> + <goals> + <goal>tag</goal> + </goals> + <configuration> + <image>${docker.image.name}:latest</image> + <newName>${onap.nexus.dockerregistry.daily}/${docker.image.name}:${project.version}</newName> + <pushImage>true</pushImage> + </configuration> + </execution> + <execution> + <id>tag-and-push-image-with-version-and-date</id> + <phase>deploy</phase> + <goals> + <goal>tag</goal> + </goals> + <configuration> + <image>${docker.image.name}:latest</image> + <newName> + ${onap.nexus.dockerregistry.daily}/${docker.image.name}:${project.version}-${maven.build.timestamp} + </newName> + <pushImage>true</pushImage> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + <configuration> + <excludes> + <exclude>org/onap/pnfsimulator/Main.class</exclude> + </excludes> + </configuration> + <executions> + <execution> + <id>default-prepare-agent</id> + <goals> + <goal>prepare-agent</goal> + </goals> + </execution> + <execution> + <id>report</id> + <phase>prepare-package</phase> + <goals> + <goal>report</goal> + </goals> + </execution> + <execution> + <id>check</id> + <goals> + <goal>check</goal> + </goals> + <configuration> + <rules> + <rule> + <element>CLASS</element> + <limits> + <limit> + <value>COVEREDRATIO</value> + <minimum>0.70</minimum> + </limit> + <limit> + <counter>BRANCH</counter> + <value>COVEREDRATIO</value> + <minimum>0.75</minimum> + </limit> + </limits> + </rule> + </rules> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project>
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/simulator.sh b/test/mocks/pnfsimulator/simulator.sh index cf16e2400..a1d7c0f23 100755 --- a/test/mocks/pnfsimulator/simulator.sh +++ b/test/mocks/pnfsimulator/simulator.sh @@ -89,14 +89,14 @@ function stop(){ 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) +$(curl -s -X POST -H "Content-Type: application/json" -H "X-ONAP-RequestID: 123" -H "X-InvocationID: 456" -d @config/config.json $SIMULATOR_START_URL) EndOfMessage } function stop_simulator(){ cat << EndOfMessage Simulator response: -$(curl -s -X POST $SIMULATOR_STOP_URL | json_pp) +$(curl -s -X POST $SIMULATOR_STOP_URL) EndOfMessage } @@ -114,7 +114,7 @@ cat << EndOfMessage $(docker-compose -f $RUNNING_COMPOSE_CONFIG ps) Simulator response: -$(curl -s -X GET $SIMULATOR_STATUS_URL | json_pp) +$(curl -s -X GET $SIMULATOR_STATUS_URL) EndOfMessage } 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<String, Object> paramsMap = params.toMap(); + Map<String, Object> 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<String, String> 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<String, Object> 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<String,String> 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<String,String> 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 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Configuration complete="true" compact="true"> + + <Property name="outputFilename" value="pnfsimulator_output"/> + <Property name="log-path" value="/var/log/ONAP/pnfsimulator"/> + <Property name="archive" value="/var/log/ONAP/pnfsimulator/archive"/> + <property name="maxFileSize" value="50MB"/> + <property name="maxHistory" value="30"/> + <property name="totalSizeCap" value="10GB"/> + + <appender name="Console" target="SYSTEM_OUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <Pattern>%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</Pattern> + </encoder> + </appender> + + <appender name="ROLLING-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> + <encoder> + <pattern>%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</pattern> + </encoder> + <File>${log-path}/${outputFilename}.log</File> + <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> + <FileNamePattern>${archive}/${outputFilename}.%d{yyyy-MM-dd}.%i.log.zip</FileNamePattern> + <MaxFileSize>${maxFileSize}</MaxFileSize> + <MaxHistory>${maxHistory}</MaxHistory> + <TotalSizeCap>${totalSizeCap}</TotalSizeCap> + </rollingPolicy> + </appender> + + <root level="info"> + <appender-ref ref="Console" /> + <appender-ref ref="ROLLING-FILE" /> + </root> +</Configuration> 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 = "<?xml version=\"1.0\"?>"; + 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<String, Object> body = (Map<String, Object>) 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<String, Object> body = (Map<String, Object>) 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" + ] +} |