2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019-2020 Nordix Foundation.
5 * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver;
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.awaitility.Awaitility.await;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertTrue;
30 import com.google.gson.Gson;
31 import java.io.ByteArrayOutputStream;
32 import java.io.IOException;
33 import java.io.PrintStream;
35 import java.util.Random;
36 import java.util.concurrent.TimeUnit;
37 import javax.ws.rs.client.Client;
38 import javax.ws.rs.client.ClientBuilder;
39 import javax.ws.rs.client.Entity;
40 import javax.ws.rs.core.Response;
41 import org.junit.After;
42 import org.junit.Before;
43 import org.junit.Test;
44 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
45 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
46 import org.onap.policy.apex.service.engine.main.ApexMain;
47 import org.onap.policy.common.utils.network.NetworkUtil;
48 import org.slf4j.ext.XLogger;
49 import org.slf4j.ext.XLoggerFactory;
52 * The Class TestRestServer.
54 public class TestRestServer {
55 private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRestServer.class);
57 private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
58 private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
60 private final PrintStream stdout = System.out;
61 private final PrintStream stderr = System.err;
63 private static int eventsSent = 0;
69 public void beforeTest() {
70 System.clearProperty("APEX_RELATIVE_FILE_ROOT");
71 System.setOut(new PrintStream(outContent));
72 System.setErr(new PrintStream(errContent));
79 public void afterTest() {
80 System.setOut(stdout);
81 System.setErr(stderr);
85 * Test rest server put.
87 * @throws MessagingException the messaging exception
88 * @throws ApexException the apex exception
89 * @throws IOException Signals that an I/O exception has occurred.
90 * @throws InterruptedException interrupted exception
92 @SuppressWarnings("unchecked")
94 public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
95 LOGGER.debug("testRestServerPut start");
97 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
98 final ApexMain apexMain = new ApexMain(args);
99 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
100 throw new IllegalStateException("cannot connect to Apex Rest Server");
102 final Client client = ClientBuilder.newClient();
104 Response response = null;
105 Map<String, Object> jsonMap = null;
107 for (int i = 0; i < 20; i++) {
108 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
109 .put(Entity.json(getEvent()));
111 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
115 final String responseString = response.readEntity(String.class);
117 jsonMap = new Gson().fromJson(responseString, Map.class);
122 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
124 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
125 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
126 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
127 LOGGER.debug("testRestServerPut end");
131 * Test rest server post.
133 * @throws MessagingException the messaging exception
134 * @throws ApexException the apex exception
135 * @throws IOException Signals that an I/O exception has occurred.
136 * @throws InterruptedException interrupted exception
138 @SuppressWarnings("unchecked")
140 public void testRestServerPost() throws MessagingException, ApexException, IOException, InterruptedException {
141 LOGGER.debug("testRestServerPost start");
142 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
143 final ApexMain apexMain = new ApexMain(args);
144 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
145 throw new IllegalStateException("cannot connect to Apex Rest Server");
147 final Client client = ClientBuilder.newClient();
149 Response response = null;
150 Map<String, Object> jsonMap = null;
152 for (int i = 0; i < 20; i++) {
153 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
154 .post(Entity.json(getEvent()));
156 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
160 final String responseString = response.readEntity(String.class);
162 jsonMap = new Gson().fromJson(responseString, Map.class);
167 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
169 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
170 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
171 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
172 LOGGER.debug("testRestServerPost end");
176 * Test rest server get status.
178 * @throws MessagingException the messaging exception
179 * @throws ApexException the apex exception
180 * @throws IOException Signals that an I/O exception has occurred.
181 * @throws InterruptedException interrupted exception
184 public void testRestServerGetStatus() throws MessagingException, ApexException, IOException, InterruptedException {
185 LOGGER.debug("testRestServerGetStatus start");
186 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
187 final ApexMain apexMain = new ApexMain(args);
188 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
189 throw new IllegalStateException("cannot connect to Apex Rest Server");
191 final Client client = ClientBuilder.newClient();
193 Response postResponse = null;
194 Response putResponse = null;
196 // trigger 10 POST & PUT events
197 for (int i = 0; i < 10; i++) {
198 postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
199 .request("application/json").post(Entity.json(getEvent()));
200 if (Response.Status.OK.getStatusCode() != postResponse.getStatus()) {
203 putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
204 .put(Entity.json(getEvent()));
206 if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
211 final Response statResponse =
212 client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
214 final String responseString = statResponse.readEntity(String.class);
218 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
220 assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
221 assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
222 assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
224 @SuppressWarnings("unchecked")
225 final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
226 assertEquals("[FirstConsumer", ((String) jsonMap.get("INPUTS")).substring(0, 14));
227 assertEquals(1.0, jsonMap.get("STAT"));
228 assertTrue((double) jsonMap.get("POST") >= 10.0);
229 assertTrue((double) jsonMap.get("PUT") >= 10.0);
230 LOGGER.debug("testRestServerGetStatus end");
234 * Test rest server multi inputs.
236 * @throws MessagingException the messaging exception
237 * @throws ApexException the apex exception
238 * @throws IOException Signals that an I/O exception has occurred.
239 * @throws InterruptedException interrupted exception
241 @SuppressWarnings("unchecked")
243 public void testRestServerMultiInputs()
244 throws MessagingException, ApexException, IOException, InterruptedException {
245 LOGGER.debug("testRestServerMultiInputs start");
246 final String[] args =
247 {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEventMultiIn.json"};
248 final ApexMain apexMain = new ApexMain(args);
249 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
250 throw new IllegalStateException("cannot connect to Apex Rest Server");
252 final Client client = ClientBuilder.newClient();
254 Response firstResponse = null;
255 Response secondResponse = null;
257 Map<String, Object> firstJsonMap = null;
258 Map<String, Object> secondJsonMap = null;
260 for (int i = 0; i < 20; i++) {
261 firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
262 .request("application/json").post(Entity.json(getEvent()));
264 if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
268 final String firstResponseString = firstResponse.readEntity(String.class);
270 firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
272 secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
273 .request("application/json").post(Entity.json(getEvent()));
275 if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
279 final String secondResponseString = secondResponse.readEntity(String.class);
281 secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
286 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
288 assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus());
289 assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace"));
290 assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan"));
292 assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus());
293 assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace"));
294 assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan"));
295 LOGGER.debug("testRestServerMultiInputs end");
299 * Test rest server producer standalone.
301 * @throws MessagingException the messaging exception
302 * @throws ApexException the apex exception
303 * @throws IOException Signals that an I/O exception has occurred.
304 * @throws InterruptedException interrupted exception
307 public void testRestServerProducerStandalone()
308 throws MessagingException, ApexException, IOException, InterruptedException {
309 LOGGER.debug("testRestServerProducerStandalone start");
310 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
312 final ApexMain apexMain = new ApexMain(args);
315 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
317 final String outString = outContent.toString();
319 assertThat(outString)
320 .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer");
321 LOGGER.debug("testRestServerProducerStandalone end");
325 * Test rest server producer host.
327 * @throws MessagingException the messaging exception
328 * @throws ApexException the apex exception
329 * @throws IOException Signals that an I/O exception has occurred.
330 * @throws InterruptedException interrupted exception
333 public void testRestServerProducerHost()
334 throws MessagingException, ApexException, IOException, InterruptedException {
335 LOGGER.debug("testRestServerProducerHost start");
336 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
338 final ApexMain apexMain = new ApexMain(args);
341 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
343 final String outString = outContent.toString();
344 assertThat(outString).contains(" host is specified only in standalone mode");
345 LOGGER.debug("testRestServerProducerHost end");
349 * Test rest server producer port.
351 * @throws MessagingException the messaging exception
352 * @throws ApexException the apex exception
353 * @throws IOException Signals that an I/O exception has occurred.
354 * @throws InterruptedException interrupted exception
357 public void testRestServerProducerPort()
358 throws MessagingException, ApexException, IOException, InterruptedException {
359 LOGGER.debug("testRestServerProducerPort start");
360 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
362 final ApexMain apexMain = new ApexMain(args);
365 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
367 final String outString = outContent.toString();
368 assertThat(outString).contains(" port is specified only in standalone mode");
369 LOGGER.debug("testRestServerProducerPort end");
373 * Test rest server consumer standalone no host.
375 * @throws MessagingException the messaging exception
376 * @throws ApexException the apex exception
377 * @throws IOException Signals that an I/O exception has occurred.
380 public void testRestServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException {
381 LOGGER.debug("testRestServerConsumerStandaloneNoHost start");
382 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"};
384 final ApexMain apexMain = new ApexMain(args);
387 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
389 final String outString = outContent.toString();
390 assertThat(outString).contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
391 + "(FirstConsumer) in standalone mode");
392 LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
396 * Test rest server consumer standalone no port.
398 * @throws MessagingException the messaging exception
399 * @throws ApexException the apex exception
400 * @throws IOException Signals that an I/O exception has occurred.
403 public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException {
404 LOGGER.debug("testRestServerConsumerStandaloneNoPort start");
405 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
407 final ApexMain apexMain = new ApexMain(args);
410 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
412 final String outString = outContent.toString();
413 assertThat(outString).contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
414 + "(FirstConsumer) in standalone mode");
415 LOGGER.debug("testRestServerConsumerStandaloneNoPort end");
419 * Test rest server producer not sync.
421 * @throws MessagingException the messaging exception
422 * @throws ApexException the apex exception
423 * @throws IOException Signals that an I/O exception has occurred.
426 public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException {
427 LOGGER.debug("testRestServerProducerNotSync start");
428 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
430 final ApexMain apexMain = new ApexMain(args);
433 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
435 final String outString = outContent.toString();
437 assertThat(outString).contains(
438 "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer");
439 LOGGER.debug("testRestServerProducerNotSync end");
443 * Test rest server consumer not sync.
445 * @throws MessagingException the messaging exception
446 * @throws ApexException the apex exception
447 * @throws IOException Signals that an I/O exception has occurred.
450 public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException {
451 LOGGER.debug("testRestServerConsumerNotSync start");
452 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
454 final ApexMain apexMain = new ApexMain(args);
457 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
459 final String outString = outContent.toString();
461 assertThat(outString)
462 .contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined "
463 + "with the same peered mode");
464 LOGGER.debug("testRestServerConsumerNotSync end");
472 private String getEvent() {
473 final Random rand = new Random();
474 final int nextMatchCase = rand.nextInt(4);
475 final String nextEventName = "Event0" + rand.nextInt(2) + "00";
477 final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
478 + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n"
479 + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
480 + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
481 + "\"TestTemperature\": 9080.866\n" + "}";