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 * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver;
26 import static org.assertj.core.api.Assertions.assertThat;
27 import static org.awaitility.Awaitility.await;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertTrue;
31 import com.google.gson.Gson;
32 import java.io.ByteArrayOutputStream;
33 import java.io.IOException;
34 import java.io.PrintStream;
36 import java.util.Random;
37 import java.util.concurrent.TimeUnit;
38 import javax.ws.rs.client.Client;
39 import javax.ws.rs.client.ClientBuilder;
40 import javax.ws.rs.client.Entity;
41 import javax.ws.rs.core.Response;
42 import org.junit.After;
43 import org.junit.Before;
44 import org.junit.Test;
45 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
46 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
47 import org.onap.policy.apex.service.engine.main.ApexMain;
48 import org.onap.policy.common.utils.network.NetworkUtil;
49 import org.slf4j.ext.XLogger;
50 import org.slf4j.ext.XLoggerFactory;
53 * The Class TestRestServer.
55 public class TestRestServer {
56 private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRestServer.class);
58 private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
59 private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
61 private final PrintStream stdout = System.out;
62 private final PrintStream stderr = System.err;
64 private static int eventsSent = 0;
70 public void beforeTest() {
71 System.clearProperty("APEX_RELATIVE_FILE_ROOT");
72 System.setOut(new PrintStream(outContent));
73 System.setErr(new PrintStream(errContent));
80 public void afterTest() {
81 System.setOut(stdout);
82 System.setErr(stderr);
86 * Test rest server put.
88 * @throws MessagingException the messaging exception
89 * @throws ApexException the apex exception
90 * @throws IOException Signals that an I/O exception has occurred.
91 * @throws InterruptedException interrupted exception
93 @SuppressWarnings("unchecked")
95 public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
96 LOGGER.debug("testRestServerPut start");
98 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
99 final ApexMain apexMain = new ApexMain(args);
100 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
101 throw new IllegalStateException("cannot connect to Apex Rest Server");
103 final Client client = ClientBuilder.newClient();
105 Response response = null;
106 Map<String, Object> jsonMap = null;
108 for (int i = 0; i < 20; i++) {
109 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
110 .put(Entity.json(getEvent()));
112 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
116 final String responseString = response.readEntity(String.class);
118 jsonMap = new Gson().fromJson(responseString, Map.class);
123 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
125 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
126 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
127 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
128 LOGGER.debug("testRestServerPut end");
132 * Test rest server post.
134 * @throws MessagingException the messaging exception
135 * @throws ApexException the apex exception
136 * @throws IOException Signals that an I/O exception has occurred.
137 * @throws InterruptedException interrupted exception
139 @SuppressWarnings("unchecked")
141 public void testRestServerPost() throws MessagingException, ApexException, IOException, InterruptedException {
142 LOGGER.debug("testRestServerPost start");
143 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
144 final ApexMain apexMain = new ApexMain(args);
145 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
146 throw new IllegalStateException("cannot connect to Apex Rest Server");
148 final Client client = ClientBuilder.newClient();
150 Response response = null;
151 Map<String, Object> jsonMap = null;
153 for (int i = 0; i < 20; i++) {
154 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
155 .post(Entity.json(getEvent()));
157 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
161 final String responseString = response.readEntity(String.class);
163 jsonMap = new Gson().fromJson(responseString, Map.class);
168 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
170 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
171 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
172 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
173 LOGGER.debug("testRestServerPost end");
177 * Test rest server get status.
179 * @throws MessagingException the messaging exception
180 * @throws ApexException the apex exception
181 * @throws IOException Signals that an I/O exception has occurred.
182 * @throws InterruptedException interrupted exception
185 public void testRestServerGetStatus() throws MessagingException, ApexException, IOException, InterruptedException {
186 LOGGER.debug("testRestServerGetStatus start");
187 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
188 final ApexMain apexMain = new ApexMain(args);
189 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
190 throw new IllegalStateException("cannot connect to Apex Rest Server");
192 final Client client = ClientBuilder.newClient();
194 Response postResponse = null;
195 Response putResponse = null;
197 // trigger 10 POST & PUT events
198 for (int i = 0; i < 10; i++) {
199 postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
200 .request("application/json").post(Entity.json(getEvent()));
201 if (Response.Status.OK.getStatusCode() != postResponse.getStatus()) {
204 putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
205 .put(Entity.json(getEvent()));
207 if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
212 final Response statResponse =
213 client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
215 final String responseString = statResponse.readEntity(String.class);
219 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
221 assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
222 assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
223 assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
225 @SuppressWarnings("unchecked")
226 final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
227 assertEquals("[FirstConsumer", ((String) jsonMap.get("INPUTS")).substring(0, 14));
228 assertEquals(1.0, jsonMap.get("STAT"));
229 assertTrue((double) jsonMap.get("POST") >= 10.0);
230 assertTrue((double) jsonMap.get("PUT") >= 10.0);
231 LOGGER.debug("testRestServerGetStatus end");
235 * Test rest server multi inputs.
237 * @throws MessagingException the messaging exception
238 * @throws ApexException the apex exception
239 * @throws IOException Signals that an I/O exception has occurred.
240 * @throws InterruptedException interrupted exception
242 @SuppressWarnings("unchecked")
244 public void testRestServerMultiInputs()
245 throws MessagingException, ApexException, IOException, InterruptedException {
246 LOGGER.debug("testRestServerMultiInputs start");
247 final String[] args =
248 {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEventMultiIn.json"};
249 final ApexMain apexMain = new ApexMain(args);
250 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
251 throw new IllegalStateException("cannot connect to Apex Rest Server");
253 final Client client = ClientBuilder.newClient();
255 Response firstResponse = null;
256 Response secondResponse = null;
258 Map<String, Object> firstJsonMap = null;
259 Map<String, Object> secondJsonMap = null;
261 for (int i = 0; i < 20; i++) {
262 firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
263 .request("application/json").post(Entity.json(getEvent()));
265 if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
269 final String firstResponseString = firstResponse.readEntity(String.class);
271 firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
273 secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
274 .request("application/json").post(Entity.json(getEvent()));
276 if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
280 final String secondResponseString = secondResponse.readEntity(String.class);
282 secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
287 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
289 assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus());
290 assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace"));
291 assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan"));
293 assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus());
294 assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace"));
295 assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan"));
296 LOGGER.debug("testRestServerMultiInputs end");
300 * Test rest server producer standalone.
302 * @throws MessagingException the messaging exception
303 * @throws ApexException the apex exception
304 * @throws IOException Signals that an I/O exception has occurred.
305 * @throws InterruptedException interrupted exception
308 public void testRestServerProducerStandalone()
309 throws MessagingException, ApexException, IOException, InterruptedException {
310 LOGGER.debug("testRestServerProducerStandalone start");
311 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
313 final ApexMain apexMain = new ApexMain(args);
316 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
318 final String outString = outContent.toString();
320 assertThat(outString).contains("\"host\" value \"null\" INVALID, is blank");
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\"", "should be 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\"", "should be 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("\"host\" value \"null\" INVALID, is blank");
391 LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
395 * Test rest server consumer standalone no port.
397 * @throws MessagingException the messaging exception
398 * @throws ApexException the apex exception
399 * @throws IOException Signals that an I/O exception has occurred.
402 public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException {
403 LOGGER.debug("testRestServerConsumerStandaloneNoPort start");
404 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
406 final ApexMain apexMain = new ApexMain(args);
409 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
411 final String outString = outContent.toString();
412 assertThat(outString).contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
413 + "(FirstConsumer) in standalone mode");
414 LOGGER.debug("testRestServerConsumerStandaloneNoPort end");
418 * Test rest server producer not sync.
420 * @throws MessagingException the messaging exception
421 * @throws ApexException the apex exception
422 * @throws IOException Signals that an I/O exception has occurred.
425 public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException {
426 LOGGER.debug("testRestServerProducerNotSync start");
427 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
429 final ApexMain apexMain = new ApexMain(args);
432 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
434 final String outString = outContent.toString();
436 assertThat(outString).contains(
437 "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer");
438 LOGGER.debug("testRestServerProducerNotSync end");
442 * Test rest server consumer not sync.
444 * @throws MessagingException the messaging exception
445 * @throws ApexException the apex exception
446 * @throws IOException Signals that an I/O exception has occurred.
449 public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException {
450 LOGGER.debug("testRestServerConsumerNotSync start");
451 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
453 final ApexMain apexMain = new ApexMain(args);
456 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
458 final String outString = outContent.toString();
460 assertThat(outString)
461 .contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined "
462 + "with the same peered mode");
463 LOGGER.debug("testRestServerConsumerNotSync end");
471 private String getEvent() {
472 final Random rand = new Random();
473 final int nextMatchCase = rand.nextInt(4);
474 final String nextEventName = "Event0" + rand.nextInt(2) + "00";
476 final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
477 + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n"
478 + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
479 + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
480 + "\"TestTemperature\": 9080.866\n" + "}";