From cd68fc9bae7d6258f77ff59c1431e4f925f61a4c Mon Sep 17 00:00:00 2001 From: liamfallon Date: Thu, 13 Sep 2018 23:48:50 +0100 Subject: Address sonar/Checkstyle Issues Sweep through Apex codebase to fix most ceheckstyle and straightforward sonar issues. Issue-ID: POLICY-1034 Change-Id: I149d9a94ad893affc93573e8de5e3304b6bdde2d Signed-off-by: liamfallon --- .../uservice/test/adapt/events/EventGenerator.java | 501 ----------------- .../uservice/test/adapt/file/TestFile2File.java | 78 --- .../test/adapt/file/TestFile2FileFiltered.java | 108 ---- .../test/adapt/file/TestFile2FileIgnore.java | 75 --- .../uservice/test/adapt/jms/JMSEventProducer.java | 127 ----- .../test/adapt/jms/JMSEventSubscriber.java | 113 ---- .../apps/uservice/test/adapt/jms/TestContext.java | 191 ------- .../test/adapt/jms/TestInitialContextFactory.java | 48 -- .../apps/uservice/test/adapt/jms/TestJMS2JMS.java | 154 ------ .../apps/uservice/test/adapt/jms/TestPing.java | 97 ---- .../test/adapt/kafka/KafkaEventProducer.java | 166 ------ .../test/adapt/kafka/KafkaEventSubscriber.java | 111 ---- .../uservice/test/adapt/kafka/TestKafka2Kafka.java | 185 ------- .../adapt/kafka/TestKafkaXMLEventProducer.java | 63 --- .../test/adapt/restclient/TestFile2REST.java | 205 ------- .../test/adapt/restclient/TestREST2File.java | 188 ------- .../adapt/restclient/TestRESTClientEndpoint.java | 123 ----- .../test/adapt/restserver/TestRESTServer.java | 343 ------------ .../adapt/restserver/TestRESTServerVPNContext.java | 136 ----- .../apps/uservice/test/adapt/sampletypes/Foo.java | 48 -- .../uservice/test/adapt/sampletypes/FooMap.java | 48 -- .../test/adapt/websocket/TestWs2WsClient.java | 71 --- .../test/adapt/websocket/TestWs2WsServer.java | 71 --- .../websocket/WebSocketEventProducerClient.java | 176 ------ .../websocket/WebSocketEventProducerServer.java | 174 ------ .../websocket/WebSocketEventSubscriberClient.java | 104 ---- .../websocket/WebSocketEventSubscriberServer.java | 106 ---- .../test/context/EventAlbumContextTest.java | 122 ----- .../uservice/test/engdep/EngDepMessagingTest.java | 219 -------- .../uservice/test/engdep/EngineTestServer.java | 269 --------- .../uservice/adapt/events/EventGenerator.java | 610 +++++++++++++++++++++ .../uservice/adapt/file/TestFile2File.java | 78 +++ .../uservice/adapt/file/TestFile2FileFiltered.java | 112 ++++ .../uservice/adapt/file/TestFile2FileIgnore.java | 96 ++++ .../uservice/adapt/jms/JmsEventProducer.java | 162 ++++++ .../uservice/adapt/jms/JmsEventSubscriber.java | 137 +++++ .../uservice/adapt/jms/TestContext.java | 282 ++++++++++ .../adapt/jms/TestInitialContextFactory.java | 54 ++ .../uservice/adapt/jms/TestJms2Jms.java | 198 +++++++ .../integration/uservice/adapt/jms/TestPing.java | 147 +++++ .../uservice/adapt/kafka/KafkaEventProducer.java | 201 +++++++ .../uservice/adapt/kafka/KafkaEventSubscriber.java | 137 +++++ .../uservice/adapt/kafka/TestKafka2Kafka.java | 185 +++++++ .../adapt/kafka/TestKafkaXmlEventProducer.java | 70 +++ .../uservice/adapt/restclient/TestFile2Rest.java | 266 +++++++++ .../uservice/adapt/restclient/TestRest2File.java | 251 +++++++++ .../adapt/restclient/TestRestClientEndpoint.java | 163 ++++++ .../uservice/adapt/restserver/TestRestServer.java | 447 +++++++++++++++ .../adapt/restserver/TestRestServerVpnContext.java | 136 +++++ .../uservice/adapt/sampletypes/Foo.java | 48 ++ .../uservice/adapt/sampletypes/FooMap.java | 48 ++ .../uservice/adapt/websocket/TestWs2WsClient.java | 71 +++ .../uservice/adapt/websocket/TestWs2WsServer.java | 94 ++++ .../websocket/WebSocketEventProducerClient.java | 176 ++++++ .../websocket/WebSocketEventProducerServer.java | 174 ++++++ .../websocket/WebSocketEventSubscriberClient.java | 104 ++++ .../websocket/WebSocketEventSubscriberServer.java | 106 ++++ .../uservice/context/EventAlbumContextTest.java | 122 +++++ .../uservice/engdep/EngDepMessagingTest.java | 227 ++++++++ .../uservice/engdep/EngineTestServer.java | 269 +++++++++ .../test/resources/policymodels/JMSTestModel.json | 8 +- .../test/resources/prodcons/JMS2JMSJsonEvent.json | 4 +- .../resources/prodcons/JMS2JMSObjectEvent.json | 4 +- 63 files changed, 5179 insertions(+), 4428 deletions(-) delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/events/EventGenerator.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2File.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileFiltered.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileIgnore.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventProducer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventSubscriber.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestContext.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestInitialContextFactory.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestJMS2JMS.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestPing.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventProducer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventSubscriber.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafka2Kafka.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafkaXMLEventProducer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestFile2REST.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestREST2File.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestRESTClientEndpoint.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServerVPNContext.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/Foo.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/FooMap.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsClient.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsServer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerClient.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerServer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberClient.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberServer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/context/EventAlbumContextTest.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngDepMessagingTest.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngineTestServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/events/EventGenerator.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2File.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileIgnore.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventProducer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestContext.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestInitialContextFactory.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestJms2Jms.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestPing.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventProducer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventSubscriber.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafka2Kafka.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafkaXmlEventProducer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestFile2Rest.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRestClientEndpoint.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServerVpnContext.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/Foo.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/FooMap.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsClient.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerClient.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberClient.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/context/EventAlbumContextTest.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngDepMessagingTest.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngineTestServer.java (limited to 'testsuites/integration/integration-uservice-test/src/test') diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/events/EventGenerator.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/events/EventGenerator.java deleted file mode 100644 index 4c2ed5c88..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/events/EventGenerator.java +++ /dev/null @@ -1,501 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.events; - -import java.util.Random; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EventGenerator { - private static int nextEventNo = 0; - - public static String xmlEvents(final int eventCount) { - final StringBuilder builder = new StringBuilder(); - - for (int i = 0; i < eventCount; i++) { - if (i > 0) { - builder.append("\n"); - } - builder.append(xmlEvent()); - } - - return builder.toString(); - } - - public static String jsonEvents(final int eventCount) { - final StringBuilder builder = new StringBuilder(); - - for (int i = 0; i < eventCount; i++) { - if (i > 0) { - builder.append("\n"); - } - builder.append(jsonEvent()); - } - - return builder.toString(); - } - - public static String xmlEvent() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("\n"); - builder.append("\n"); - - builder.append(" " + eventName + "\n"); - builder.append(" 0.0.1\n"); - builder.append(" org.onap.policy.apex.sample.events\n"); - builder.append(" test\n"); - builder.append(" apex\n"); - builder.append(" \n"); - builder.append(" TestSlogan\n"); - builder.append(" Test slogan for External Event" + (nextEventNo++) + "\n"); - builder.append(" \n"); - builder.append(" \n"); - builder.append(" TestMatchCase\n"); - builder.append(" " + nextMatchCase + "\n"); - builder.append(" \n"); - builder.append(" \n"); - builder.append(" TestTimestamp\n"); - builder.append(" " + System.currentTimeMillis() + "\n"); - builder.append(" \n"); - builder.append(" \n"); - builder.append(" TestTemperature\n"); - builder.append(" " + nextTestTemperature + "\n"); - builder.append(" \n"); - builder.append(""); - - return builder.toString(); - } - - public static String jsonEvent() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoName() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"namez\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadName() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"%%%%\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoExName() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"I_DONT_EXIST\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoVersion() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"versiion\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadVersion() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"#####\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoExVersion() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"Event0000\",\n"); - builder.append(" \"version\": \"1.2.3\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoNamespace() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpacee\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadNamespace() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"hello.&&&&\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoExNamespace() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"pie.in.the.sky\",\n"); - builder.append(" \"name\": \"Event0000\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoSource() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"sourcee\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadSource() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"%!@**@!\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoTarget() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"targett\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadTarget() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"KNIO(*S)A(S)D\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventMissingFields() { - final StringBuilder builder = new StringBuilder(); - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"Event0000\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\"\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNullFields() { - final StringBuilder builder = new StringBuilder(); - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"Event0000\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"Apex\",\n"); - builder.append(" \"TestSlogan\": null,\n"); - builder.append(" \"TestMatchCase\": -1,\n"); - builder.append(" \"TestTimestamp\": -1,\n"); - builder.append(" \"TestTemperature\": -1.0\n"); - builder.append("}"); - - return builder.toString(); - } - - public static void main(final String[] args) { - if (args.length != 2) { - System.err.println("usage EventGenerator #events XML|JSON"); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage EventGenerator #events XML|JSON"); - e.printStackTrace(); - return; - } - - if (args[1].equalsIgnoreCase("XML")) { - System.out.println(xmlEvents(eventCount)); - } else if (args[1].equalsIgnoreCase("JSON")) { - System.out.println(jsonEvents(eventCount)); - } else { - System.err.println("usage EventGenerator #events XML|JSON"); - return; - } - } - - public static int getNextEventNo() { - return nextEventNo; - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2File.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2File.java deleted file mode 100644 index 347cce80e..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2File.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.file; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestFile2File { - - @Test - public void testJsonFileEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileJsonEvent.json"}; - - testFileEvents(args, "src/test/resources/events/EventsOut.json", 48956); - } - - @Test - public void testXMLFileEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileXmlEvent.json"}; - - testFileEvents(args, "src/test/resources/events/EventsOut.xmlfile", 106739); - } - - private void testFileEvents(final String[] args, final String outFilePath, final long expectedFileSize) - throws MessagingException, ApexException, IOException { - final ApexMain apexMain = new ApexMain(args); - - final File outFile = new File(outFilePath); - - while (!outFile.exists()) { - ThreadUtilities.sleep(500); - } - - // Wait for the file to be filled - long outFileSize = 0; - while (true) { - final String fileString = TextFileUtils.getTextFileAsString(outFilePath).replaceAll("\\s+", ""); - outFileSize = fileString.length(); - if (outFileSize > 0 && outFileSize >= expectedFileSize) { - break; - } - ThreadUtilities.sleep(500); - } - - apexMain.shutdown(); - outFile.delete(); - assertEquals(outFileSize, expectedFileSize); - } -} - - diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileFiltered.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileFiltered.java deleted file mode 100644 index c2b097273..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileFiltered.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.file; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestFile2FileFiltered { - - @Test - public void testJsonFilteredFileInOutEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileFilteredInOutJsonEvent.json"}; - - final String[] outFilePaths = - {"src/test/resources/events/Events0004Out.json", "src/test/resources/events/Events0104Out.json"}; - - final long[] expectedFileSizes = {25949, 23007}; - - testFilteredFileEvents(args, outFilePaths, expectedFileSizes); - } - - @Test - public void testJsonFilteredFileOutEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileFilteredOutJsonEvent.json"}; - - final String[] outFilePaths = - {"src/test/resources/events/Events0004Out.json", "src/test/resources/events/Events0104Out.json"}; - - final long[] expectedFileSizes = {25949, 23007}; - - testFilteredFileEvents(args, outFilePaths, expectedFileSizes); - } - - @Test - public void testJsonFilteredFileInEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileFilteredInJsonEvent.json"}; - - final String[] outFilePaths = {"src/test/resources/events/Events0004Out.json"}; - - final long[] expectedFileSizes = {25949}; - - testFilteredFileEvents(args, outFilePaths, expectedFileSizes); - } - - private void testFilteredFileEvents(final String[] args, final String[] outFilePaths, - final long[] expectedFileSizes) throws MessagingException, ApexException, IOException { - final ApexMain apexMain = new ApexMain(args); - - final File outFile0 = new File(outFilePaths[0]); - - while (!outFile0.exists()) { - ThreadUtilities.sleep(500); - } - - // Wait for the file to be filled - long outFile0Size = 0; - for (int i = 0; i < 4; i++) { - final String fileString = TextFileUtils.getTextFileAsString(outFilePaths[0]).replaceAll("\\s+", ""); - outFile0Size = fileString.length(); - if (outFile0Size > 0 && outFile0Size >= expectedFileSizes[0]) { - break; - } - ThreadUtilities.sleep(500); - } - - ThreadUtilities.sleep(500); - apexMain.shutdown(); - - final long[] actualFileSizes = new long[expectedFileSizes.length]; - - for (int i = 0; i < outFilePaths.length; i++) { - final String fileString = TextFileUtils.getTextFileAsString(outFilePaths[i]).replaceAll("\\s+", ""); - actualFileSizes[i] = fileString.length(); - new File(outFilePaths[i]).delete(); - } - - for (int i = 0; i < actualFileSizes.length; i++) { - assertEquals(actualFileSizes[i], expectedFileSizes[i]); - } - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileIgnore.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileIgnore.java deleted file mode 100644 index c952d73b5..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileIgnore.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.file; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; - -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestFile2FileIgnore { - - // This test is used just to bring up an instance of Apex for manual testing and demonstrations - // It should always be ignored in automated testing because it holds Apex up for a very long - // time - public static void main(final String[] args) throws MessagingException, ApexException, IOException { - final String[] apexArgs = {"src/test/resources/prodcons/File2FileJsonEvent.json"}; - - testFileEvents(apexArgs, "src/test/resources/events/EventsOut.json", 48656); - } - - private static void testFileEvents(final String[] args, final String outFilePath, final long expectedFileSize) - throws MessagingException, ApexException, IOException { - final ApexMain apexMain = new ApexMain(args); - - final File outFile = new File(outFilePath); - - while (!outFile.exists()) { - ThreadUtilities.sleep(500); - } - - // Wait for the file to be filled - long outFileSize = 0; - while (true) { - final String fileString = TextFileUtils.getTextFileAsString(outFilePath).replaceAll("\\s+", ""); - outFileSize = fileString.length(); - if (outFileSize > 0 && outFileSize >= expectedFileSize) { - break; - } - ThreadUtilities.sleep(500); - } - - // Here's the long time I was talking about above! - ThreadUtilities.sleep(100000000); - - apexMain.shutdown(); - outFile.delete(); - assertEquals(outFileSize, expectedFileSize); - } -} - - diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventProducer.java deleted file mode 100644 index 8b9f2a112..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventProducer.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.Topic; - -import org.apache.activemq.command.ActiveMQTopic; -import org.onap.policy.apex.apps.uservice.test.adapt.events.EventGenerator; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JMSEventProducer implements Runnable { - private static final Logger LOGGER = LoggerFactory.getLogger(JMSEventProducer.class); - - private final String topic; - private final int eventCount; - private final boolean sendObjects; - private final long eventInterval; - private long eventsSentCount = 0; - - private final Thread producerThread; - private boolean sendEventsFlag = false; - private boolean stopFlag = false; - private final Connection connection; - - public JMSEventProducer(final String topic, final ConnectionFactory connectionFactory, final String username, - final String password, final int eventCount, final boolean sendObjects, final long eventInterval) - throws JMSException { - this.topic = topic; - this.eventCount = eventCount; - this.sendObjects = sendObjects; - this.eventInterval = eventInterval; - connection = connectionFactory.createConnection(username, password); - connection.start(); - - producerThread = new Thread(this); - producerThread.start(); - } - - @Override - public void run() { - final Topic jmsTopic = new ActiveMQTopic(topic); - try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer jmsProducer = jmsSession.createProducer(jmsTopic);) { - - while (producerThread.isAlive() && !stopFlag) { - ThreadUtilities.sleep(50); - - if (sendEventsFlag) { - sendEventsToTopic(jmsSession, jmsProducer); - sendEventsFlag = false; - } - } - - } catch (final Exception e) { - throw new ApexEventRuntimeException("JMS event consumption failed", e); - } - } - - public void sendEvents() { - sendEventsFlag = true; - } - - private void sendEventsToTopic(final Session jmsSession, final MessageProducer jmsProducer) throws JMSException { - - LOGGER.info("{} : sending events to JMS server, event count {}", this.getClass().getCanonicalName(), - eventCount); - - for (int i = 0; i < eventCount; i++) { - ThreadUtilities.sleep(eventInterval); - - Message jmsMessage = null; - if (sendObjects) { - jmsMessage = jmsSession.createObjectMessage(new TestPing()); - } else { - jmsMessage = jmsSession.createTextMessage(EventGenerator.jsonEvent()); - } - jmsProducer.send(jmsMessage); - eventsSentCount++; - } - LOGGER.info("{} : completed, number of events sent", this.getClass().getCanonicalName(), eventsSentCount); - } - - public long getEventsSentCount() { - return eventsSentCount; - } - - public void shutdown() { - LOGGER.info("{} : stopping", this.getClass().getCanonicalName()); - stopFlag = true; - - while (producerThread.isAlive()) { - ThreadUtilities.sleep(10); - } - LOGGER.info("{} : stopped", this.getClass().getCanonicalName()); - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventSubscriber.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventSubscriber.java deleted file mode 100644 index 916216a5a..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventSubscriber.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.ObjectMessage; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; - -import org.apache.activemq.command.ActiveMQTopic; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JMSEventSubscriber implements Runnable { - private static final Logger LOGGER = LoggerFactory.getLogger(JMSEventSubscriber.class); - - private final String topic; - private long eventsReceivedCount = 0; - - private final Thread subscriberThread; - private final Connection connection; - - - public JMSEventSubscriber(final String topic, final ConnectionFactory connectionFactory, final String username, - final String password) throws JMSException { - this.topic = topic; - connection = connectionFactory.createConnection(username, password); - connection.start(); - - subscriberThread = new Thread(this); - subscriberThread.start(); - } - - @Override - public void run() { - final Topic jmsTopic = new ActiveMQTopic(topic); - try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer jmsConsumer = jmsSession.createConsumer(jmsTopic);) { - - while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) { - try { - final Message message = jmsConsumer.receive(100); - if (message == null) { - continue; - } - - if (message instanceof ObjectMessage) { - final TestPing testPing = (TestPing) ((ObjectMessage) message).getObject(); - testPing.verify(); - } else if (message instanceof TextMessage) { - ((TextMessage) message).getText(); - } else { - throw new ApexEventException("unknowm message \"" + message + "\" of type \"" - + message.getClass().getCanonicalName() + "\" received"); - } - eventsReceivedCount++; - } catch (final Exception e) { - break; - } - } - - } catch (final Exception e) { - throw new ApexEventRuntimeException("JMS event consumption failed", e); - } - - LOGGER.info("{} : event reception completed", this.getClass().getCanonicalName()); - } - - public long getEventsReceivedCount() { - return eventsReceivedCount; - } - - public void shutdown() throws JMSException { - subscriberThread.interrupt(); - - while (subscriberThread.isAlive()) { - ThreadUtilities.sleep(10); - } - - connection.close(); - LOGGER.info("{} : stopped", this.getClass().getCanonicalName()); - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestContext.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestContext.java deleted file mode 100644 index de3c8d37b..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestContext.java +++ /dev/null @@ -1,191 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.HOST; -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.JMS_TOPIC_APEX_IN; -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.JMS_TOPIC_APEX_OUT; -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.PORT; -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.connectionFactory; - -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; -import java.util.Properties; - -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NameClassPair; -import javax.naming.NameParser; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; - -import org.apache.activemq.command.ActiveMQTopic; -import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContext implements Context { - - private Properties testProperties; - - public TestContext() { - try { - testProperties = new Properties(); - - final Map params = new HashMap(); - params.put("host", HOST); - params.put("port", PORT); - testProperties.put("ConnectionFactory", connectionFactory); - testProperties.put(JMS_TOPIC_APEX_IN, new ActiveMQTopic(JMS_TOPIC_APEX_IN)); - testProperties.put(JMS_TOPIC_APEX_OUT, new ActiveMQTopic(JMS_TOPIC_APEX_OUT)); - } catch (final Exception e) { - e.printStackTrace(); - throw new ApexRuntimeException("Context initiation failed", e); - } - } - - @Override - public Object lookup(final Name name) throws NamingException { - return null; - } - - @Override - public Object lookup(final String name) throws NamingException { - return testProperties.get(name); - } - - @Override - public void bind(final Name name, final Object obj) throws NamingException {} - - @Override - public void bind(final String name, final Object obj) throws NamingException {} - - @Override - public void rebind(final Name name, final Object obj) throws NamingException {} - - @Override - public void rebind(final String name, final Object obj) throws NamingException {} - - @Override - public void unbind(final Name name) throws NamingException {} - - @Override - public void unbind(final String name) throws NamingException {} - - @Override - public void rename(final Name oldName, final Name newName) throws NamingException {} - - @Override - public void rename(final String oldName, final String newName) throws NamingException {} - - @Override - public NamingEnumeration list(final Name name) throws NamingException { - return null; - } - - @Override - public NamingEnumeration list(final String name) throws NamingException { - return null; - } - - @Override - public NamingEnumeration listBindings(final Name name) throws NamingException { - return null; - } - - @Override - public NamingEnumeration listBindings(final String name) throws NamingException { - return null; - } - - @Override - public void destroySubcontext(final Name name) throws NamingException {} - - @Override - public void destroySubcontext(final String name) throws NamingException {} - - @Override - public Context createSubcontext(final Name name) throws NamingException { - return null; - } - - @Override - public Context createSubcontext(final String name) throws NamingException { - return null; - } - - @Override - public Object lookupLink(final Name name) throws NamingException { - return null; - } - - @Override - public Object lookupLink(final String name) throws NamingException { - return null; - } - - @Override - public NameParser getNameParser(final Name name) throws NamingException { - return null; - } - - @Override - public NameParser getNameParser(final String name) throws NamingException { - return null; - } - - @Override - public Name composeName(final Name name, final Name prefix) throws NamingException { - return null; - } - - @Override - public String composeName(final String name, final String prefix) throws NamingException { - return null; - } - - @Override - public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { - return null; - } - - @Override - public Object removeFromEnvironment(final String propName) throws NamingException { - return null; - } - - @Override - public Hashtable getEnvironment() throws NamingException { - return null; - } - - @Override - public void close() throws NamingException {} - - @Override - public String getNameInNamespace() throws NamingException { - return null; - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestInitialContextFactory.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestInitialContextFactory.java deleted file mode 100644 index 6cb874671..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestInitialContextFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import java.util.Hashtable; - -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.spi.InitialContextFactory; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestInitialContextFactory implements InitialContextFactory { - - private final Context context = new TestContext(); - - public TestInitialContextFactory() throws NamingException {} - - /* - * (non-Javadoc) - * - * @see javax.naming.spi.InitialContextFactory#getInitialContext(java.util.Hashtable) - */ - @Override - public Context getInitialContext(final Hashtable environment) throws NamingException { - return context; - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestJMS2JMS.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestJMS2JMS.java deleted file mode 100644 index f021b2674..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestJMS2JMS.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.jms.JMSException; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.security.AuthenticationUser; -import org.apache.activemq.security.SimpleAuthenticationPlugin; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -public class TestJMS2JMS { - public static final String PORT = "5445"; - public static final String HOST = "localhost"; - public static final String JMS_TOPIC_APEX_IN = "jms/topic/apexIn"; - public static final String JMS_TOPIC_APEX_OUT = "jms/topic/apexOut"; - - private static final int SLEEP_TIME = 1500; - private static final String GROUP_ROLE = "guests"; - private static final String PACKAGE_NAME = "org.onap.policy.apex.apps.uservice.test.adapt.jms"; - private static final String USERNAME = "guest"; - private static final String PASSWORD = "IAmAGuest"; - private static final String URL = "tcp://" + HOST + ":" + PORT; - - private static final String DATA_PARENT_DIR = Paths.get("target", "activemq-data").toString(); - - private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestJMS2JMS.class); - - private static final long MAX_TEST_LENGTH = 10000; - private static final int EVENT_COUNT = 100; - private static final int EVENT_INTERVAL = 20; - - private static BrokerService broker; - - public static ActiveMQConnectionFactory connectionFactory; - - - @BeforeClass - public static void setupEmbeddedJMSServer() throws Exception { - final ArrayList plugins = new ArrayList(); - final BrokerPlugin authenticationPlugin = getAuthenticationBrokerPlugin(); - plugins.add(authenticationPlugin); - - broker = new BrokerService(); - broker.setUseJmx(false); - broker.setPersistent(false); - broker.addConnector(URL); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPlugins(plugins.toArray(new BrokerPlugin[0])); - broker.setDataDirectory(DATA_PARENT_DIR); - broker.start(); - broker.waitUntilStarted(); - connectionFactory = new ActiveMQConnectionFactory(URL); - connectionFactory.setTrustedPackages(Arrays.asList(PACKAGE_NAME)); - } - - private static BrokerPlugin getAuthenticationBrokerPlugin() { - final List users = new ArrayList(); - users.add(new AuthenticationUser(USERNAME, PASSWORD, GROUP_ROLE)); - final SimpleAuthenticationPlugin authenticationPlugin = new SimpleAuthenticationPlugin(users); - return authenticationPlugin; - } - - @AfterClass - public static void shutdownEmbeddedJMSServer() throws IOException { - try { - if (broker != null) { - broker.stop(); - } - } catch (final Exception e) { - LOGGER.warn("Failed to stop JMS server", e); - } - - } - - @Test - public void testJMSObjectEvents() throws ApexException, JMSException { - final String[] args = { "src/test/resources/prodcons/JMS2JMSObjectEvent.json" }; - testJMSEvents(args, true); - } - - @Test - public void testJMSJsonEvents() throws ApexException, JMSException { - final String[] args = { "src/test/resources/prodcons/JMS2JMSJsonEvent.json" }; - testJMSEvents(args, false); - } - - private void testJMSEvents(final String[] args, final Boolean sendObjects) throws ApexException, JMSException { - final JMSEventSubscriber subscriber = - new JMSEventSubscriber(JMS_TOPIC_APEX_OUT, connectionFactory, USERNAME, PASSWORD); - final JMSEventProducer producer = new JMSEventProducer(JMS_TOPIC_APEX_IN, connectionFactory, USERNAME, PASSWORD, - EVENT_COUNT, sendObjects, EVENT_INTERVAL); - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(3000); - - producer.sendEvents(); - - final long testStartTime = System.currentTimeMillis(); - - while (isTimedOut(testStartTime) && subscriber.getEventsReceivedCount() < EVENT_COUNT) { - ThreadUtilities.sleep(EVENT_INTERVAL); - } - - ThreadUtilities.sleep(SLEEP_TIME); - apexMain.shutdown(); - subscriber.shutdown(); - producer.shutdown(); - ThreadUtilities.sleep(SLEEP_TIME); - - assertEquals(EVENT_COUNT, producer.getEventsSentCount()); - assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount()); - - } - - private boolean isTimedOut(final long testStartTime) { - return System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH; - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestPing.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestPing.java deleted file mode 100644 index caf6e2ffd..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestPing.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import java.io.Serializable; - -import org.onap.policy.apex.service.engine.event.ApexEventException; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestPing implements Serializable { - private static final long serialVersionUID = -3400711508992955886L; - - private String name = "Rose"; - private String description = "A rose by any other name would smell as sweet"; - private long pingTime = System.currentTimeMillis(); - private long pongTime = -1; - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(final String description) { - this.description = description; - } - - public long getPingTime() { - return pingTime; - } - - public void setPingTime(final long pingTime) { - this.pingTime = pingTime; - } - - public long getPongTime() { - return pongTime; - } - - public void setPongTime(final long pongTime) { - this.pongTime = pongTime; - } - - @Override - public String toString() { - return "TestPing [name=" + name + ", description=" + description + ", pingTime=" + pingTime + ", pongTime=" - + pongTime + "]"; - } - - public void verify() throws ApexEventException { - if (!name.startsWith("Rose")) { - throw new ApexEventException("TestPing is not valid"); - } - - if (name.length() <= 4) { - throw new ApexEventException("TestPing is not valid"); - } - - if (!description.startsWith("A rose by any other name would smell as sweet")) { - throw new ApexEventException("TestPing is not valid"); - } - - if (description.length() <= 44) { - throw new ApexEventException("TestPing is not valid"); - } - - if (pongTime <= pingTime) { - throw new ApexEventException("TestPing is not valid"); - } - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventProducer.java deleted file mode 100644 index c243b8b07..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventProducer.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.kafka; - -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.onap.policy.apex.apps.uservice.test.adapt.events.EventGenerator; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class KafkaEventProducer implements Runnable { - private final String topic; - private final String kafkaServerAddress; - private final int eventCount; - private final boolean xmlEvents; - private final long eventInterval; - private long eventsSentCount = 0; - - private final Thread producerThread; - private boolean sendEventsFlag = false; - private boolean stopFlag = false; - - public KafkaEventProducer(final String topic, final String kafkaServerAddress, final int eventCount, - final boolean xmlEvents, final long eventInterval) { - this.topic = topic; - this.kafkaServerAddress = kafkaServerAddress; - this.eventCount = eventCount; - this.xmlEvents = xmlEvents; - this.eventInterval = eventInterval; - - producerThread = new Thread(this); - producerThread.start(); - } - - @Override - public void run() { - final Properties kafkaProducerProperties = new Properties(); - kafkaProducerProperties.put("bootstrap.servers", kafkaServerAddress); - kafkaProducerProperties.put("acks", "all"); - kafkaProducerProperties.put("retries", 0); - kafkaProducerProperties.put("batch.size", 16384); - kafkaProducerProperties.put("linger.ms", 1); - kafkaProducerProperties.put("buffer.memory", 33554432); - kafkaProducerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - kafkaProducerProperties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - - final Producer producer = new KafkaProducer(kafkaProducerProperties); - - while (producerThread.isAlive() && !stopFlag) { - ThreadUtilities.sleep(50); - - if (sendEventsFlag) { - sendEventsToTopic(producer); - sendEventsFlag = false; - } - } - - producer.close(1000, TimeUnit.MILLISECONDS); - } - - public void sendEvents() { - sendEventsFlag = true; - } - - private void sendEventsToTopic(final Producer producer) { - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": sending events to Kafka server at " - + kafkaServerAddress + ", event count " + eventCount + ", xmlEvents " + xmlEvents); - - for (int i = 0; i < eventCount; i++) { - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": waiting " + eventInterval - + " milliseconds before sending next event"); - ThreadUtilities.sleep(eventInterval); - - String eventString = null; - if (xmlEvents) { - eventString = EventGenerator.xmlEvent(); - } else { - eventString = EventGenerator.jsonEvent(); - } - producer.send(new ProducerRecord(topic, "Event" + i + "Of" + eventCount, eventString)); - producer.flush(); - eventsSentCount++; - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": sent event " + eventString); - } - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": completed"); - } - - public long getEventsSentCount() { - return eventsSentCount; - } - - public void shutdown() { - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": stopping"); - - stopFlag = true; - - while (producerThread.isAlive()) { - ThreadUtilities.sleep(10); - } - - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": stopped"); - } - - public static void main(final String[] args) { - if (args.length != 5) { - System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[2]); - } catch (final Exception e) { - System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - long eventInterval = 0; - try { - eventInterval = Long.parseLong(args[4]); - } catch (final Exception e) { - System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - boolean xmlEvents = false; - if (args[3].equalsIgnoreCase("XML")) { - xmlEvents = true; - } else if (!args[3].equalsIgnoreCase("JSON")) { - System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); - return; - } - - final KafkaEventProducer producer = new KafkaEventProducer(args[0], args[1], eventCount, xmlEvents, - eventInterval); - - producer.sendEvents(); - producer.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventSubscriber.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventSubscriber.java deleted file mode 100644 index 8bdc56dda..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventSubscriber.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.kafka; - -import java.util.Arrays; -import java.util.Properties; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class KafkaEventSubscriber implements Runnable { - private final String topic; - private final String kafkaServerAddress; - private long eventsReceivedCount = 0; - - KafkaConsumer consumer; - - Thread subscriberThread; - - public KafkaEventSubscriber(final String topic, final String kafkaServerAddress) throws MessagingException { - this.topic = topic; - this.kafkaServerAddress = kafkaServerAddress; - - final Properties props = new Properties(); - props.put("bootstrap.servers", kafkaServerAddress); - props.put("group.id", "test"); - props.put("enable.auto.commit", "true"); - props.put("auto.commit.interval.ms", "1000"); - props.put("session.timeout.ms", "30000"); - props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - - consumer = new KafkaConsumer(props); - consumer.subscribe(Arrays.asList(topic)); - - subscriberThread = new Thread(this); - subscriberThread.start(); - } - - @Override - public void run() { - System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": receiving events from Kafka server at " - + kafkaServerAddress + " on topic " + topic); - - while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) { - try { - final ConsumerRecords records = consumer.poll(100); - for (final ConsumerRecord record : records) { - System.out.println("******"); - System.out.println("offset=" + record.offset()); - System.out.println("key=" + record.key()); - System.out.println("name=" + record.value()); - eventsReceivedCount++; - } - } catch (final Exception e) { - // Thread interrupted - break; - } - } - - System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": event reception completed"); - } - - public long getEventsReceivedCount() { - return eventsReceivedCount; - } - - public void shutdown() { - subscriberThread.interrupt(); - - while (subscriberThread.isAlive()) { - ThreadUtilities.sleep(10); - } - - consumer.close(); - System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": stopped"); - } - - - public static void main(final String[] args) throws MessagingException { - if (args.length != 2) { - System.err.println("usage KafkaEventSubscriber topic kafkaServerAddress"); - return; - } - new KafkaEventSubscriber(args[0], args[1]); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafka2Kafka.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafka2Kafka.java deleted file mode 100644 index c95498a05..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafka2Kafka.java +++ /dev/null @@ -1,185 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.kafka; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.nio.file.Files; -import java.util.Properties; - -import kafka.admin.AdminUtils; -import kafka.admin.RackAwareMode; -import kafka.server.KafkaConfig; -import kafka.server.KafkaServer; -import kafka.utils.TestUtils; -import kafka.utils.ZKStringSerializer$; -import kafka.utils.ZkUtils; -import kafka.zk.EmbeddedZookeeper; - -import org.I0Itec.zkclient.ZkClient; -import org.apache.kafka.common.utils.MockTime; -import org.apache.kafka.common.utils.Time; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - - -/** - * The Class TestKafka2Kafka. - */ -public class TestKafka2Kafka { - // The method of starting an embedded Kafka server used in this example is based on the method - // on stack overflow at - // https://github.com/asmaier/mini-kafka - - private static final long MAX_TEST_LENGTH = 20000; - - private static final int EVENT_COUNT = 10; - private static final int EVENT_INTERVAL = 20; - - private static final String ZKHOST = "127.0.0.1"; - private static final String BROKERHOST = "127.0.0.1"; - private static final String BROKERPORT = "39902"; - - private static EmbeddedZookeeper zkServer; - private static ZkClient zkClient; - private static KafkaServer kafkaServer; - - /** - * Setup dummy kafka server. - * - * @throws IOException Signals that an I/O exception has occurred. - */ - @BeforeClass - public static void setupDummyKafkaServer() throws IOException { - // setup Zookeeper - zkServer = new EmbeddedZookeeper(); - final String zkConnect = ZKHOST + ":" + zkServer.port(); - zkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer$.MODULE$); - final ZkUtils zkUtils = ZkUtils.apply(zkClient, false); - - // setup Broker - final Properties brokerProps = new Properties(); - brokerProps.setProperty("zookeeper.connect", zkConnect); - brokerProps.setProperty("broker.id", "0"); - brokerProps.setProperty("log.dirs", Files.createTempDirectory("kafka-").toAbsolutePath().toString()); - brokerProps.setProperty("listeners", "PLAINTEXT://" + BROKERHOST + ":" + BROKERPORT); - brokerProps.setProperty("offsets.topic.replication.factor", "1"); - brokerProps.setProperty("transaction.state.log.replication.factor", "1"); - brokerProps.setProperty("transaction.state.log.min.isr", "1"); - final KafkaConfig config = new KafkaConfig(brokerProps); - final Time mock = new MockTime(); - kafkaServer = TestUtils.createServer(config, mock); - kafkaServer.startup(); - - // create topics - AdminUtils.createTopic(zkUtils, "apex-in-0", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); - AdminUtils.createTopic(zkUtils, "apex-in-1", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); - AdminUtils.createTopic(zkUtils, "apex-out", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); - - } - - /** - * Shutdown dummy kafka server. - * - * @throws IOException Signals that an I/O exception has occurred. - */ - @AfterClass - public static void shutdownDummyKafkaServer() throws IOException { - if (kafkaServer != null) { - kafkaServer.shutdown(); - } - if (zkClient != null) { - zkClient.close(); - } - if (zkServer != null) { - zkServer.shutdown(); - } - } - - /** - * Test json kafka events. - * - * @throws MessagingException the messaging exception - * @throws ApexException the apex exception - */ - @Test - public void testJsonKafkaEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Kafka2KafkaJsonEvent.json"}; - testKafkaEvents(args, false, "json"); - } - - /** - * Test XML kafka events. - * - * @throws MessagingException the messaging exception - * @throws ApexException the apex exception - */ - @Test - public void testXmlKafkaEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Kafka2KafkaXmlEvent.json"}; - testKafkaEvents(args, true, "xml"); - } - - /** - * Test kafka events. - * - * @param args the args - * @param xmlEvents the xml events - * @param topicSuffix the topic suffix - * @throws MessagingException the messaging exception - * @throws ApexException the apex exception - */ - private void testKafkaEvents(final String[] args, final Boolean xmlEvents, final String topicSuffix) - throws MessagingException, ApexException { - final KafkaEventSubscriber subscriber = - new KafkaEventSubscriber("apex-out-" + topicSuffix, "localhost:" + BROKERPORT); - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(3000); - - final KafkaEventProducer producer = new KafkaEventProducer("apex-in-" + topicSuffix, "localhost:" + BROKERPORT, - EVENT_COUNT, xmlEvents, EVENT_INTERVAL); - - producer.sendEvents(); - - final long testStartTime = System.currentTimeMillis(); - - while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH - && subscriber.getEventsReceivedCount() < EVENT_COUNT) { - ThreadUtilities.sleep(EVENT_INTERVAL); - } - - ThreadUtilities.sleep(1000); - - assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount()); - - apexMain.shutdown(); - subscriber.shutdown(); - producer.shutdown(); - ThreadUtilities.sleep(1000); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafkaXMLEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafkaXMLEventProducer.java deleted file mode 100644 index 80b4aef55..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafkaXMLEventProducer.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.kafka; - -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEvent; -import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEventData; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestKafkaXMLEventProducer { - - public static void main(final String[] args) { - final Properties props = new Properties(); - props.put("bootstrap.servers", "localhost:49092"); - props.put("acks", "all"); - props.put("retries", 0); - props.put("batch.size", 16384); - props.put("linger.ms", 1); - props.put("buffer.memory", 33554432); - props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - - final XMLApexEvent xmlEvent = new XMLApexEvent(); - xmlEvent.setName("XMLEvent-1"); - xmlEvent.setVersion("0.0.1"); - xmlEvent.getData().add(new XMLApexEventData("Data-1", "Data Value -1")); - - final Producer producer = new KafkaProducer(props); - for (int i = 0; i < 100; i++) { - xmlEvent.setName("XMLEvent" + Integer.toString(i)); - xmlEvent.setVersion("0.0.1"); - xmlEvent.getData() - .add(new XMLApexEventData("Data" + Integer.toString(i), "Data Value " + Integer.toString(i))); - - producer.send(new ProducerRecord("apex-in-0", xmlEvent.getName(), xmlEvent.toString())); - } - producer.close(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestFile2REST.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestFile2REST.java deleted file mode 100644 index dd3f15ab6..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestFile2REST.java +++ /dev/null @@ -1,205 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.net.URI; -import java.util.Map; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.core.Response; - -import org.glassfish.grizzly.http.server.HttpServer; -import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; -import org.glassfish.jersey.server.ResourceConfig; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - -import com.google.gson.Gson; - - -public class TestFile2REST { - private static final String BASE_URI = "http://localhost:32801/TestFile2Rest"; - private static HttpServer server; - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - - private final PrintStream stdout = System.out; - private final PrintStream stderr = System.err; - - @BeforeClass - public static void setUp() throws Exception { - final ResourceConfig rc = new ResourceConfig(TestRESTClientEndpoint.class); - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); - - while (!server.isStarted()) { - ThreadUtilities.sleep(50); - } - } - - @AfterClass - public static void tearDown() throws Exception { - server.shutdown(); - } - - @Test - public void testFileEventsPost() throws MessagingException, ApexException, IOException { - final Client client = ClientBuilder.newClient(); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventPost.json"}; - final ApexMain apexMain = new ApexMain(args); - - // Wait for the required amount of events to be received or for 10 seconds - for (int i = 0; i < 100; i++) { - ThreadUtilities.sleep(100); - final Response response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats") - .request("application/json").get(); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - if ((double) jsonMap.get("POST") == 100) { - break; - } - } - - apexMain.shutdown(); - } - - @Test - public void testFileEventsPut() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventPut.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - // Wait for the required amount of events to be received or for 10 seconds - for (int i = 0; i < 100; i++) { - ThreadUtilities.sleep(100); - final Response response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats") - .request("application/json").get(); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - if ((double) jsonMap.get("PUT") == 100) { - break; - } - } - - apexMain.shutdown(); - } - - @Test - public void testFileEventsNoURL() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventNoURL.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains(" no URL has been set for event sending on REST client")); - } - - @Test - public void testFileEventsBadURL() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventBadURL.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/Bad\" using HTTP \"POST\" failed with status code 404")); - } - - @Test - public void testFileEventsBadHTTPMethod() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "specified HTTP method of \"DELETE\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supproted for event sending on REST client producer")); - } - - @Test - public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(500); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/PostEventBadResponse\" using HTTP \"POST\" failed with status code 400")); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestREST2File.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestREST2File.java deleted file mode 100644 index 922e03217..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestREST2File.java +++ /dev/null @@ -1,188 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restclient; - -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.net.URI; - -import org.glassfish.grizzly.http.server.HttpServer; -import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; -import org.glassfish.jersey.server.ResourceConfig; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; - - -public class TestREST2File { - - private static final String BASE_URI = "http://localhost:32801/TestRest2File"; - private HttpServer server; - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - - private final PrintStream stdout = System.out; - private final PrintStream stderr = System.err; - - @Before - public void setUp() throws Exception { - final ResourceConfig rc = new ResourceConfig(TestRESTClientEndpoint.class); - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); - - while (!server.isStarted()) { - ThreadUtilities.sleep(50); - } - } - - @After - public void tearDown() throws Exception { - server.shutdown(); - } - - @AfterClass - public static void deleteTempFiles() { - new File("src/test/resources/events/EventsOut.json").delete(); - } - - @Test - public void testRESTEventsIn() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEvent.json"}; - - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outputEventText = TextFileUtils.getTextFileAsString("src/test/resources/events/EventsOut.json"); - assertTrue(outputEventText.contains( - "04\",\n" + " \"version\": \"0.0.1\",\n" + " \"nameSpace\": \"org.onap.policy.apex.sample.events\"")); - } - - @Test - public void testFileEmptyEvents() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEmptyEvents.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "received an empty event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\"")); - } - - @Test - public void testFileEventsNoURL() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventNoURL.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains(" no URL has been set for event sending on REST client")); - } - - @Test - public void testFileEventsBadURL() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadURL.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404")); - } - - @Test - public void testFileEventsBadHTTPMethod() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "specified HTTP method of \"POST\" is invalid, only HTTP method \"GET\" is supported for event reception on REST client consumer")); - } - - @Test - public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadResponse.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" failed with status code 400 and message \"\"")); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestRESTClientEndpoint.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestRESTClientEndpoint.java deleted file mode 100644 index 79634ebcb..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestRESTClientEndpoint.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Map; -import java.util.Random; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; - -import com.google.gson.Gson; - - -@Path("/apex") -public class TestRESTClientEndpoint { - - private static int postMessagesReceived = 0; - private static int putMessagesReceived = 0; - private static int statMessagesReceived = 0; - private static int getMessagesReceived = 0; - - @Path("/event/Stats") - @GET - public Response serviceGetStats() { - statMessagesReceived++; - return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } - - @Path("/event/GetEvent") - @GET - public Response serviceGetEvent() { - final Random rand = new Random(); - final int nextMatchCase = rand.nextInt(4); - final String nextEventName = "Event0" + rand.nextInt(2) + "00"; - - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" - + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + getMessagesReceived - + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" - + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() - + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; - - getMessagesReceived++; - - return Response.status(200).entity(eventString).build(); - } - - @Path("/event/GetEmptyEvent") - @GET - public Response serviceGetEmptyEvent() { - return Response.status(200).build(); - } - - @Path("/event/GetEventBadResponse") - @GET - public Response serviceGetEventBadResponse() { - return Response.status(400).build(); - } - - @Path("/event/PostEvent") - @POST - public Response servicePostRequest(final String jsonString) { - postMessagesReceived++; - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(jsonString, Map.class); - assertTrue(jsonMap.containsKey("name")); - assertEquals("0.0.1", jsonMap.get("version")); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Act", jsonMap.get("source")); - assertEquals("Outside", jsonMap.get("target")); - - return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } - - @Path("/event/PostEventBadResponse") - @POST - public Response servicePostRequestBadResponse(final String jsonString) { - return Response.status(400).build(); - } - - @Path("/event/PutEvent") - @PUT - public Response servicePutRequest(final String jsonString) { - putMessagesReceived++; - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(jsonString, Map.class); - assertTrue(jsonMap.containsKey("name")); - assertEquals("0.0.1", jsonMap.get("version")); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Act", jsonMap.get("source")); - assertEquals("Outside", jsonMap.get("target")); - - return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServer.java deleted file mode 100644 index 15928b3c7..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServer.java +++ /dev/null @@ -1,343 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restserver; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.Map; -import java.util.Random; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - -import com.google.gson.Gson; - - -public class TestRESTServer { - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - - private final PrintStream stdout = System.out; - private final PrintStream stderr = System.err; - - private static int eventsSent = 0; - - @Test - public void testRESTServerPut() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEvent.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - for (int i = 0; i < 20; i++) { - final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); - } - - apexMain.shutdown(); - } - - @Test - public void testRESTServerPost() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEvent.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - for (int i = 0; i < 20; i++) { - final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").post(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); - } - - apexMain.shutdown(); - } - - @Test - public void testRESTServerGetStatus() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEvent.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - // trigger 10 POST & PUT events - for (int i = 0; i < 10; i++) { - final Response postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").post(Entity.json(getEvent())); - final Response putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(getEvent())); - assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus()); - assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus()); - } - - final Response statResponse = - client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get(); - - assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus()); - final String responseString = statResponse.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - assertEquals("[FirstConsumer]", jsonMap.get("INPUTS")); - assertEquals(1.0, jsonMap.get("STAT")); - assertEquals(10.0, jsonMap.get("POST")); - assertEquals(10.0, jsonMap.get("PUT")); - - apexMain.shutdown(); - } - - @Test - public void testRESTServerMultiInputs() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventMultiIn.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - for (int i = 0; i < 20; i++) { - final Response firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").post(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus()); - final String firstResponseString = firstResponse.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map firstJsonMap = new Gson().fromJson(firstResponseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan")); - - final Response secondResponse = client.target("http://localhost:23324/apex/SecondConsumer/EventIn") - .request("application/json").post(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus()); - final String secondResponseString = secondResponse.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map secondJsonMap = new Gson().fromJson(secondResponseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan")); - } - - apexMain.shutdown(); - } - - @Test - public void testRESTServerProducerStandalone() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString - .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer")); - } - - @Test - public void testRESTServerProducerHost() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains(" host is specified only in standalone mode")); - } - - @Test - public void testRESTServerProducerPort() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains(" port is specified only in standalone mode")); - } - - @Test - public void testRESTServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "the parameters \"host\" and \"port\" must be defined for REST Server consumer (FirstConsumer) in standalone mode")); - } - - @Test - public void testRESTServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "the parameters \"host\" and \"port\" must be defined for REST Server consumer (FirstConsumer) in standalone mode")); - } - - @Test - public void testRESTServerProducerNotSync() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "REST Server producer (FirstProducer) must run in synchronous mode with a REST Server consumer")); - } - - @Test - public void testRESTServerConsumerNotSync() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined with the same peered mode")); - } - - @Test - public void testRESTServerDivideByZero() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventDivideByZero.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - for (int i = 0; i < 20; i++) { - final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); - assertTrue(((String) jsonMap.get("exceptionMessage")).contains("caused by: / by zero")); - } - - apexMain.shutdown(); - } - - private String getEvent() { - final Random rand = new Random(); - final int nextMatchCase = rand.nextInt(4); - final String nextEventName = "Event0" + rand.nextInt(2) + "00"; - - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" - + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n" - + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" - + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() - + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; - - return eventString; - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServerVPNContext.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServerVPNContext.java deleted file mode 100644 index cb52dd50b..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServerVPNContext.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restserver; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Response; - -import org.junit.Ignore; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - - -public class TestRESTServerVPNContext { - private static int eventsSent = 0; - - @Ignore - @Test - public void testRESTServerPut() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventContextJava.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(setupLinkContext("L09", true))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupLinkContext("L10", true))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("A", "L09 L10", 300, 50))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("B", "L09 L10", 300, 299))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("C", "L09 L10", 300, 300))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("D", "L09 L10", 300, 400))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - ThreadUtilities.sleep(100000); - - apexMain.shutdown(); - } - - @Ignore - @Test - public void testRESTServerPutAvro() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventContextAvro.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(setupLinkContext("L09", true))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupLinkContext("L10", true))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("A", "L09 L10", 300, 50))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("B", "L09 L10", 300, 299))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("C", "L09 L10", 300, 300))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("D", "L09 L10", 300, 400))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - ThreadUtilities.sleep(100000); - - apexMain.shutdown(); - } - - private String setupLinkContext(final String link, final Boolean isUp) { - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.domains.vpn.events\",\n" - + "\"name\": \"VPNLinkCtxtTriggerEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" - + eventsSent++ + "\",\n" + "\"target\": \"apex\",\n" + "\"Link\": \"" + link + "\",\n" + "\"LinkUp\": " - + isUp + "\n" + "}"; - - return eventString; - } - - private String setupCustomerContext(final String customerName, final String linkList, final int slaDT, - final int ytdDT) { - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.domains.vpn.events\",\n" - + "\"name\": \"VPNCustomerCtxtTriggerEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" - + eventsSent++ + "\",\n" + "\"target\": \"apex\",\n" + "\"CustomerName\": \"" + customerName + "\",\n" - + "\"LinkList\": \"" + linkList + "\",\n" + "\"SlaDT\": \"" + slaDT + "\",\n" + "\"YtdDT\": " + ytdDT - + "\n" + "}"; - - return eventString; - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/Foo.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/Foo.java deleted file mode 100644 index da075b6a2..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/Foo.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.sampletypes; - -public class Foo { - private String bar; - - public String getBar() { - return bar; - } - - public void setBar(final String bar) { - this.bar = bar; - } - - public Foo(final String bar) { - this(); - this.bar = bar; - } - - public Foo() { - super(); - } - - @Override - public String toString() { - return "Foo [bar=(String)\"" + bar + "\"]"; - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/FooMap.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/FooMap.java deleted file mode 100644 index 9adaf6dae..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/FooMap.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.sampletypes; - -import java.util.LinkedHashMap; -import java.util.Map; - -public class FooMap extends LinkedHashMap { - private static final long serialVersionUID = -7125986379378753022L; - - public FooMap() { - super(); - } - - public FooMap(final int initialCapacity, final float loadFactor, final boolean accessOrder) { - super(initialCapacity, loadFactor, accessOrder); - } - - public FooMap(final int initialCapacity, final float loadFactor) { - super(initialCapacity, loadFactor); - } - - public FooMap(final int initialCapacity) { - super(initialCapacity); - } - - public FooMap(final Map m) { - super(m); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsClient.java deleted file mode 100644 index 52e896438..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsClient.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestWs2WsClient { - private static final long MAX_TEST_LENGTH = 10000; - - private static final int EVENT_COUNT = 100; - private static final int EVENT_INTERVAL = 20; - - @Test - public void testJsonWSEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Ws2WsClientJsonEvent.json"}; - testWSEvents(args, false); - } - - @Test - public void testXMLWSEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Ws2WsClientXMLEvent.json"}; - testWSEvents(args, true); - } - - private void testWSEvents(final String[] args, final Boolean xmlEvents) throws MessagingException, ApexException { - final WebSocketEventSubscriberServer subServer = new WebSocketEventSubscriberServer(42453); - final WebSocketEventProducerServer prodServer = - new WebSocketEventProducerServer(42451, EVENT_COUNT, xmlEvents, EVENT_INTERVAL); - - final ApexMain apexMain = new ApexMain(args); - - prodServer.sendEvents(); - - final long testStartTime = System.currentTimeMillis(); - - while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH - && subServer.getEventsReceivedCount() < EVENT_COUNT) { - ThreadUtilities.sleep(EVENT_INTERVAL); - } - - assertEquals(prodServer.getEventsSentCount(), subServer.getEventsReceivedCount()); - - apexMain.shutdown(); - prodServer.shutdown(); - subServer.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsServer.java deleted file mode 100644 index 86f6ee123..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsServer.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestWs2WsServer { - private static final long MAX_TEST_LENGTH = 10000; - - private static final int EVENT_COUNT = 100; - private static final int EVENT_INTERVAL = 20; - - @Test - public void testJsonWSEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Ws2WsServerJsonEvent.json"}; - testWSEvents(args, false); - } - - @Test - public void testXMLWSEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Ws2WsServerXMLEvent.json"}; - testWSEvents(args, true); - } - - public void testWSEvents(final String[] args, final boolean xmlEvents) throws MessagingException, ApexException { - final ApexMain apexMain = new ApexMain(args); - - final WebSocketEventSubscriberClient subClient = new WebSocketEventSubscriberClient("localhost", 42452); - final WebSocketEventProducerClient prodClient = - new WebSocketEventProducerClient("localhost", 42450, EVENT_COUNT, xmlEvents, EVENT_INTERVAL); - - prodClient.sendEvents(); - - final long testStartTime = System.currentTimeMillis(); - - while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH - && subClient.getEventsReceivedCount() < EVENT_COUNT) { - ThreadUtilities.sleep(EVENT_INTERVAL); - } - - assertEquals(subClient.getEventsReceivedCount(), prodClient.getEventsSentCount()); - - prodClient.shutdown(); - subClient.shutdown(); - apexMain.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerClient.java deleted file mode 100644 index fd78ba5c0..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerClient.java +++ /dev/null @@ -1,176 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import org.onap.policy.apex.apps.uservice.test.adapt.events.EventGenerator; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageClient; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -/** - * The Class WebSocketEventProducerClient. - */ -public class WebSocketEventProducerClient implements WsStringMessageListener { - private final String host; - private final int port; - private final int eventCount; - private final boolean xmlEvents; - private final long eventInterval; - private long eventsSentCount = 0; - - WsStringMessageClient client; - - /** - * Instantiates a new web socket event producer client. - * - * @param host the host - * @param port the port - * @param eventCount the event count - * @param xmlEvents the xml events - * @param eventInterval the event interval - * @throws MessagingException the messaging exception - */ - public WebSocketEventProducerClient(final String host, final int port, final int eventCount, - final boolean xmlEvents, final long eventInterval) throws MessagingException { - this.host = host; - this.port = port; - this.eventCount = eventCount; - this.xmlEvents = xmlEvents; - this.eventInterval = eventInterval; - - client = new WsStringMessageClient(host, port); - client.start(this); - - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": host " + host + ", port " + port - + ", event count " + eventCount + ", xmlEvents " + xmlEvents); - } - - /** - * Send events. - */ - public void sendEvents() { - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": sending events on host " + host - + ", port " + port + ", event count " + eventCount + ", xmlEvents " + xmlEvents); - - for (int i = 0; i < eventCount; i++) { - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": waiting " + eventInterval - + " milliseconds before sending next event"); - ThreadUtilities.sleep(eventInterval); - - String eventString = null; - if (xmlEvents) { - eventString = EventGenerator.xmlEvent(); - } else { - eventString = EventGenerator.jsonEvent(); - } - client.sendString(eventString); - eventsSentCount++; - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": host " + host + ", port " - + port + ", sent event " + eventString); - } - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": completed"); - } - - /** - * Gets the events sent count. - * - * @return the events sent count - */ - public long getEventsSentCount() { - return eventsSentCount; - } - - /** - * Shutdown. - */ - public void shutdown() { - client.stop(); - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": stopped"); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# - * receiveString(java.lang.String) - */ - @Override - public void receiveString(final String eventString) { - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": host " + host + ", port " + port - + ", received event " + eventString); - } - - /** - * The main method. - * - * @param args the arguments - * @throws MessagingException the messaging exception - */ - public static void main(final String[] args) throws MessagingException { - if (args.length != 5) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - return; - } - - int port = 0; - try { - port = Integer.parseInt(args[1]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[2]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - long eventInterval = 0; - try { - eventInterval = Long.parseLong(args[4]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - boolean xmlEvents = false; - if (args[3].equalsIgnoreCase("XML")) { - xmlEvents = true; - } else if (!args[3].equalsIgnoreCase("JSON")) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - return; - } - - final WebSocketEventProducerClient client = - new WebSocketEventProducerClient(args[0], port, eventCount, xmlEvents, eventInterval); - - client.sendEvents(); - client.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerServer.java deleted file mode 100644 index 53aa0cab4..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerServer.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import org.onap.policy.apex.apps.uservice.test.adapt.events.EventGenerator; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageServer; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -/** - * The Class WebSocketEventProducerServer. - */ -public class WebSocketEventProducerServer implements WsStringMessageListener { - private final int port; - private final int eventCount; - private final boolean xmlEvents; - private final long eventInterval; - private long eventsSentCount = 0; - - WsStringMessageServer server; - - /** - * Instantiates a new web socket event producer server. - * - * @param port the port - * @param eventCount the event count - * @param xmlEvents the xml events - * @param eventInterval the event interval - * @throws MessagingException the messaging exception - */ - public WebSocketEventProducerServer(final int port, final int eventCount, final boolean xmlEvents, - final long eventInterval) throws MessagingException { - this.port = port; - this.eventCount = eventCount; - this.xmlEvents = xmlEvents; - this.eventInterval = eventInterval; - - server = new WsStringMessageServer(port); - server.start(this); - - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port + ", event count " - + eventCount + ", xmlEvents " + xmlEvents); - } - - /** - * Send events. - */ - public void sendEvents() { - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": sending events on port " + port - + ", event count " + eventCount + ", xmlEvents " + xmlEvents); - - for (int i = 0; i < eventCount; i++) { - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": waiting " + eventInterval - + " milliseconds before sending next event"); - ThreadUtilities.sleep(eventInterval); - - String eventString = null; - if (xmlEvents) { - eventString = EventGenerator.xmlEvent(); - } else { - eventString = EventGenerator.jsonEvent(); - } - server.sendString(eventString); - eventsSentCount++; - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port - + ", sent event " + eventString); - } - - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": event sending completed"); - } - - /** - * Gets the events sent count. - * - * @return the events sent count - */ - public long getEventsSentCount() { - return eventsSentCount; - } - - /** - * Shutdown. - */ - public void shutdown() { - server.stop(); - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": stopped"); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# - * receiveString(java.lang.String) - */ - @Override - public void receiveString(final String eventString) { - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port - + ", received event " + eventString); - } - - /** - * The main method. - * - * @param args the arguments - * @throws MessagingException the messaging exception - */ - public static void main(final String[] args) throws MessagingException { - if (args.length != 4) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); - return; - } - - int port = 0; - try { - port = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[1]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - long eventInterval = 0; - try { - eventInterval = Long.parseLong(args[3]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - boolean xmlEvents = false; - if (args[2].equalsIgnoreCase("XML")) { - xmlEvents = true; - } else if (!args[2].equalsIgnoreCase("JSON")) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON startDelay eventInterval"); - return; - } - - final WebSocketEventProducerServer server = - new WebSocketEventProducerServer(port, eventCount, xmlEvents, eventInterval); - - server.sendEvents(); - server.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberClient.java deleted file mode 100644 index 27a34a92e..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberClient.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageClient; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; - -/** - * The Class WebSocketEventSubscriberClient. - */ -public class WebSocketEventSubscriberClient implements WsStringMessageListener { - private final int port; - private long eventsReceivedCount = 0; - - private final WsStringMessageClient client; - - /** - * Instantiates a new web socket event subscriber client. - * - * @param host the host - * @param port the port - * @throws MessagingException the messaging exception - */ - public WebSocketEventSubscriberClient(final String host, final int port) throws MessagingException { - this.port = port; - - client = new WsStringMessageClient(host, port); - client.start(this); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# - * receiveString(java.lang.String) - */ - @Override - public void receiveString(final String eventString) { - System.out.println(WebSocketEventSubscriberClient.class.getCanonicalName() + ": port " + port - + ", received event " + eventString); - eventsReceivedCount++; - } - - /** - * Gets the events received count. - * - * @return the events received count - */ - public long getEventsReceivedCount() { - return eventsReceivedCount; - } - - /** - * Shutdown. - */ - public void shutdown() { - client.stop(); - System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": stopped"); - } - - /** - * The main method. - * - * @param args the arguments - * @throws MessagingException the messaging exception - */ - public static void main(final String[] args) throws MessagingException { - if (args.length != 2) { - System.err.println("usage WebSocketEventSubscriberClient host port"); - return; - } - - int port = 0; - try { - port = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventSubscriberClient port"); - e.printStackTrace(); - return; - } - - new WebSocketEventSubscriberClient(args[0], port); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberServer.java deleted file mode 100644 index 854a0e410..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberServer.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageServer; - -/** - * The Class WebSocketEventSubscriberServer. - */ -public class WebSocketEventSubscriberServer implements WsStringMessageListener { - private final int port; - private long eventsReceivedCount = 0; - - private final WsStringMessageServer server; - - /** - * Instantiates a new web socket event subscriber server. - * - * @param port the port - * @throws MessagingException the messaging exception - */ - public WebSocketEventSubscriberServer(final int port) throws MessagingException { - this.port = port; - - server = new WsStringMessageServer(port); - server.start(this); - - System.out.println( - WebSocketEventSubscriberServer.class.getCanonicalName() + ": port " + port + ", waiting for events"); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# - * receiveString(java.lang.String) - */ - @Override - public void receiveString(final String eventString) { - System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": port " + port - + ", received event " + eventString); - eventsReceivedCount++; - } - - /** - * Gets the events received count. - * - * @return the events received count - */ - public long getEventsReceivedCount() { - return eventsReceivedCount; - } - - /** - * Shutdown. - */ - public void shutdown() { - server.stop(); - System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": stopped"); - } - - /** - * The main method. - * - * @param args the arguments - * @throws MessagingException the messaging exception - */ - public static void main(final String[] args) throws MessagingException { - if (args.length != 1) { - System.err.println("usage WebSocketEventSubscriberClient port"); - return; - } - - int port = 0; - try { - port = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventSubscriberClient port"); - e.printStackTrace(); - return; - } - - new WebSocketEventSubscriberServer(port); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/context/EventAlbumContextTest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/context/EventAlbumContextTest.java deleted file mode 100644 index 8f9aa6cee..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/context/EventAlbumContextTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.context; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; -import org.onap.policy.common.utils.resources.ResourceUtils; - -public class EventAlbumContextTest { - private File tempCommandFile; - private File tempLogFile; - private File tempModelFile; - private String eventContextString; - private String configFile; - private String outputFile; - private String compareFile; - - @Rule - public TemporaryFolder tempTestDir = new TemporaryFolder(); - - @Test - public void testJavaEventAlbumContextTest() throws IOException, ApexException { - tempCommandFile = tempTestDir.newFile("TestPolicyJavaEventContext.apex"); - tempLogFile = tempTestDir.newFile("TestPolicyJavaEventContext.log"); - tempModelFile = tempTestDir.newFile("TestPolicyJavaEventContext.json"); - - eventContextString = ResourceUtils.getResourceAsString("examples/scripts/TestPolicyJavaEventContext.apex"); - - configFile = "src/test/resources/prodcons/Context_JavaEventAlbum_file2file.json"; - outputFile = "src/test/resources/events/Context_JavaEventAlbum_EventOut.json"; - compareFile = "src/test/resources/events/Context_JavaEventAlbum_EventOutCompare.json"; - - testEventAlbumContextTest(); - } - - @Test - public void testAvroEventAlbumContextTest() throws IOException, ApexException { - tempCommandFile = tempTestDir.newFile("TestPolicyAvroEventContext.apex"); - tempLogFile = tempTestDir.newFile("TestPolicyAvroEventContext.log"); - tempModelFile = tempTestDir.newFile("TestPolicyAvroEventContext.json"); - - eventContextString = ResourceUtils.getResourceAsString("examples/scripts/TestPolicyAvroEventContext.apex"); - - configFile = "src/test/resources/prodcons/Context_AvroEventAlbum_file2file.json"; - outputFile = "src/test/resources/events/Context_AvroEventAlbum_EventOut.json"; - compareFile = "src/test/resources/events/Context_AvroEventAlbum_EventOutCompare.json"; - - testEventAlbumContextTest(); - } - - private void testEventAlbumContextTest() throws IOException, ApexException { - TextFileUtils.putStringAsFile(eventContextString, tempCommandFile); - - final String[] cliArgs = new String[] { "-c", tempCommandFile.getCanonicalPath(), "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath() }; - - new ApexCommandLineEditorMain(cliArgs); - - final String[] args = new String[] { "-m", tempModelFile.getAbsolutePath(), "-c", configFile }; - final ApexMain apexMain = new ApexMain(args); - - // The output event will be in this file - final File outputEventFile = new File(outputFile); - String receivedApexOutputString = ""; - for (int tenthsOfSecondsToWait = 100; tenthsOfSecondsToWait > 0; tenthsOfSecondsToWait--) { - if (outputEventFile.exists() && outputEventFile.length() > 0) { - // The output event is in this file - receivedApexOutputString = TextFileUtils.getTextFileAsString(outputEventFile.getCanonicalPath()) - .replaceAll("\\s+", ""); - break; - } - - ThreadUtilities.sleep(100); - } - - // Shut down Apex - apexMain.shutdown(); - - assertTrue("Test failed, the output event file was not created", outputEventFile.exists()); - outputEventFile.delete(); - - assertTrue("Test failed, the output event file was empty", receivedApexOutputString.length() > 0); - - // We compare the output to what we expect to get - final String expectedFileContent = TextFileUtils - .getTextFileAsString(compareFile); - final String outputEventCompareString = expectedFileContent.replaceAll("\\s+", ""); - - assertEquals(outputEventCompareString, receivedApexOutputString); - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngDepMessagingTest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngDepMessagingTest.java deleted file mode 100644 index 187a2a316..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngDepMessagingTest.java +++ /dev/null @@ -1,219 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.engdep; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.deployment.BatchDeployer; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.service.ModelService; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -// CHECKSTYLE:OFF: checkstyle:magicNumber - -/** - * The Class EngDepMessagingTest. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EngDepMessagingTest { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngDepMessagingTest.class); - - private static final long MAX_START_WAIT = 10000; // 10 sec - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineServiceParameters engineServiceParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineServiceParameters = new EngineServiceParameters(); - engineServiceParameters.setName("EngDepMessagingTest"); - engineServiceParameters.setVersion("0.0.1"); - engineServiceParameters.setDeploymentPort(58820); - engineServiceParameters.setInstanceCount(3); - engineServiceParameters.setId(100); - engineServiceParameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - - ParameterService.register(engineServiceParameters); - ParameterService.register(engineServiceParameters.getEngineParameters()); - } - - @After - public void afterTest() { - ParameterService.deregister(engineServiceParameters); - ParameterService.deregister(engineServiceParameters.getEngineParameters()); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test EngDep messaging. - * - * @throws URISyntaxException the URI syntax exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexException the apex exception - */ - @Test - public void testEngDepMessaging() throws URISyntaxException, IOException, ApexException { - LOGGER.debug("engine<-->deployment messaging test starting . . ."); - - ModelService.clear(); - - final EngineTestServer server = new EngineTestServer(engineServiceParameters); - assertNotNull(server); - - final Thread serverThread = new Thread(server); - serverThread.start(); - final long starttime = System.currentTimeMillis(); - while (server.isStarting() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { - ThreadUtilities.sleep(100); - } - if (server.isStarting()) { - fail("Test server failed to start after " + MAX_START_WAIT + " ms"); - } - - final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - - final BatchDeployer deployer1 = new BatchDeployer("localhost", 58820); - assertNotNull(deployer1); - - deployer1.init(); - deployer1.deployModel(apexPolicyModel, false, false); - deployer1.stopEngines(); - deployer1.startEngines(); - deployer1.close(); - - // Send events - final Date testStartTime = new Date(); - final Map eventDataMap = new HashMap<>(); - eventDataMap.put("TestSlogan", "This is a test slogan"); - eventDataMap.put("TestMatchCase", (byte) 123); - eventDataMap.put("TestTimestamp", testStartTime.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - final ApexEvent event0 = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "apex", "test"); - event0.putAll(eventDataMap); - server.sendEvent(event0); - - final ApexEvent event1 = - new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "apex", "test"); - event1.putAll(eventDataMap); - server.sendEvent(event1); - - // Wait for results - while (server.getTotalActionEventsReceived() < 2) { - ThreadUtilities.sleep(100); - } - ThreadUtilities.sleep(500); - - assertEquals(2, server.getTotalActionEventsReceived()); - - deployer1.init(); - deployer1.stopEngines(); - deployer1.close(); - - // Test re-initialization of model - final BatchDeployer deployer2 = new BatchDeployer("localhost", 58820); - assertNotNull(deployer2); - - deployer2.init(); - deployer2.deployModel(apexPolicyModel, true, true); - deployer2.stopEngines(); - deployer2.startEngines(); - deployer2.close(); - - server.sendEvent(event0); - server.sendEvent(event1); - - // Wait for results - while (server.getTotalActionEventsReceived() < 4) { - ThreadUtilities.sleep(100); - } - ThreadUtilities.sleep(500); - - assertEquals(4, server.getTotalActionEventsReceived()); - - deployer2.init(); - deployer2.stopEngines(); - deployer2.close(); - - server.stopServer(); - LOGGER.debug("engine<-->deployment messaging test finished"); - } - - /** - * Tear down. - * - * @throws Exception the exception - */ - @After - public void tearDown() throws Exception {} -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngineTestServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngineTestServer.java deleted file mode 100644 index 1a8b1d364..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngineTestServer.java +++ /dev/null @@ -1,269 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.engdep; - -import java.util.Date; - -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.service.engine.engdep.EngDepMessagingService; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.runtime.ApexEventListener; -import org.onap.policy.apex.service.engine.runtime.EngineService; -import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; -import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class EngineTestServer is a test Apex service used to test the performance of Apex engines. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EngineTestServer implements Runnable, EngineServiceEventInterface { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineTestServer.class); - - private static final int TEST_SERVER_WAIT_TIME = 200; - - // The engine service for sending events to the Apex engines and the EngDEp service for engine - // administration - private EngineService engineService = null; - private EngDepMessagingService messageService = null; - - // The inner class used to receive and process events - private TestApexListener testApexListener = null; - - // Status flags - private boolean starting = true; - private boolean interrupted = false; - - // Parameters for the test - private final EngineServiceParameters parameters; - - // Apex performance statistics - private Date statsStartDate = null; - private long actionEventsReceivedCount = 0; - private long accumulatedExecutionTime = 0; - private long totalActionEventsReceivedCount = 0; - - private ApexEvent lastEventReceived = null; - - /** - * Instantiates a new engine test server to test Apex performance. - * - * @param parameters the parameters - */ - public EngineTestServer(final EngineServiceParameters parameters) { - this.parameters = parameters; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - LOGGER.debug("engine<-->deployment test server starting . . ."); - - // Set the name of the test server thread - Thread.currentThread().setName(EngineTestServer.class.getName()); - - try { - // Create the engine service and set the listener for events emitted by the Apex service - engineService = EngineServiceImpl.create(parameters); - testApexListener = new TestApexListener(); - engineService.registerActionListener("testApexListener", testApexListener); - - // Create the EngDep messaging service and start it - messageService = new EngDepMessagingService(engineService, parameters.getDeploymentPort()); - messageService.start(); - - // Record the start date for statistics - statsStartDate = new Date(); - } catch (final Exception e) { - LOGGER.error("engine<-->deployment test server exception", e); - e.printStackTrace(); - return; - } - LOGGER.debug("engine<-->deployment test server started"); - - starting = false; - - while (!interrupted) { - if (!ThreadUtilities.sleep(TEST_SERVER_WAIT_TIME)) { - interrupted = true; - } - } - } - - /** - * Stop the test server. - */ - public void stopServer() { - LOGGER.debug("engine<-->deployment test server stopping . . ."); - - interrupted = true; - messageService.stop(); - - LOGGER.debug("engine<-->deployment test server stopped"); - } - - /** - * Checks if the test server is interrupted. - * - * @return true, if is interrupted - */ - public boolean isInterrupted() { - return interrupted; - } - - /** - * Gets the total action events received. - * - * @return the total action events received - */ - public long getTotalActionEventsReceived() { - return totalActionEventsReceivedCount; - } - - /** - * Gets the last action events received. - * - * @return the last action event received - */ - public ApexEvent getLastActionEvent() { - return lastEventReceived; - } - - /** - * Gets the Apex statistics and resets them. - * - * @return the statistics - */ - public long[] getAndResetStats() { - // Check if we have statistics - if (statsStartDate == null || actionEventsReceivedCount == 0) { - return null; - } - - // Calculate, save, and reset the statistics - final long[] stats = new long[2]; - synchronized (statsStartDate) { - final long averageExecutionTime = accumulatedExecutionTime / actionEventsReceivedCount; - final long measuringTime = new Date().getTime() - statsStartDate.getTime(); - final long transactionsPerMillisecond = actionEventsReceivedCount / measuringTime; - stats[0] = averageExecutionTime; - stats[1] = transactionsPerMillisecond; - statsStartDate = new Date(); - - actionEventsReceivedCount = 0; - accumulatedExecutionTime = 0; - } - - // Return the statistics - return stats; - } - - /** - * Checks if the test server is starting. - * - * @return true, if the server is starting - */ - public boolean isStarting() { - return starting; - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface#sendEvent(org.onap. - * policy.apex.service.engine.event.ApexEvent) - */ - @Override - public void sendEvent(final ApexEvent event) { - // Send the event onto the service being tested - engineService.getEngineServiceEventInterface().sendEvent(event); - } - - /** - * The listener interface for receiving testApex events. The class that is interested in - * processing a testApex event implements this interface, and the object created with that class - * is registered with a component using the component's {@code addTestApexListener} method. When - * the testApex event occurs, that object's appropriate method is invoked. - * - * This class listens for events from the Apex engine - * - * @see TestApexEvent - */ - private final class TestApexListener implements ApexEventListener { - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy - * .apex.service.engine.event.ApexEvent) - */ - @Override - public synchronized void onApexEvent(final ApexEvent apexEvent) { - LOGGER.debug("result is:" + apexEvent); - - // Check the result event is correct - checkResult(apexEvent); - - // Calculate the performance of the Apex engine service on this policy execution run and - // accumulate the total statistics - final Date testStartTime = new Date((Long) apexEvent.get("TestTimestamp")); - final Date testEndTime = new Date(); - final long testTime = testEndTime.getTime() - testStartTime.getTime(); - LOGGER.debug("policy execution time: " + testTime + "ms"); - synchronized (statsStartDate) { - actionEventsReceivedCount++; - totalActionEventsReceivedCount++; - accumulatedExecutionTime += testTime; - } - lastEventReceived = apexEvent; - } - - /** - * Check that a reply event from the Apex engine is valid. - * - * @param result the result event from the Apex engine - */ - private void checkResult(final ApexEvent result) { - assert result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"); - - // CHECKSTYLE:OFF: checkstyle:magicNumber - assert result.get("TestSlogan").equals("This is a test slogan"); - assert result.get("TestMatchCase").equals(new Byte((byte) 123)); - assert result.get("TestTemperature").equals(34.5445667); - assert ((byte) result.get("TestMatchCaseSelected") >= 0 && (byte) result.get("TestMatchCaseSelected") <= 3); - assert ((byte) result.get("TestEstablishCaseSelected") >= 0 - && (byte) result.get("TestEstablishCaseSelected") <= 3); - assert ((byte) result.get("TestDecideCaseSelected") >= 0 - && (byte) result.get("TestDecideCaseSelected") <= 3); - assert ((byte) result.get("TestActCaseSelected") >= 0 && (byte) result.get("TestActCaseSelected") <= 3); - // CHECKSTYLE:ON: checkstyle:magicNumber - } - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/events/EventGenerator.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/events/EventGenerator.java new file mode 100644 index 000000000..6a585d7c5 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/events/EventGenerator.java @@ -0,0 +1,610 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.events; + +import java.util.Random; + +/** + * The Class EventGenerator. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EventGenerator { + private static int nextEventNo = 0; + + /** + * Xml events. + * + * @param eventCount the event count + * @return the string + */ + public static String xmlEvents(final int eventCount) { + final StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < eventCount; i++) { + if (i > 0) { + builder.append("\n"); + } + builder.append(xmlEvent()); + } + + return builder.toString(); + } + + /** + * Json events. + * + * @param eventCount the event count + * @return the string + */ + public static String jsonEvents(final int eventCount) { + final StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < eventCount; i++) { + if (i > 0) { + builder.append("\n"); + } + builder.append(jsonEvent()); + } + + return builder.toString(); + } + + /** + * Xml event. + * + * @return the string + */ + public static String xmlEvent() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("\n"); + builder.append("\n"); + + builder.append(" " + eventName + "\n"); + builder.append(" 0.0.1\n"); + builder.append(" org.onap.policy.apex.sample.events\n"); + builder.append(" test\n"); + builder.append(" apex\n"); + builder.append(" \n"); + builder.append(" TestSlogan\n"); + builder.append(" Test slogan for External Event" + (nextEventNo++) + "\n"); + builder.append(" \n"); + builder.append(" \n"); + builder.append(" TestMatchCase\n"); + builder.append(" " + nextMatchCase + "\n"); + builder.append(" \n"); + builder.append(" \n"); + builder.append(" TestTimestamp\n"); + builder.append(" " + System.currentTimeMillis() + "\n"); + builder.append(" \n"); + builder.append(" \n"); + builder.append(" TestTemperature\n"); + builder.append(" " + nextTestTemperature + "\n"); + builder.append(" \n"); + builder.append(""); + + return builder.toString(); + } + + /** + * Json event. + * + * @return the string + */ + public static String jsonEvent() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no name. + * + * @return the string + */ + public static String jsonEventNoName() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"namez\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad name. + * + * @return the string + */ + public static String jsonEventBadName() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"%%%%\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no ex name. + * + * @return the string + */ + public static String jsonEventNoExName() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"I_DONT_EXIST\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no version. + * + * @return the string + */ + public static String jsonEventNoVersion() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"versiion\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad version. + * + * @return the string + */ + public static String jsonEventBadVersion() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"#####\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no ex version. + * + * @return the string + */ + public static String jsonEventNoExVersion() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"Event0000\",\n"); + builder.append(" \"version\": \"1.2.3\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no namespace. + * + * @return the string + */ + public static String jsonEventNoNamespace() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpacee\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad namespace. + * + * @return the string + */ + public static String jsonEventBadNamespace() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"hello.&&&&\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no ex namespace. + * + * @return the string + */ + public static String jsonEventNoExNamespace() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"pie.in.the.sky\",\n"); + builder.append(" \"name\": \"Event0000\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no source. + * + * @return the string + */ + public static String jsonEventNoSource() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"sourcee\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad source. + * + * @return the string + */ + public static String jsonEventBadSource() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"%!@**@!\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no target. + * + * @return the string + */ + public static String jsonEventNoTarget() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"targett\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad target. + * + * @return the string + */ + public static String jsonEventBadTarget() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"KNIO(*S)A(S)D\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event missing fields. + * + * @return the string + */ + public static String jsonEventMissingFields() { + final StringBuilder builder = new StringBuilder(); + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"Event0000\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\"\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event null fields. + * + * @return the string + */ + public static String jsonEventNullFields() { + final StringBuilder builder = new StringBuilder(); + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"Event0000\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"Apex\",\n"); + builder.append(" \"TestSlogan\": null,\n"); + builder.append(" \"TestMatchCase\": -1,\n"); + builder.append(" \"TestTimestamp\": -1,\n"); + builder.append(" \"TestTemperature\": -1.0\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + if (args.length != 2) { + System.err.println("usage EventGenerator #events XML|JSON"); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage EventGenerator #events XML|JSON"); + e.printStackTrace(); + return; + } + + if (args[1].equalsIgnoreCase("XML")) { + System.out.println(xmlEvents(eventCount)); + } else if (args[1].equalsIgnoreCase("JSON")) { + System.out.println(jsonEvents(eventCount)); + } else { + System.err.println("usage EventGenerator #events XML|JSON"); + return; + } + } + + /** + * Gets the next event no. + * + * @return the next event no + */ + public static int getNextEventNo() { + return nextEventNo; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2File.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2File.java new file mode 100644 index 000000000..5483501b2 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2File.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.file; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +public class TestFile2File { + + @Test + public void testJsonFileEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileJsonEvent.json"}; + + testFileEvents(args, "src/test/resources/events/EventsOut.json", 48956); + } + + @Test + public void testXmlFileEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileXmlEvent.json"}; + + testFileEvents(args, "src/test/resources/events/EventsOut.xmlfile", 106739); + } + + private void testFileEvents(final String[] args, final String outFilePath, final long expectedFileSize) + throws MessagingException, ApexException, IOException { + final ApexMain apexMain = new ApexMain(args); + + final File outFile = new File(outFilePath); + + while (!outFile.exists()) { + ThreadUtilities.sleep(500); + } + + // Wait for the file to be filled + long outFileSize = 0; + while (true) { + final String fileString = TextFileUtils.getTextFileAsString(outFilePath).replaceAll("\\s+", ""); + outFileSize = fileString.length(); + if (outFileSize > 0 && outFileSize >= expectedFileSize) { + break; + } + ThreadUtilities.sleep(500); + } + + apexMain.shutdown(); + outFile.delete(); + assertEquals(outFileSize, expectedFileSize); + } +} + + diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java new file mode 100644 index 000000000..48cd6c013 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.file; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +public class TestFile2FileFiltered { + + @Test + public void testJsonFilteredFileInOutEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileFilteredInOutJsonEvent.json"}; + + final String[] outFilePaths = { + "src/test/resources/events/Events0004Out.json", + "src/test/resources/events/Events0104Out.json" + }; + + final long[] expectedFileSizes = {25949, 23007}; + + testFilteredFileEvents(args, outFilePaths, expectedFileSizes); + } + + @Test + public void testJsonFilteredFileOutEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileFilteredOutJsonEvent.json"}; + + final String[] outFilePaths = { + "src/test/resources/events/Events0004Out.json", + "src/test/resources/events/Events0104Out.json" + }; + + final long[] expectedFileSizes = {25949, 23007}; + + testFilteredFileEvents(args, outFilePaths, expectedFileSizes); + } + + @Test + public void testJsonFilteredFileInEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileFilteredInJsonEvent.json"}; + + final String[] outFilePaths = {"src/test/resources/events/Events0004Out.json"}; + + final long[] expectedFileSizes = {25949}; + + testFilteredFileEvents(args, outFilePaths, expectedFileSizes); + } + + private void testFilteredFileEvents(final String[] args, final String[] outFilePaths, + final long[] expectedFileSizes) throws MessagingException, ApexException, IOException { + final ApexMain apexMain = new ApexMain(args); + + final File outFile0 = new File(outFilePaths[0]); + + while (!outFile0.exists()) { + ThreadUtilities.sleep(500); + } + + // Wait for the file to be filled + long outFile0Size = 0; + for (int i = 0; i < 4; i++) { + final String fileString = TextFileUtils.getTextFileAsString(outFilePaths[0]).replaceAll("\\s+", ""); + outFile0Size = fileString.length(); + if (outFile0Size > 0 && outFile0Size >= expectedFileSizes[0]) { + break; + } + ThreadUtilities.sleep(500); + } + + ThreadUtilities.sleep(500); + apexMain.shutdown(); + + final long[] actualFileSizes = new long[expectedFileSizes.length]; + + for (int i = 0; i < outFilePaths.length; i++) { + final String fileString = TextFileUtils.getTextFileAsString(outFilePaths[i]).replaceAll("\\s+", ""); + actualFileSizes[i] = fileString.length(); + new File(outFilePaths[i]).delete(); + } + + for (int i = 0; i < actualFileSizes.length; i++) { + assertEquals(actualFileSizes[i], expectedFileSizes[i]); + } + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileIgnore.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileIgnore.java new file mode 100644 index 000000000..49c7a96d1 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileIgnore.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.file; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestFile2FileIgnore. + */ +public class TestFile2FileIgnore { + + // This test is used just to bring up an instance of Apex for manual testing and demonstrations + // It should always be ignored in automated testing because it holds Apex up for a very long + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + // time + public static void main(final String[] args) throws MessagingException, ApexException, IOException { + final String[] apexArgs = {"src/test/resources/prodcons/File2FileJsonEvent.json"}; + + testFileEvents(apexArgs, "src/test/resources/events/EventsOut.json", 48656); + } + + /** + * Test file events. + * + * @param args the args + * @param outFilePath the out file path + * @param expectedFileSize the expected file size + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + private static void testFileEvents(final String[] args, final String outFilePath, final long expectedFileSize) + throws MessagingException, ApexException, IOException { + final ApexMain apexMain = new ApexMain(args); + + final File outFile = new File(outFilePath); + + while (!outFile.exists()) { + ThreadUtilities.sleep(500); + } + + // Wait for the file to be filled + long outFileSize = 0; + while (true) { + final String fileString = TextFileUtils.getTextFileAsString(outFilePath).replaceAll("\\s+", ""); + outFileSize = fileString.length(); + if (outFileSize > 0 && outFileSize >= expectedFileSize) { + break; + } + ThreadUtilities.sleep(500); + } + + // Here's the long time I was talking about above! + ThreadUtilities.sleep(100000000); + + apexMain.shutdown(); + outFile.delete(); + assertEquals(outFileSize, expectedFileSize); + } +} + + diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventProducer.java new file mode 100644 index 000000000..6a7e61739 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventProducer.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.Topic; + +import org.apache.activemq.command.ActiveMQTopic; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class JmsEventProducer. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JmsEventProducer implements Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(JmsEventProducer.class); + + private final String topic; + private final int eventCount; + private final boolean sendObjects; + private final long eventInterval; + private long eventsSentCount = 0; + + private final Thread producerThread; + private boolean sendEventsFlag = false; + private boolean stopFlag = false; + private final Connection connection; + + /** + * Instantiates a new jms event producer. + * + * @param topic the topic + * @param connectionFactory the connection factory + * @param username the username + * @param password the password + * @param eventCount the event count + * @param sendObjects the send objects + * @param eventInterval the event interval + * @throws JMSException the JMS exception + */ + public JmsEventProducer(final String topic, final ConnectionFactory connectionFactory, final String username, + final String password, final int eventCount, final boolean sendObjects, final long eventInterval) + throws JMSException { + this.topic = topic; + this.eventCount = eventCount; + this.sendObjects = sendObjects; + this.eventInterval = eventInterval; + connection = connectionFactory.createConnection(username, password); + connection.start(); + + producerThread = new Thread(this); + producerThread.start(); + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + final Topic jmsTopic = new ActiveMQTopic(topic); + try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer jmsProducer = jmsSession.createProducer(jmsTopic);) { + + while (producerThread.isAlive() && !stopFlag) { + ThreadUtilities.sleep(50); + + if (sendEventsFlag) { + sendEventsToTopic(jmsSession, jmsProducer); + sendEventsFlag = false; + } + } + + } catch (final Exception e) { + throw new ApexEventRuntimeException("JMS event consumption failed", e); + } + } + + /** + * Send events. + */ + public void sendEvents() { + sendEventsFlag = true; + } + + /** + * Send events to topic. + * + * @param jmsSession the jms session + * @param jmsProducer the jms producer + * @throws JMSException the JMS exception + */ + private void sendEventsToTopic(final Session jmsSession, final MessageProducer jmsProducer) throws JMSException { + + LOGGER.info("{} : sending events to JMS server, event count {}", this.getClass().getCanonicalName(), + eventCount); + + for (int i = 0; i < eventCount; i++) { + ThreadUtilities.sleep(eventInterval); + + Message jmsMessage = null; + if (sendObjects) { + jmsMessage = jmsSession.createObjectMessage(new TestPing()); + } else { + jmsMessage = jmsSession.createTextMessage(EventGenerator.jsonEvent()); + } + jmsProducer.send(jmsMessage); + eventsSentCount++; + } + LOGGER.info("{} : completed, number of events sent", this.getClass().getCanonicalName(), eventsSentCount); + } + + /** + * Gets the events sent count. + * + * @return the events sent count + */ + public long getEventsSentCount() { + return eventsSentCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + LOGGER.info("{} : stopping", this.getClass().getCanonicalName()); + stopFlag = true; + + while (producerThread.isAlive()) { + ThreadUtilities.sleep(10); + } + LOGGER.info("{} : stopped", this.getClass().getCanonicalName()); + } + +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java new file mode 100644 index 000000000..d1af8c39a --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.ObjectMessage; +import javax.jms.Session; +import javax.jms.TextMessage; +import javax.jms.Topic; + +import org.apache.activemq.command.ActiveMQTopic; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class JmsEventSubscriber. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JmsEventSubscriber implements Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(JmsEventSubscriber.class); + + private final String topic; + private long eventsReceivedCount = 0; + + private final Thread subscriberThread; + private final Connection connection; + + + /** + * Instantiates a new jms event subscriber. + * + * @param topic the topic + * @param connectionFactory the connection factory + * @param username the username + * @param password the password + * @throws JMSException the JMS exception + */ + public JmsEventSubscriber(final String topic, final ConnectionFactory connectionFactory, final String username, + final String password) throws JMSException { + this.topic = topic; + connection = connectionFactory.createConnection(username, password); + connection.start(); + + subscriberThread = new Thread(this); + subscriberThread.start(); + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + final Topic jmsTopic = new ActiveMQTopic(topic); + try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer jmsConsumer = jmsSession.createConsumer(jmsTopic);) { + + while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) { + try { + final Message message = jmsConsumer.receive(100); + if (message == null) { + continue; + } + + if (message instanceof ObjectMessage) { + final TestPing testPing = (TestPing) ((ObjectMessage) message).getObject(); + testPing.verify(); + } else if (message instanceof TextMessage) { + ((TextMessage) message).getText(); + } else { + throw new ApexEventException("unknowm message \"" + message + "\" of type \"" + + message.getClass().getCanonicalName() + "\" received"); + } + eventsReceivedCount++; + } catch (final Exception e) { + break; + } + } + + } catch (final Exception e) { + throw new ApexEventRuntimeException("JMS event consumption failed", e); + } + + LOGGER.info("{} : event reception completed", this.getClass().getCanonicalName()); + } + + /** + * Gets the events received count. + * + * @return the events received count + */ + public long getEventsReceivedCount() { + return eventsReceivedCount; + } + + /** + * Shutdown. + * + * @throws JMSException the JMS exception + */ + public void shutdown() throws JMSException { + subscriberThread.interrupt(); + + while (subscriberThread.isAlive()) { + ThreadUtilities.sleep(10); + } + + connection.close(); + LOGGER.info("{} : stopped", this.getClass().getCanonicalName()); + } + +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestContext.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestContext.java new file mode 100644 index 000000000..b8ea0c7fe --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestContext.java @@ -0,0 +1,282 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.HOST; +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.JMS_TOPIC_APEX_IN; +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.JMS_TOPIC_APEX_OUT; +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.PORT; +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.connectionFactory; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; +import java.util.Properties; + +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.NameParser; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; + +import org.apache.activemq.command.ActiveMQTopic; +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; + +/** + * The Class TestContext. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContext implements Context { + + private Properties testProperties; + + /** + * Instantiates a new test context. + */ + public TestContext() { + try { + testProperties = new Properties(); + + final Map params = new HashMap(); + params.put("host", HOST); + params.put("port", PORT); + testProperties.put("ConnectionFactory", connectionFactory); + testProperties.put(JMS_TOPIC_APEX_IN, new ActiveMQTopic(JMS_TOPIC_APEX_IN)); + testProperties.put(JMS_TOPIC_APEX_OUT, new ActiveMQTopic(JMS_TOPIC_APEX_OUT)); + } catch (final Exception e) { + e.printStackTrace(); + throw new ApexRuntimeException("Context initiation failed", e); + } + } + + /* (non-Javadoc) + * @see javax.naming.Context#lookup(javax.naming.Name) + */ + @Override + public Object lookup(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#lookup(java.lang.String) + */ + @Override + public Object lookup(final String name) throws NamingException { + return testProperties.get(name); + } + + /* (non-Javadoc) + * @see javax.naming.Context#bind(javax.naming.Name, java.lang.Object) + */ + @Override + public void bind(final Name name, final Object obj) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#bind(java.lang.String, java.lang.Object) + */ + @Override + public void bind(final String name, final Object obj) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#rebind(javax.naming.Name, java.lang.Object) + */ + @Override + public void rebind(final Name name, final Object obj) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#rebind(java.lang.String, java.lang.Object) + */ + @Override + public void rebind(final String name, final Object obj) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#unbind(javax.naming.Name) + */ + @Override + public void unbind(final Name name) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#unbind(java.lang.String) + */ + @Override + public void unbind(final String name) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#rename(javax.naming.Name, javax.naming.Name) + */ + @Override + public void rename(final Name oldName, final Name newName) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#rename(java.lang.String, java.lang.String) + */ + @Override + public void rename(final String oldName, final String newName) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#list(javax.naming.Name) + */ + @Override + public NamingEnumeration list(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#list(java.lang.String) + */ + @Override + public NamingEnumeration list(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#listBindings(javax.naming.Name) + */ + @Override + public NamingEnumeration listBindings(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#listBindings(java.lang.String) + */ + @Override + public NamingEnumeration listBindings(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#destroySubcontext(javax.naming.Name) + */ + @Override + public void destroySubcontext(final Name name) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#destroySubcontext(java.lang.String) + */ + @Override + public void destroySubcontext(final String name) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#createSubcontext(javax.naming.Name) + */ + @Override + public Context createSubcontext(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#createSubcontext(java.lang.String) + */ + @Override + public Context createSubcontext(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#lookupLink(javax.naming.Name) + */ + @Override + public Object lookupLink(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#lookupLink(java.lang.String) + */ + @Override + public Object lookupLink(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#getNameParser(javax.naming.Name) + */ + @Override + public NameParser getNameParser(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#getNameParser(java.lang.String) + */ + @Override + public NameParser getNameParser(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#composeName(javax.naming.Name, javax.naming.Name) + */ + @Override + public Name composeName(final Name name, final Name prefix) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#composeName(java.lang.String, java.lang.String) + */ + @Override + public String composeName(final String name, final String prefix) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#addToEnvironment(java.lang.String, java.lang.Object) + */ + @Override + public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#removeFromEnvironment(java.lang.String) + */ + @Override + public Object removeFromEnvironment(final String propName) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#getEnvironment() + */ + @Override + public Hashtable getEnvironment() throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#close() + */ + @Override + public void close() throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#getNameInNamespace() + */ + @Override + public String getNameInNamespace() throws NamingException { + return null; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestInitialContextFactory.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestInitialContextFactory.java new file mode 100644 index 000000000..d04cd5791 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestInitialContextFactory.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import java.util.Hashtable; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.spi.InitialContextFactory; + +/** + * A factory for creating TestInitialContext objects. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestInitialContextFactory implements InitialContextFactory { + + private final Context context = new TestContext(); + + /** + * Instantiates a new test initial context factory. + * + * @throws NamingException the naming exception + */ + public TestInitialContextFactory() throws NamingException {} + + /* + * (non-Javadoc) + * + * @see javax.naming.spi.InitialContextFactory#getInitialContext(java.util.Hashtable) + */ + @Override + public Context getInitialContext(final Hashtable environment) throws NamingException { + return context; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestJms2Jms.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestJms2Jms.java new file mode 100644 index 000000000..422a97a11 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestJms2Jms.java @@ -0,0 +1,198 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.jms.JMSException; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.activemq.broker.BrokerPlugin; +import org.apache.activemq.broker.BrokerService; +import org.apache.activemq.security.AuthenticationUser; +import org.apache.activemq.security.SimpleAuthenticationPlugin; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestJms2Jms. + */ +public class TestJms2Jms { + public static final String PORT = "5445"; + public static final String HOST = "localhost"; + public static final String JMS_TOPIC_APEX_IN = "jms/topic/apexIn"; + public static final String JMS_TOPIC_APEX_OUT = "jms/topic/apexOut"; + + private static final int SLEEP_TIME = 1500; + private static final String GROUP_ROLE = "guests"; + private static final String PACKAGE_NAME = "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms"; + private static final String USERNAME = "guest"; + private static final String PASSWORD = "IAmAGuest"; + private static final String URL = "tcp://" + HOST + ":" + PORT; + + private static final String DATA_PARENT_DIR = Paths.get("target", "activemq-data").toString(); + + private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestJms2Jms.class); + + private static final long MAX_TEST_LENGTH = 10000; + private static final int EVENT_COUNT = 100; + private static final int EVENT_INTERVAL = 20; + + private static BrokerService broker; + + public static ActiveMQConnectionFactory connectionFactory; + + + /** + * Setup embedded jms server. + * + * @throws Exception the exception + */ + @BeforeClass + public static void setupEmbeddedJmsServer() throws Exception { + final ArrayList plugins = new ArrayList(); + final BrokerPlugin authenticationPlugin = getAuthenticationBrokerPlugin(); + plugins.add(authenticationPlugin); + + broker = new BrokerService(); + broker.setUseJmx(false); + broker.setPersistent(false); + broker.addConnector(URL); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPlugins(plugins.toArray(new BrokerPlugin[0])); + broker.setDataDirectory(DATA_PARENT_DIR); + broker.start(); + broker.waitUntilStarted(); + connectionFactory = new ActiveMQConnectionFactory(URL); + connectionFactory.setTrustedPackages(Arrays.asList(PACKAGE_NAME)); + } + + /** + * Gets the authentication broker plugin. + * + * @return the authentication broker plugin + */ + private static BrokerPlugin getAuthenticationBrokerPlugin() { + final List users = new ArrayList(); + users.add(new AuthenticationUser(USERNAME, PASSWORD, GROUP_ROLE)); + final SimpleAuthenticationPlugin authenticationPlugin = new SimpleAuthenticationPlugin(users); + return authenticationPlugin; + } + + /** + * Shutdown embedded jms server. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @AfterClass + public static void shutdownEmbeddedJmsServer() throws IOException { + try { + if (broker != null) { + broker.stop(); + } + } catch (final Exception e) { + LOGGER.warn("Failed to stop JMS server", e); + } + + } + + /** + * Test jms object events. + * + * @throws ApexException the apex exception + * @throws JMSException the JMS exception + */ + @Test + public void testJmsObjectEvents() throws ApexException, JMSException { + final String[] args = { "src/test/resources/prodcons/JMS2JMSObjectEvent.json" }; + testJmsEvents(args, true); + } + + /** + * Test jms json events. + * + * @throws ApexException the apex exception + * @throws JMSException the JMS exception + */ + @Test + public void testJmsJsonEvents() throws ApexException, JMSException { + final String[] args = { "src/test/resources/prodcons/JMS2JMSJsonEvent.json" }; + testJmsEvents(args, false); + } + + /** + * Test jms events. + * + * @param args the args + * @param sendObjects the send objects + * @throws ApexException the apex exception + * @throws JMSException the JMS exception + */ + private void testJmsEvents(final String[] args, final Boolean sendObjects) throws ApexException, JMSException { + final JmsEventSubscriber subscriber = + new JmsEventSubscriber(JMS_TOPIC_APEX_OUT, connectionFactory, USERNAME, PASSWORD); + final JmsEventProducer producer = new JmsEventProducer(JMS_TOPIC_APEX_IN, connectionFactory, USERNAME, PASSWORD, + EVENT_COUNT, sendObjects, EVENT_INTERVAL); + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(3000); + + producer.sendEvents(); + + final long testStartTime = System.currentTimeMillis(); + + while (isTimedOut(testStartTime) && subscriber.getEventsReceivedCount() < EVENT_COUNT) { + ThreadUtilities.sleep(EVENT_INTERVAL); + } + + ThreadUtilities.sleep(SLEEP_TIME); + apexMain.shutdown(); + subscriber.shutdown(); + producer.shutdown(); + ThreadUtilities.sleep(SLEEP_TIME); + + assertEquals(EVENT_COUNT, producer.getEventsSentCount()); + assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount()); + + } + + /** + * Checks if is timed out. + * + * @param testStartTime the test start time + * @return true, if is timed out + */ + private boolean isTimedOut(final long testStartTime) { + return System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestPing.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestPing.java new file mode 100644 index 000000000..b0dfb553a --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestPing.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import java.io.Serializable; + +import org.onap.policy.apex.service.engine.event.ApexEventException; + +/** + * The Class TestPing. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestPing implements Serializable { + private static final long serialVersionUID = -3400711508992955886L; + + private String name = "Rose"; + private String description = "A rose by any other name would smell as sweet"; + private long pingTime = System.currentTimeMillis(); + private long pongTime = -1; + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(final String name) { + this.name = name; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Sets the description. + * + * @param description the new description + */ + public void setDescription(final String description) { + this.description = description; + } + + /** + * Gets the ping time. + * + * @return the ping time + */ + public long getPingTime() { + return pingTime; + } + + /** + * Sets the ping time. + * + * @param pingTime the new ping time + */ + public void setPingTime(final long pingTime) { + this.pingTime = pingTime; + } + + /** + * Gets the pong time. + * + * @return the pong time + */ + public long getPongTime() { + return pongTime; + } + + /** + * Sets the pong time. + * + * @param pongTime the new pong time + */ + public void setPongTime(final long pongTime) { + this.pongTime = pongTime; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "TestPing [name=" + name + ", description=" + description + ", pingTime=" + pingTime + ", pongTime=" + + pongTime + "]"; + } + + /** + * Verify. + * + * @throws ApexEventException the apex event exception + */ + public void verify() throws ApexEventException { + if (!name.startsWith("Rose")) { + throw new ApexEventException("TestPing is not valid"); + } + + if (name.length() <= 4) { + throw new ApexEventException("TestPing is not valid"); + } + + if (!description.startsWith("A rose by any other name would smell as sweet")) { + throw new ApexEventException("TestPing is not valid"); + } + + if (description.length() <= 44) { + throw new ApexEventException("TestPing is not valid"); + } + + if (pongTime <= pingTime) { + throw new ApexEventException("TestPing is not valid"); + } + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventProducer.java new file mode 100644 index 000000000..072d67864 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventProducer.java @@ -0,0 +1,201 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka; + +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator; + +/** + * The Class KafkaEventProducer. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class KafkaEventProducer implements Runnable { + private final String topic; + private final String kafkaServerAddress; + private final int eventCount; + private final boolean xmlEvents; + private final long eventInterval; + private long eventsSentCount = 0; + + private final Thread producerThread; + private boolean sendEventsFlag = false; + private boolean stopFlag = false; + + /** + * Instantiates a new kafka event producer. + * + * @param topic the topic + * @param kafkaServerAddress the kafka server address + * @param eventCount the event count + * @param xmlEvents the xml events + * @param eventInterval the event interval + */ + public KafkaEventProducer(final String topic, final String kafkaServerAddress, final int eventCount, + final boolean xmlEvents, final long eventInterval) { + this.topic = topic; + this.kafkaServerAddress = kafkaServerAddress; + this.eventCount = eventCount; + this.xmlEvents = xmlEvents; + this.eventInterval = eventInterval; + + producerThread = new Thread(this); + producerThread.start(); + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + final Properties kafkaProducerProperties = new Properties(); + kafkaProducerProperties.put("bootstrap.servers", kafkaServerAddress); + kafkaProducerProperties.put("acks", "all"); + kafkaProducerProperties.put("retries", 0); + kafkaProducerProperties.put("batch.size", 16384); + kafkaProducerProperties.put("linger.ms", 1); + kafkaProducerProperties.put("buffer.memory", 33554432); + kafkaProducerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + kafkaProducerProperties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + + final Producer producer = new KafkaProducer(kafkaProducerProperties); + + while (producerThread.isAlive() && !stopFlag) { + ThreadUtilities.sleep(50); + + if (sendEventsFlag) { + sendEventsToTopic(producer); + sendEventsFlag = false; + } + } + + producer.close(1000, TimeUnit.MILLISECONDS); + } + + /** + * Send events. + */ + public void sendEvents() { + sendEventsFlag = true; + } + + /** + * Send events to topic. + * + * @param producer the producer + */ + private void sendEventsToTopic(final Producer producer) { + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": sending events to Kafka server at " + + kafkaServerAddress + ", event count " + eventCount + ", xmlEvents " + xmlEvents); + + for (int i = 0; i < eventCount; i++) { + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": waiting " + eventInterval + + " milliseconds before sending next event"); + ThreadUtilities.sleep(eventInterval); + + String eventString = null; + if (xmlEvents) { + eventString = EventGenerator.xmlEvent(); + } else { + eventString = EventGenerator.jsonEvent(); + } + producer.send(new ProducerRecord(topic, "Event" + i + "Of" + eventCount, eventString)); + producer.flush(); + eventsSentCount++; + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": sent event " + eventString); + } + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": completed"); + } + + /** + * Gets the events sent count. + * + * @return the events sent count + */ + public long getEventsSentCount() { + return eventsSentCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": stopping"); + + stopFlag = true; + + while (producerThread.isAlive()) { + ThreadUtilities.sleep(10); + } + + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": stopped"); + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + if (args.length != 5) { + System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[2]); + } catch (final Exception e) { + System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + long eventInterval = 0; + try { + eventInterval = Long.parseLong(args[4]); + } catch (final Exception e) { + System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + boolean xmlEvents = false; + if (args[3].equalsIgnoreCase("XML")) { + xmlEvents = true; + } else if (!args[3].equalsIgnoreCase("JSON")) { + System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); + return; + } + + final KafkaEventProducer producer = new KafkaEventProducer(args[0], args[1], eventCount, xmlEvents, + eventInterval); + + producer.sendEvents(); + producer.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventSubscriber.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventSubscriber.java new file mode 100644 index 000000000..4b6a62e28 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventSubscriber.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka; + +import java.util.Arrays; +import java.util.Properties; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; + +/** + * The Class KafkaEventSubscriber. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class KafkaEventSubscriber implements Runnable { + private final String topic; + private final String kafkaServerAddress; + private long eventsReceivedCount = 0; + + KafkaConsumer consumer; + + Thread subscriberThread; + + /** + * Instantiates a new kafka event subscriber. + * + * @param topic the topic + * @param kafkaServerAddress the kafka server address + * @throws MessagingException the messaging exception + */ + public KafkaEventSubscriber(final String topic, final String kafkaServerAddress) throws MessagingException { + this.topic = topic; + this.kafkaServerAddress = kafkaServerAddress; + + final Properties props = new Properties(); + props.put("bootstrap.servers", kafkaServerAddress); + props.put("group.id", "test"); + props.put("enable.auto.commit", "true"); + props.put("auto.commit.interval.ms", "1000"); + props.put("session.timeout.ms", "30000"); + props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + + consumer = new KafkaConsumer(props); + consumer.subscribe(Arrays.asList(topic)); + + subscriberThread = new Thread(this); + subscriberThread.start(); + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": receiving events from Kafka server at " + + kafkaServerAddress + " on topic " + topic); + + while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) { + try { + final ConsumerRecords records = consumer.poll(100); + for (final ConsumerRecord record : records) { + System.out.println("******"); + System.out.println("offset=" + record.offset()); + System.out.println("key=" + record.key()); + System.out.println("name=" + record.value()); + eventsReceivedCount++; + } + } catch (final Exception e) { + // Thread interrupted + break; + } + } + + System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": event reception completed"); + } + + /** + * Gets the events received count. + * + * @return the events received count + */ + public long getEventsReceivedCount() { + return eventsReceivedCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + subscriberThread.interrupt(); + + while (subscriberThread.isAlive()) { + ThreadUtilities.sleep(10); + } + + consumer.close(); + System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": stopped"); + } + + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 2) { + System.err.println("usage KafkaEventSubscriber topic kafkaServerAddress"); + return; + } + new KafkaEventSubscriber(args[0], args[1]); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafka2Kafka.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafka2Kafka.java new file mode 100644 index 000000000..e70a597c2 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafka2Kafka.java @@ -0,0 +1,185 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.file.Files; +import java.util.Properties; + +import kafka.admin.AdminUtils; +import kafka.admin.RackAwareMode; +import kafka.server.KafkaConfig; +import kafka.server.KafkaServer; +import kafka.utils.TestUtils; +import kafka.utils.ZKStringSerializer$; +import kafka.utils.ZkUtils; +import kafka.zk.EmbeddedZookeeper; + +import org.I0Itec.zkclient.ZkClient; +import org.apache.kafka.common.utils.MockTime; +import org.apache.kafka.common.utils.Time; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + + +/** + * The Class TestKafka2Kafka. + */ +public class TestKafka2Kafka { + // The method of starting an embedded Kafka server used in this example is based on the method + // on stack overflow at + // https://github.com/asmaier/mini-kafka + + private static final long MAX_TEST_LENGTH = 20000; + + private static final int EVENT_COUNT = 10; + private static final int EVENT_INTERVAL = 20; + + private static final String ZKHOST = "127.0.0.1"; + private static final String BROKERHOST = "127.0.0.1"; + private static final String BROKERPORT = "39902"; + + private static EmbeddedZookeeper zkServer; + private static ZkClient zkClient; + private static KafkaServer kafkaServer; + + /** + * Setup dummy kafka server. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @BeforeClass + public static void setupDummyKafkaServer() throws IOException { + // setup Zookeeper + zkServer = new EmbeddedZookeeper(); + final String zkConnect = ZKHOST + ":" + zkServer.port(); + zkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer$.MODULE$); + final ZkUtils zkUtils = ZkUtils.apply(zkClient, false); + + // setup Broker + final Properties brokerProps = new Properties(); + brokerProps.setProperty("zookeeper.connect", zkConnect); + brokerProps.setProperty("broker.id", "0"); + brokerProps.setProperty("log.dirs", Files.createTempDirectory("kafka-").toAbsolutePath().toString()); + brokerProps.setProperty("listeners", "PLAINTEXT://" + BROKERHOST + ":" + BROKERPORT); + brokerProps.setProperty("offsets.topic.replication.factor", "1"); + brokerProps.setProperty("transaction.state.log.replication.factor", "1"); + brokerProps.setProperty("transaction.state.log.min.isr", "1"); + final KafkaConfig config = new KafkaConfig(brokerProps); + final Time mock = new MockTime(); + kafkaServer = TestUtils.createServer(config, mock); + kafkaServer.startup(); + + // create topics + AdminUtils.createTopic(zkUtils, "apex-in-0", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); + AdminUtils.createTopic(zkUtils, "apex-in-1", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); + AdminUtils.createTopic(zkUtils, "apex-out", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); + + } + + /** + * Shutdown dummy kafka server. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @AfterClass + public static void shutdownDummyKafkaServer() throws IOException { + if (kafkaServer != null) { + kafkaServer.shutdown(); + } + if (zkClient != null) { + zkClient.close(); + } + if (zkServer != null) { + zkServer.shutdown(); + } + } + + /** + * Test json kafka events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + @Test + public void testJsonKafkaEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Kafka2KafkaJsonEvent.json"}; + testKafkaEvents(args, false, "json"); + } + + /** + * Test XML kafka events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + @Test + public void testXmlKafkaEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Kafka2KafkaXmlEvent.json"}; + testKafkaEvents(args, true, "xml"); + } + + /** + * Test kafka events. + * + * @param args the args + * @param xmlEvents the xml events + * @param topicSuffix the topic suffix + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + private void testKafkaEvents(final String[] args, final Boolean xmlEvents, final String topicSuffix) + throws MessagingException, ApexException { + final KafkaEventSubscriber subscriber = + new KafkaEventSubscriber("apex-out-" + topicSuffix, "localhost:" + BROKERPORT); + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(3000); + + final KafkaEventProducer producer = new KafkaEventProducer("apex-in-" + topicSuffix, "localhost:" + BROKERPORT, + EVENT_COUNT, xmlEvents, EVENT_INTERVAL); + + producer.sendEvents(); + + final long testStartTime = System.currentTimeMillis(); + + while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH + && subscriber.getEventsReceivedCount() < EVENT_COUNT) { + ThreadUtilities.sleep(EVENT_INTERVAL); + } + + ThreadUtilities.sleep(1000); + + assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount()); + + apexMain.shutdown(); + subscriber.shutdown(); + producer.shutdown(); + ThreadUtilities.sleep(1000); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafkaXmlEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafkaXmlEventProducer.java new file mode 100644 index 000000000..2b16d71d4 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafkaXmlEventProducer.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka; + +import java.util.Properties; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEvent; +import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEventData; + +/** + * The Class TestKafkaXmlEventProducer. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestKafkaXmlEventProducer { + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + final Properties props = new Properties(); + props.put("bootstrap.servers", "localhost:49092"); + props.put("acks", "all"); + props.put("retries", 0); + props.put("batch.size", 16384); + props.put("linger.ms", 1); + props.put("buffer.memory", 33554432); + props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + + final XMLApexEvent xmlEvent = new XMLApexEvent(); + xmlEvent.setName("XMLEvent-1"); + xmlEvent.setVersion("0.0.1"); + xmlEvent.getData().add(new XMLApexEventData("Data-1", "Data Value -1")); + + final Producer producer = new KafkaProducer(props); + for (int i = 0; i < 100; i++) { + xmlEvent.setName("XMLEvent" + Integer.toString(i)); + xmlEvent.setVersion("0.0.1"); + xmlEvent.getData() + .add(new XMLApexEventData("Data" + Integer.toString(i), "Data Value " + Integer.toString(i))); + + producer.send(new ProducerRecord("apex-in-0", xmlEvent.getName(), xmlEvent.toString())); + } + producer.close(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestFile2Rest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestFile2Rest.java new file mode 100644 index 000000000..d681fd471 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestFile2Rest.java @@ -0,0 +1,266 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; +import java.util.Map; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.core.Response; + +import org.glassfish.grizzly.http.server.HttpServer; +import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestFile2Rest. + */ +public class TestFile2Rest { + private static final String BASE_URI = "http://localhost:32801/TestFile2Rest"; + private static HttpServer server; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + + private final PrintStream stdout = System.out; + private final PrintStream stderr = System.err; + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @BeforeClass + public static void setUp() throws Exception { + final ResourceConfig rc = new ResourceConfig(TestRestClientEndpoint.class); + server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); + + while (!server.isStarted()) { + ThreadUtilities.sleep(50); + } + } + + /** + * Tear down. + * + * @throws Exception the exception + */ + @AfterClass + public static void tearDown() throws Exception { + server.shutdown(); + } + + /** + * Test file events post. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsPost() throws MessagingException, ApexException, IOException { + final Client client = ClientBuilder.newClient(); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventPost.json" }; + final ApexMain apexMain = new ApexMain(args); + + // Wait for the required amount of events to be received or for 10 seconds + for (int i = 0; i < 100; i++) { + ThreadUtilities.sleep(100); + final Response response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats") + .request("application/json").get(); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + if ((double) jsonMap.get("POST") == 100) { + break; + } + } + + apexMain.shutdown(); + } + + /** + * Test file events put. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsPut() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventPut.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + // Wait for the required amount of events to be received or for 10 seconds + for (int i = 0; i < 100; i++) { + ThreadUtilities.sleep(100); + final Response response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats") + .request("application/json").get(); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + if ((double) jsonMap.get("PUT") == 100) { + break; + } + } + + apexMain.shutdown(); + } + + /** + * Test file events no url. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsNoUrl() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventNoURL.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains(" no URL has been set for event sending on REST client")); + } + + /** + * Test file events bad url. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadUrl() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventBadURL.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/Bad\" using HTTP \"POST\" failed with status code 404")); + } + + /** + * Test file events bad http method. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadHttpMethod() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "specified HTTP method of \"DELETE\" is invalid, only HTTP methods \"POST\" and \"PUT\" " + + "are supproted for event sending on REST client producer")); + } + + /** + * Test file events bad response. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(500); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/PostEventBadResponse\" using HTTP \"POST\" failed with status code 400")); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java new file mode 100644 index 000000000..ec41de5fb --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java @@ -0,0 +1,251 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restclient; + +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; + +import org.glassfish.grizzly.http.server.HttpServer; +import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestRest2File. + */ +public class TestRest2File { + + private static final String BASE_URI = "http://localhost:32801/TestRest2File"; + private HttpServer server; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + + private final PrintStream stdout = System.out; + private final PrintStream stderr = System.err; + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @Before + public void setUp() throws Exception { + final ResourceConfig rc = new ResourceConfig(TestRestClientEndpoint.class); + server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); + + while (!server.isStarted()) { + ThreadUtilities.sleep(50); + } + } + + /** + * Tear down. + * + * @throws Exception the exception + */ + @After + public void tearDown() throws Exception { + server.shutdown(); + } + + /** + * Delete temp files. + */ + @AfterClass + public static void deleteTempFiles() { + new File("src/test/resources/events/EventsOut.json").delete(); + } + + /** + * Test rest events in. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestEventsIn() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEvent.json" }; + + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outputEventText = TextFileUtils.getTextFileAsString("src/test/resources/events/EventsOut.json"); + assertTrue(outputEventText.contains("04\",\n" + " \"version\": \"0.0.1\",\n" + + " \"nameSpace\": \"org.onap.policy.apex.sample.events\"")); + } + + /** + * Test file empty events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEmptyEvents() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEmptyEvents.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "received an empty event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\"")); + } + + /** + * Test file events no url. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsNoUrl() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEventNoURL.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains(" no URL has been set for event sending on REST client")); + } + + /** + * Test file events bad url. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadUrl() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEventBadURL.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404")); + } + + /** + * Test file events bad http method. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadHttpMethod() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains("specified HTTP method of \"POST\" is invalid, " + + "only HTTP method \"GET\" is supported for event reception on REST client consumer")); + } + + /** + * Test file events bad response. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEventBadResponse.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" failed with status code 400 and message \"\"")); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRestClientEndpoint.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRestClientEndpoint.java new file mode 100644 index 000000000..906b20bf2 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRestClientEndpoint.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; + +import java.util.Map; +import java.util.Random; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; + +/** + * The Class TestRestClientEndpoint. + */ +@Path("/apex") +public class TestRestClientEndpoint { + + private static int postMessagesReceived = 0; + private static int putMessagesReceived = 0; + private static int statMessagesReceived = 0; + private static int getMessagesReceived = 0; + + /** + * Service get stats. + * + * @return the response + */ + @Path("/event/Stats") + @GET + public Response serviceGetStats() { + statMessagesReceived++; + return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } + + /** + * Service get event. + * + * @return the response + */ + @Path("/event/GetEvent") + @GET + public Response serviceGetEvent() { + final Random rand = new Random(); + final int nextMatchCase = rand.nextInt(4); + final String nextEventName = "Event0" + rand.nextInt(2) + "00"; + + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" + + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + getMessagesReceived + + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" + + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; + + getMessagesReceived++; + + return Response.status(200).entity(eventString).build(); + } + + /** + * Service get empty event. + * + * @return the response + */ + @Path("/event/GetEmptyEvent") + @GET + public Response serviceGetEmptyEvent() { + return Response.status(200).build(); + } + + /** + * Service get event bad response. + * + * @return the response + */ + @Path("/event/GetEventBadResponse") + @GET + public Response serviceGetEventBadResponse() { + return Response.status(400).build(); + } + + /** + * Service post request. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PostEvent") + @POST + public Response servicePostRequest(final String jsonString) { + postMessagesReceived++; + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(jsonString, Map.class); + assertTrue(jsonMap.containsKey("name")); + assertEquals("0.0.1", jsonMap.get("version")); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Act", jsonMap.get("source")); + assertEquals("Outside", jsonMap.get("target")); + + return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } + + /** + * Service post request bad response. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PostEventBadResponse") + @POST + public Response servicePostRequestBadResponse(final String jsonString) { + return Response.status(400).build(); + } + + /** + * Service put request. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PutEvent") + @PUT + public Response servicePutRequest(final String jsonString) { + putMessagesReceived++; + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(jsonString, Map.class); + assertTrue(jsonMap.containsKey("name")); + assertEquals("0.0.1", jsonMap.get("version")); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Act", jsonMap.get("source")); + assertEquals("Outside", jsonMap.get("target")); + + return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServer.java new file mode 100644 index 000000000..59cc2ceea --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServer.java @@ -0,0 +1,447 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Map; +import java.util.Random; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestRestServer. + */ +public class TestRestServer { + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + + private final PrintStream stdout = System.out; + private final PrintStream stderr = System.err; + + private static int eventsSent = 0; + + /** + * Test rest server put. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerPut() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEvent.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + for (int i = 0; i < 20; i++) { + final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); + } + + apexMain.shutdown(); + } + + /** + * Test rest server post. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerPost() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEvent.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + for (int i = 0; i < 20; i++) { + final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").post(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); + } + + apexMain.shutdown(); + } + + /** + * Test rest server get status. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerGetStatus() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEvent.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + // trigger 10 POST & PUT events + for (int i = 0; i < 10; i++) { + final Response postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").post(Entity.json(getEvent())); + final Response putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(getEvent())); + assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus()); + assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus()); + } + + final Response statResponse = client.target("http://localhost:23324/apex/FirstConsumer/Status") + .request("application/json").get(); + + assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus()); + final String responseString = statResponse.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + assertEquals("[FirstConsumer", ((String)jsonMap.get("INPUTS")).substring(0, 14)); + assertEquals(1.0, jsonMap.get("STAT")); + assertTrue((double)jsonMap.get("POST") >= 10.0); + assertTrue((double)jsonMap.get("PUT") >= 10.0); + + apexMain.shutdown(); + } + + /** + * Test rest server multi inputs. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerMultiInputs() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventMultiIn.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + for (int i = 0; i < 20; i++) { + final Response firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").post(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus()); + final String firstResponseString = firstResponse.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map firstJsonMap = new Gson().fromJson(firstResponseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan")); + + final Response secondResponse = client.target("http://localhost:23324/apex/SecondConsumer/EventIn") + .request("application/json").post(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus()); + final String secondResponseString = secondResponse.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map secondJsonMap = new Gson().fromJson(secondResponseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan")); + } + + apexMain.shutdown(); + } + + /** + * Test rest server producer standalone. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerProducerStandalone() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer")); + } + + /** + * Test rest server producer host. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerProducerHost() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventProducerHost.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains(" host is specified only in standalone mode")); + } + + /** + * Test rest server producer port. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerProducerPort() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventProducerPort.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains(" port is specified only in standalone mode")); + } + + /** + * Test rest server consumer standalone no host. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer " + + "(FirstConsumer) in standalone mode")); + } + + /** + * Test rest server consumer standalone no port. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer " + + "(FirstConsumer) in standalone mode")); + } + + /** + * Test rest server producer not sync. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains("REST Server producer (FirstProducer) must run in synchronous mode " + + "with a REST Server consumer")); + } + + /** + * Test rest server consumer not sync. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString + .contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined " + + "with the same peered mode")); + } + + /** + * Test rest server divide by zero. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerDivideByZero() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventDivideByZero.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + for (int i = 0; i < 20; i++) { + final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); + assertTrue(((String) jsonMap.get("exceptionMessage")).contains("caused by: / by zero")); + } + + apexMain.shutdown(); + } + + /** + * Gets the event. + * + * @return the event + */ + private String getEvent() { + final Random rand = new Random(); + final int nextMatchCase = rand.nextInt(4); + final String nextEventName = "Event0" + rand.nextInt(2) + "00"; + + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" + + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" + + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + + System.currentTimeMillis() + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; + + return eventString; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServerVpnContext.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServerVpnContext.java new file mode 100644 index 000000000..1791033e6 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServerVpnContext.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; + +import org.junit.Ignore; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + + +public class TestRestServerVpnContext { + private static int eventsSent = 0; + + @Ignore + @Test + public void testRestServerPut() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventContextJava.json"}; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(setupLinkContext("L09", true))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupLinkContext("L10", true))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("A", "L09 L10", 300, 50))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("B", "L09 L10", 300, 299))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("C", "L09 L10", 300, 300))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("D", "L09 L10", 300, 400))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + ThreadUtilities.sleep(100000); + + apexMain.shutdown(); + } + + @Ignore + @Test + public void testRestServerPutAvro() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventContextAvro.json"}; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(setupLinkContext("L09", true))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupLinkContext("L10", true))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("A", "L09 L10", 300, 50))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("B", "L09 L10", 300, 299))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("C", "L09 L10", 300, 300))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("D", "L09 L10", 300, 400))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + ThreadUtilities.sleep(100000); + + apexMain.shutdown(); + } + + private String setupLinkContext(final String link, final Boolean isUp) { + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.domains.vpn.events\",\n" + + "\"name\": \"VPNLinkCtxtTriggerEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + + eventsSent++ + "\",\n" + "\"target\": \"apex\",\n" + "\"Link\": \"" + link + "\",\n" + "\"LinkUp\": " + + isUp + "\n" + "}"; + + return eventString; + } + + private String setupCustomerContext(final String customerName, final String linkList, final int slaDt, + final int ytdDt) { + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.domains.vpn.events\",\n" + + "\"name\": \"VPNCustomerCtxtTriggerEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + + eventsSent++ + "\",\n" + "\"target\": \"apex\",\n" + "\"CustomerName\": \"" + customerName + "\",\n" + + "\"LinkList\": \"" + linkList + "\",\n" + "\"SlaDT\": \"" + slaDt + "\",\n" + "\"YtdDT\": " + ytdDt + + "\n" + "}"; + + return eventString; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/Foo.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/Foo.java new file mode 100644 index 000000000..2d6ab4629 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/Foo.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.sampletypes; + +public class Foo { + private String bar; + + public String getBar() { + return bar; + } + + public void setBar(final String bar) { + this.bar = bar; + } + + public Foo(final String bar) { + this(); + this.bar = bar; + } + + public Foo() { + super(); + } + + @Override + public String toString() { + return "Foo [bar=(String)\"" + bar + "\"]"; + } + +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/FooMap.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/FooMap.java new file mode 100644 index 000000000..af09e5a3b --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/FooMap.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.sampletypes; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class FooMap extends LinkedHashMap { + private static final long serialVersionUID = -7125986379378753022L; + + public FooMap() { + super(); + } + + public FooMap(final int initialCapacity, final float loadFactor, final boolean accessOrder) { + super(initialCapacity, loadFactor, accessOrder); + } + + public FooMap(final int initialCapacity, final float loadFactor) { + super(initialCapacity, loadFactor); + } + + public FooMap(final int initialCapacity) { + super(initialCapacity); + } + + public FooMap(final Map map) { + super(map); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsClient.java new file mode 100644 index 000000000..c2db95860 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsClient.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + +public class TestWs2WsClient { + private static final long MAX_TEST_LENGTH = 10000; + + private static final int EVENT_COUNT = 100; + private static final int EVENT_INTERVAL = 20; + + @Test + public void testJsonWsEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Ws2WsClientJsonEvent.json"}; + testWsEvents(args, false); + } + + @Test + public void testXmlWsEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Ws2WsClientXMLEvent.json"}; + testWsEvents(args, true); + } + + private void testWsEvents(final String[] args, final Boolean xmlEvents) throws MessagingException, ApexException { + final WebSocketEventSubscriberServer subServer = new WebSocketEventSubscriberServer(42453); + final WebSocketEventProducerServer prodServer = + new WebSocketEventProducerServer(42451, EVENT_COUNT, xmlEvents, EVENT_INTERVAL); + + final ApexMain apexMain = new ApexMain(args); + + prodServer.sendEvents(); + + final long testStartTime = System.currentTimeMillis(); + + while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH + && subServer.getEventsReceivedCount() < EVENT_COUNT) { + ThreadUtilities.sleep(EVENT_INTERVAL); + } + + assertEquals(prodServer.getEventsSentCount(), subServer.getEventsReceivedCount()); + + apexMain.shutdown(); + prodServer.shutdown(); + subServer.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsServer.java new file mode 100644 index 000000000..34871e3c6 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsServer.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestWs2WsServer. + */ +public class TestWs2WsServer { + private static final long MAX_TEST_LENGTH = 10000; + + private static final int EVENT_COUNT = 100; + private static final int EVENT_INTERVAL = 20; + + /** + * Test json ws events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + @Test + public void testJsonWsEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Ws2WsServerJsonEvent.json"}; + testWsEvents(args, false); + } + + /** + * Test xml ws events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + @Test + public void testXmlWsEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Ws2WsServerXMLEvent.json"}; + testWsEvents(args, true); + } + + /** + * Test ws events. + * + * @param args the args + * @param xmlEvents the xml events + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + public void testWsEvents(final String[] args, final boolean xmlEvents) throws MessagingException, ApexException { + final ApexMain apexMain = new ApexMain(args); + + final WebSocketEventSubscriberClient subClient = new WebSocketEventSubscriberClient("localhost", 42452); + final WebSocketEventProducerClient prodClient = + new WebSocketEventProducerClient("localhost", 42450, EVENT_COUNT, xmlEvents, EVENT_INTERVAL); + + prodClient.sendEvents(); + + final long testStartTime = System.currentTimeMillis(); + + while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH + && subClient.getEventsReceivedCount() < EVENT_COUNT) { + ThreadUtilities.sleep(EVENT_INTERVAL); + } + + assertEquals(subClient.getEventsReceivedCount(), prodClient.getEventsSentCount()); + + prodClient.shutdown(); + subClient.shutdown(); + apexMain.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerClient.java new file mode 100644 index 000000000..84a337362 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerClient.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageClient; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator; + +/** + * The Class WebSocketEventProducerClient. + */ +public class WebSocketEventProducerClient implements WsStringMessageListener { + private final String host; + private final int port; + private final int eventCount; + private final boolean xmlEvents; + private final long eventInterval; + private long eventsSentCount = 0; + + WsStringMessageClient client; + + /** + * Instantiates a new web socket event producer client. + * + * @param host the host + * @param port the port + * @param eventCount the event count + * @param xmlEvents the xml events + * @param eventInterval the event interval + * @throws MessagingException the messaging exception + */ + public WebSocketEventProducerClient(final String host, final int port, final int eventCount, + final boolean xmlEvents, final long eventInterval) throws MessagingException { + this.host = host; + this.port = port; + this.eventCount = eventCount; + this.xmlEvents = xmlEvents; + this.eventInterval = eventInterval; + + client = new WsStringMessageClient(host, port); + client.start(this); + + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": host " + host + ", port " + port + + ", event count " + eventCount + ", xmlEvents " + xmlEvents); + } + + /** + * Send events. + */ + public void sendEvents() { + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": sending events on host " + host + + ", port " + port + ", event count " + eventCount + ", xmlEvents " + xmlEvents); + + for (int i = 0; i < eventCount; i++) { + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": waiting " + eventInterval + + " milliseconds before sending next event"); + ThreadUtilities.sleep(eventInterval); + + String eventString = null; + if (xmlEvents) { + eventString = EventGenerator.xmlEvent(); + } else { + eventString = EventGenerator.jsonEvent(); + } + client.sendString(eventString); + eventsSentCount++; + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": host " + host + ", port " + + port + ", sent event " + eventString); + } + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": completed"); + } + + /** + * Gets the events sent count. + * + * @return the events sent count + */ + public long getEventsSentCount() { + return eventsSentCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + client.stop(); + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": stopped"); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# + * receiveString(java.lang.String) + */ + @Override + public void receiveString(final String eventString) { + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": host " + host + ", port " + port + + ", received event " + eventString); + } + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 5) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + return; + } + + int port = 0; + try { + port = Integer.parseInt(args[1]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[2]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + long eventInterval = 0; + try { + eventInterval = Long.parseLong(args[4]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + boolean xmlEvents = false; + if (args[3].equalsIgnoreCase("XML")) { + xmlEvents = true; + } else if (!args[3].equalsIgnoreCase("JSON")) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + return; + } + + final WebSocketEventProducerClient client = + new WebSocketEventProducerClient(args[0], port, eventCount, xmlEvents, eventInterval); + + client.sendEvents(); + client.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerServer.java new file mode 100644 index 000000000..3e5ff714e --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerServer.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageServer; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator; + +/** + * The Class WebSocketEventProducerServer. + */ +public class WebSocketEventProducerServer implements WsStringMessageListener { + private final int port; + private final int eventCount; + private final boolean xmlEvents; + private final long eventInterval; + private long eventsSentCount = 0; + + WsStringMessageServer server; + + /** + * Instantiates a new web socket event producer server. + * + * @param port the port + * @param eventCount the event count + * @param xmlEvents the xml events + * @param eventInterval the event interval + * @throws MessagingException the messaging exception + */ + public WebSocketEventProducerServer(final int port, final int eventCount, final boolean xmlEvents, + final long eventInterval) throws MessagingException { + this.port = port; + this.eventCount = eventCount; + this.xmlEvents = xmlEvents; + this.eventInterval = eventInterval; + + server = new WsStringMessageServer(port); + server.start(this); + + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port + ", event count " + + eventCount + ", xmlEvents " + xmlEvents); + } + + /** + * Send events. + */ + public void sendEvents() { + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": sending events on port " + port + + ", event count " + eventCount + ", xmlEvents " + xmlEvents); + + for (int i = 0; i < eventCount; i++) { + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": waiting " + eventInterval + + " milliseconds before sending next event"); + ThreadUtilities.sleep(eventInterval); + + String eventString = null; + if (xmlEvents) { + eventString = EventGenerator.xmlEvent(); + } else { + eventString = EventGenerator.jsonEvent(); + } + server.sendString(eventString); + eventsSentCount++; + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port + + ", sent event " + eventString); + } + + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": event sending completed"); + } + + /** + * Gets the events sent count. + * + * @return the events sent count + */ + public long getEventsSentCount() { + return eventsSentCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + server.stop(); + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": stopped"); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# + * receiveString(java.lang.String) + */ + @Override + public void receiveString(final String eventString) { + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port + + ", received event " + eventString); + } + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 4) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); + return; + } + + int port = 0; + try { + port = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[1]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + long eventInterval = 0; + try { + eventInterval = Long.parseLong(args[3]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + boolean xmlEvents = false; + if (args[2].equalsIgnoreCase("XML")) { + xmlEvents = true; + } else if (!args[2].equalsIgnoreCase("JSON")) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON startDelay eventInterval"); + return; + } + + final WebSocketEventProducerServer server = + new WebSocketEventProducerServer(port, eventCount, xmlEvents, eventInterval); + + server.sendEvents(); + server.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberClient.java new file mode 100644 index 000000000..6477a0dc9 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberClient.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageClient; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; + +/** + * The Class WebSocketEventSubscriberClient. + */ +public class WebSocketEventSubscriberClient implements WsStringMessageListener { + private final int port; + private long eventsReceivedCount = 0; + + private final WsStringMessageClient client; + + /** + * Instantiates a new web socket event subscriber client. + * + * @param host the host + * @param port the port + * @throws MessagingException the messaging exception + */ + public WebSocketEventSubscriberClient(final String host, final int port) throws MessagingException { + this.port = port; + + client = new WsStringMessageClient(host, port); + client.start(this); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# + * receiveString(java.lang.String) + */ + @Override + public void receiveString(final String eventString) { + System.out.println(WebSocketEventSubscriberClient.class.getCanonicalName() + ": port " + port + + ", received event " + eventString); + eventsReceivedCount++; + } + + /** + * Gets the events received count. + * + * @return the events received count + */ + public long getEventsReceivedCount() { + return eventsReceivedCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + client.stop(); + System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": stopped"); + } + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 2) { + System.err.println("usage WebSocketEventSubscriberClient host port"); + return; + } + + int port = 0; + try { + port = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventSubscriberClient port"); + e.printStackTrace(); + return; + } + + new WebSocketEventSubscriberClient(args[0], port); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberServer.java new file mode 100644 index 000000000..92329236f --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberServer.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageServer; + +/** + * The Class WebSocketEventSubscriberServer. + */ +public class WebSocketEventSubscriberServer implements WsStringMessageListener { + private final int port; + private long eventsReceivedCount = 0; + + private final WsStringMessageServer server; + + /** + * Instantiates a new web socket event subscriber server. + * + * @param port the port + * @throws MessagingException the messaging exception + */ + public WebSocketEventSubscriberServer(final int port) throws MessagingException { + this.port = port; + + server = new WsStringMessageServer(port); + server.start(this); + + System.out.println( + WebSocketEventSubscriberServer.class.getCanonicalName() + ": port " + port + ", waiting for events"); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# + * receiveString(java.lang.String) + */ + @Override + public void receiveString(final String eventString) { + System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": port " + port + + ", received event " + eventString); + eventsReceivedCount++; + } + + /** + * Gets the events received count. + * + * @return the events received count + */ + public long getEventsReceivedCount() { + return eventsReceivedCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + server.stop(); + System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": stopped"); + } + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 1) { + System.err.println("usage WebSocketEventSubscriberClient port"); + return; + } + + int port = 0; + try { + port = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventSubscriberClient port"); + e.printStackTrace(); + return; + } + + new WebSocketEventSubscriberServer(port); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/context/EventAlbumContextTest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/context/EventAlbumContextTest.java new file mode 100644 index 000000000..757a48302 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/context/EventAlbumContextTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.context; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; +import org.onap.policy.common.utils.resources.ResourceUtils; + +public class EventAlbumContextTest { + private File tempCommandFile; + private File tempLogFile; + private File tempModelFile; + private String eventContextString; + private String configFile; + private String outputFile; + private String compareFile; + + @Rule + public TemporaryFolder tempTestDir = new TemporaryFolder(); + + @Test + public void testJavaEventAlbumContextTest() throws IOException, ApexException { + tempCommandFile = tempTestDir.newFile("TestPolicyJavaEventContext.apex"); + tempLogFile = tempTestDir.newFile("TestPolicyJavaEventContext.log"); + tempModelFile = tempTestDir.newFile("TestPolicyJavaEventContext.json"); + + eventContextString = ResourceUtils.getResourceAsString("examples/scripts/TestPolicyJavaEventContext.apex"); + + configFile = "src/test/resources/prodcons/Context_JavaEventAlbum_file2file.json"; + outputFile = "src/test/resources/events/Context_JavaEventAlbum_EventOut.json"; + compareFile = "src/test/resources/events/Context_JavaEventAlbum_EventOutCompare.json"; + + testEventAlbumContextTest(); + } + + @Test + public void testAvroEventAlbumContextTest() throws IOException, ApexException { + tempCommandFile = tempTestDir.newFile("TestPolicyAvroEventContext.apex"); + tempLogFile = tempTestDir.newFile("TestPolicyAvroEventContext.log"); + tempModelFile = tempTestDir.newFile("TestPolicyAvroEventContext.json"); + + eventContextString = ResourceUtils.getResourceAsString("examples/scripts/TestPolicyAvroEventContext.apex"); + + configFile = "src/test/resources/prodcons/Context_AvroEventAlbum_file2file.json"; + outputFile = "src/test/resources/events/Context_AvroEventAlbum_EventOut.json"; + compareFile = "src/test/resources/events/Context_AvroEventAlbum_EventOutCompare.json"; + + testEventAlbumContextTest(); + } + + private void testEventAlbumContextTest() throws IOException, ApexException { + TextFileUtils.putStringAsFile(eventContextString, tempCommandFile); + + final String[] cliArgs = new String[] { "-c", tempCommandFile.getCanonicalPath(), "-l", + tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath() }; + + new ApexCommandLineEditorMain(cliArgs); + + final String[] args = new String[] { "-m", tempModelFile.getAbsolutePath(), "-c", configFile }; + final ApexMain apexMain = new ApexMain(args); + + // The output event will be in this file + final File outputEventFile = new File(outputFile); + String receivedApexOutputString = ""; + for (int tenthsOfSecondsToWait = 100; tenthsOfSecondsToWait > 0; tenthsOfSecondsToWait--) { + if (outputEventFile.exists() && outputEventFile.length() > 0) { + // The output event is in this file + receivedApexOutputString = TextFileUtils.getTextFileAsString(outputEventFile.getCanonicalPath()) + .replaceAll("\\s+", ""); + break; + } + + ThreadUtilities.sleep(100); + } + + // Shut down Apex + apexMain.shutdown(); + + assertTrue("Test failed, the output event file was not created", outputEventFile.exists()); + outputEventFile.delete(); + + assertTrue("Test failed, the output event file was empty", receivedApexOutputString.length() > 0); + + // We compare the output to what we expect to get + final String expectedFileContent = TextFileUtils + .getTextFileAsString(compareFile); + final String outputEventCompareString = expectedFileContent.replaceAll("\\s+", ""); + + assertEquals(outputEventCompareString, receivedApexOutputString); + } + +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngDepMessagingTest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngDepMessagingTest.java new file mode 100644 index 000000000..a306b536e --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngDepMessagingTest.java @@ -0,0 +1,227 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.engdep; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.deployment.BatchDeployer; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +// CHECKSTYLE:OFF: checkstyle:magicNumber + +/** + * The Class EngDepMessagingTest. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EngDepMessagingTest { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngDepMessagingTest.class); + + private static final long MAX_START_WAIT = 10000; // 10 sec + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineServiceParameters engineServiceParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters, true); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters, true); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineServiceParameters = new EngineServiceParameters(); + engineServiceParameters.setName("EngDepMessagingTest"); + engineServiceParameters.setVersion("0.0.1"); + engineServiceParameters.setDeploymentPort(58820); + engineServiceParameters.setInstanceCount(3); + engineServiceParameters.setId(100); + engineServiceParameters.getEngineParameters().getExecutorParameterMap().put("MVEL", + new MvelExecutorParameters()); + + ParameterService.register(engineServiceParameters); + ParameterService.register(engineServiceParameters.getEngineParameters()); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineServiceParameters); + ParameterService.deregister(engineServiceParameters.getEngineParameters()); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test EngDep messaging. + * + * @throws URISyntaxException the URI syntax exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ + @Test + public void testEngDepMessaging() throws URISyntaxException, IOException, ApexException { + LOGGER.debug("engine<-->deployment messaging test starting . . ."); + + ModelService.clear(); + + final EngineTestServer server = new EngineTestServer(engineServiceParameters); + assertNotNull(server); + + final Thread serverThread = new Thread(server); + serverThread.start(); + final long starttime = System.currentTimeMillis(); + while (server.isStarting() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { + ThreadUtilities.sleep(100); + } + if (server.isStarting()) { + fail("Test server failed to start after " + MAX_START_WAIT + " ms"); + } + + final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + + final BatchDeployer deployer1 = new BatchDeployer("localhost", 58820); + assertNotNull(deployer1); + + deployer1.init(); + deployer1.deployModel(apexPolicyModel, false, false); + deployer1.stopEngines(); + deployer1.startEngines(); + deployer1.close(); + + // Send events + final Date testStartTime = new Date(); + final Map eventDataMap = new HashMap<>(); + eventDataMap.put("TestSlogan", "This is a test slogan"); + eventDataMap.put("TestMatchCase", (byte) 123); + eventDataMap.put("TestTimestamp", testStartTime.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + final ApexEvent event0 = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", + "apex", "test"); + event0.putAll(eventDataMap); + server.sendEvent(event0); + + final ApexEvent event1 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", + "apex", "test"); + event1.putAll(eventDataMap); + server.sendEvent(event1); + + // Wait for results + while (server.getTotalActionEventsReceived() < 2) { + ThreadUtilities.sleep(100); + } + ThreadUtilities.sleep(500); + + assertEquals(2, server.getTotalActionEventsReceived()); + + deployer1.init(); + deployer1.stopEngines(); + deployer1.close(); + + // Test re-initialization of model + final BatchDeployer deployer2 = new BatchDeployer("localhost", 58820); + assertNotNull(deployer2); + + deployer2.init(); + deployer2.deployModel(apexPolicyModel, true, true); + deployer2.stopEngines(); + deployer2.startEngines(); + deployer2.close(); + + server.sendEvent(event0); + server.sendEvent(event1); + + // Wait for results + while (server.getTotalActionEventsReceived() < 4) { + ThreadUtilities.sleep(100); + } + ThreadUtilities.sleep(500); + + assertEquals(4, server.getTotalActionEventsReceived()); + + deployer2.init(); + deployer2.stopEngines(); + deployer2.close(); + + server.stopServer(); + LOGGER.debug("engine<-->deployment messaging test finished"); + } + + /** + * Tear down. + * + * @throws Exception the exception + */ + @After + public void tearDown() throws Exception { + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngineTestServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngineTestServer.java new file mode 100644 index 000000000..9e6ff67ca --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngineTestServer.java @@ -0,0 +1,269 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.engdep; + +import java.util.Date; + +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.service.engine.engdep.EngDepMessagingService; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.runtime.ApexEventListener; +import org.onap.policy.apex.service.engine.runtime.EngineService; +import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; +import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; +import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class EngineTestServer is a test Apex service used to test the performance of Apex engines. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EngineTestServer implements Runnable, EngineServiceEventInterface { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineTestServer.class); + + private static final int TEST_SERVER_WAIT_TIME = 200; + + // The engine service for sending events to the Apex engines and the EngDEp service for engine + // administration + private EngineService engineService = null; + private EngDepMessagingService messageService = null; + + // The inner class used to receive and process events + private TestApexListener testApexListener = null; + + // Status flags + private boolean starting = true; + private boolean interrupted = false; + + // Parameters for the test + private final EngineServiceParameters parameters; + + // Apex performance statistics + private Date statsStartDate = null; + private long actionEventsReceivedCount = 0; + private long accumulatedExecutionTime = 0; + private long totalActionEventsReceivedCount = 0; + + private ApexEvent lastEventReceived = null; + + /** + * Instantiates a new engine test server to test Apex performance. + * + * @param parameters the parameters + */ + public EngineTestServer(final EngineServiceParameters parameters) { + this.parameters = parameters; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + LOGGER.debug("engine<-->deployment test server starting . . ."); + + // Set the name of the test server thread + Thread.currentThread().setName(EngineTestServer.class.getName()); + + try { + // Create the engine service and set the listener for events emitted by the Apex service + engineService = EngineServiceImpl.create(parameters); + testApexListener = new TestApexListener(); + engineService.registerActionListener("testApexListener", testApexListener); + + // Create the EngDep messaging service and start it + messageService = new EngDepMessagingService(engineService, parameters.getDeploymentPort()); + messageService.start(); + + // Record the start date for statistics + statsStartDate = new Date(); + } catch (final Exception e) { + LOGGER.error("engine<-->deployment test server exception", e); + e.printStackTrace(); + return; + } + LOGGER.debug("engine<-->deployment test server started"); + + starting = false; + + while (!interrupted) { + if (!ThreadUtilities.sleep(TEST_SERVER_WAIT_TIME)) { + interrupted = true; + } + } + } + + /** + * Stop the test server. + */ + public void stopServer() { + LOGGER.debug("engine<-->deployment test server stopping . . ."); + + interrupted = true; + messageService.stop(); + + LOGGER.debug("engine<-->deployment test server stopped"); + } + + /** + * Checks if the test server is interrupted. + * + * @return true, if is interrupted + */ + public boolean isInterrupted() { + return interrupted; + } + + /** + * Gets the total action events received. + * + * @return the total action events received + */ + public long getTotalActionEventsReceived() { + return totalActionEventsReceivedCount; + } + + /** + * Gets the last action events received. + * + * @return the last action event received + */ + public ApexEvent getLastActionEvent() { + return lastEventReceived; + } + + /** + * Gets the Apex statistics and resets them. + * + * @return the statistics + */ + public long[] getAndResetStats() { + // Check if we have statistics + if (statsStartDate == null || actionEventsReceivedCount == 0) { + return null; + } + + // Calculate, save, and reset the statistics + final long[] stats = new long[2]; + synchronized (statsStartDate) { + final long averageExecutionTime = accumulatedExecutionTime / actionEventsReceivedCount; + final long measuringTime = new Date().getTime() - statsStartDate.getTime(); + final long transactionsPerMillisecond = actionEventsReceivedCount / measuringTime; + stats[0] = averageExecutionTime; + stats[1] = transactionsPerMillisecond; + statsStartDate = new Date(); + + actionEventsReceivedCount = 0; + accumulatedExecutionTime = 0; + } + + // Return the statistics + return stats; + } + + /** + * Checks if the test server is starting. + * + * @return true, if the server is starting + */ + public boolean isStarting() { + return starting; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface#sendEvent(org.onap. + * policy.apex.service.engine.event.ApexEvent) + */ + @Override + public void sendEvent(final ApexEvent event) { + // Send the event onto the service being tested + engineService.getEngineServiceEventInterface().sendEvent(event); + } + + /** + * The listener interface for receiving testApex events. The class that is interested in + * processing a testApex event implements this interface, and the object created with that class + * is registered with a component using the component's {@code addTestApexListener} method. When + * the testApex event occurs, that object's appropriate method is invoked. + * + *

This class listens for events from the Apex engine + * + * @see TestApexEvent + */ + private final class TestApexListener implements ApexEventListener { + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy + * .apex.service.engine.event.ApexEvent) + */ + @Override + public synchronized void onApexEvent(final ApexEvent apexEvent) { + LOGGER.debug("result is:" + apexEvent); + + // Check the result event is correct + checkResult(apexEvent); + + // Calculate the performance of the Apex engine service on this policy execution run and + // accumulate the total statistics + final Date testStartTime = new Date((Long) apexEvent.get("TestTimestamp")); + final Date testEndTime = new Date(); + final long testTime = testEndTime.getTime() - testStartTime.getTime(); + LOGGER.debug("policy execution time: " + testTime + "ms"); + synchronized (statsStartDate) { + actionEventsReceivedCount++; + totalActionEventsReceivedCount++; + accumulatedExecutionTime += testTime; + } + lastEventReceived = apexEvent; + } + + /** + * Check that a reply event from the Apex engine is valid. + * + * @param result the result event from the Apex engine + */ + private void checkResult(final ApexEvent result) { + assert result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"); + + // CHECKSTYLE:OFF: checkstyle:magicNumber + assert result.get("TestSlogan").equals("This is a test slogan"); + assert result.get("TestMatchCase").equals(new Byte((byte) 123)); + assert result.get("TestTemperature").equals(34.5445667); + assert ((byte) result.get("TestMatchCaseSelected") >= 0 && (byte) result.get("TestMatchCaseSelected") <= 3); + assert ((byte) result.get("TestEstablishCaseSelected") >= 0 + && (byte) result.get("TestEstablishCaseSelected") <= 3); + assert ((byte) result.get("TestDecideCaseSelected") >= 0 + && (byte) result.get("TestDecideCaseSelected") <= 3); + assert ((byte) result.get("TestActCaseSelected") >= 0 && (byte) result.get("TestActCaseSelected") <= 3); + // CHECKSTYLE:ON: checkstyle:magicNumber + } + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/policymodels/JMSTestModel.json b/testsuites/integration/integration-uservice-test/src/test/resources/policymodels/JMSTestModel.json index d85630456..354638a6d 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/policymodels/JMSTestModel.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/policymodels/JMSTestModel.json @@ -342,7 +342,7 @@ "taskLogic": { "key": "TaskLogic", "logicFlavour": "JAVASCRIPT", - "logic": "var outFieldType = Java.type(\"org.onap.policy.apex.apps.uservice.test.adapt.jms.TestPing\");\nvar outValue = new outFieldType();\n\nvar inValue = executor.inFields.get(\"TestPing\");\n\nexecutor.logger.info(inValue);\n\noutValue.setPingTime(inValue.getPingTime());\noutValue.setPongTime(new Date().getTime());\noutValue.setName(inValue.getName() + \"_out\");\n\noutValue.setDescription(\ninValue.getDescription() +\n\". So Romeo would, were he not Romeo call'd,\" +\n\" retain that dear perfection which he owes, without that title.\");\n\nexecutor.logger.info(outValue);\nexecutor.outFields.put(\"TestPing\", outValue)\n\nvar returnValueType = Java.type(\"java.lang.Boolean\");\nvar returnValue = new returnValueType(true);" + "logic": "var outFieldType = Java.type(\"org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestPing\");\nvar outValue = new outFieldType();\n\nvar inValue = executor.inFields.get(\"TestPing\");\n\nexecutor.logger.info(inValue);\n\noutValue.setPingTime(inValue.getPingTime());\noutValue.setPongTime(new Date().getTime());\noutValue.setName(inValue.getName() + \"_out\");\n\noutValue.setDescription(\ninValue.getDescription() +\n\". So Romeo would, were he not Romeo call'd,\" +\n\" retain that dear perfection which he owes, without that title.\");\n\nexecutor.logger.info(outValue);\nexecutor.outFields.put(\"TestPing\", outValue)\n\nvar returnValueType = Java.type(\"java.lang.Boolean\");\nvar returnValue = new returnValueType(true);" } } } @@ -366,7 +366,7 @@ "name": "TestPingIncomingEvent", "version": "0.0.1" }, - "nameSpace": "org.onap.policy.apex.apps.uservice.test.adapt.jms", + "nameSpace": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms", "source": "JMS", "target": "Apex", "parameter": { @@ -396,7 +396,7 @@ "name": "TestPingOutgoingEvent", "version": "0.0.1" }, - "nameSpace": "org.onap.policy.apex.apps.uservice.test.adapt.jms", + "nameSpace": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms", "source": "Apex", "target": "JMS", "parameter": { @@ -446,7 +446,7 @@ "version": "0.0.1" }, "schemaFlavour": "Java", - "schemaDefinition": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestPing" + "schemaDefinition": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestPing" } } ] diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSJsonEvent.json index 0d55d8a7d..f8479969b 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSJsonEvent.json @@ -20,7 +20,7 @@ "carrierTechnology": "JMS", "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { - "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", + "initialContextFactory": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", "providerURL": "remote://localhost:5445", "securityPrincipal": "guest", @@ -41,7 +41,7 @@ "carrierTechnology": "JMS", "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { - "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", + "initialContextFactory": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", "providerURL": "remote://localhost:5445", "securityPrincipal": "guest", diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSObjectEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSObjectEvent.json index 228f8ec60..8fea3346b 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSObjectEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSObjectEvent.json @@ -20,7 +20,7 @@ "carrierTechnology": "JMS", "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { - "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", + "initialContextFactory": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", "providerURL": "remote://localhost:5445", "securityPrincipal": "guest", @@ -40,7 +40,7 @@ "carrierTechnology": "JMS", "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { - "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", + "initialContextFactory": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", "providerURL": "remote://localhost:5445", "securityPrincipal": "guest", -- cgit 1.2.3-korg