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 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.awaitility.Awaitility.await;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
29 import com.google.gson.Gson;
30 import java.io.ByteArrayOutputStream;
31 import java.io.IOException;
32 import java.io.PrintStream;
34 import java.util.Random;
35 import java.util.concurrent.TimeUnit;
36 import javax.ws.rs.client.Client;
37 import javax.ws.rs.client.ClientBuilder;
38 import javax.ws.rs.client.Entity;
39 import javax.ws.rs.core.Response;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
43 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
44 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
45 import org.onap.policy.apex.service.engine.main.ApexMain;
46 import org.onap.policy.common.utils.network.NetworkUtil;
47 import org.slf4j.ext.XLogger;
48 import org.slf4j.ext.XLoggerFactory;
51 * The Class TestRestServer.
53 public class TestRestServer {
54 private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRestServer.class);
56 private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
57 private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
59 private final PrintStream stdout = System.out;
60 private final PrintStream stderr = System.err;
62 private static int eventsSent = 0;
65 * Clear relative file root environment variable.
68 public void clearRelativeFileRoot() {
69 System.clearProperty("APEX_RELATIVE_FILE_ROOT");
73 * Test rest server put.
75 * @throws MessagingException the messaging exception
76 * @throws ApexException the apex exception
77 * @throws IOException Signals that an I/O exception has occurred.
78 * @throws InterruptedException interrupted exception
80 @SuppressWarnings("unchecked")
82 public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
83 LOGGER.debug("testRestServerPut start");
85 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
86 final ApexMain apexMain = new ApexMain(args);
87 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
88 throw new IllegalStateException("cannot connect to Apex Rest Server");
90 final Client client = ClientBuilder.newClient();
92 Response response = null;
93 Map<String, Object> jsonMap = null;
95 for (int i = 0; i < 20; i++) {
96 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
97 .put(Entity.json(getEvent()));
99 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
103 final String responseString = response.readEntity(String.class);
105 jsonMap = new Gson().fromJson(responseString, Map.class);
110 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
112 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
113 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
114 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
115 LOGGER.debug("testRestServerPut end");
119 * Test rest server post.
121 * @throws MessagingException the messaging exception
122 * @throws ApexException the apex exception
123 * @throws IOException Signals that an I/O exception has occurred.
124 * @throws InterruptedException interrupted exception
126 @SuppressWarnings("unchecked")
128 public void testRestServerPost() throws MessagingException, ApexException, IOException, InterruptedException {
129 LOGGER.debug("testRestServerPost start");
130 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
131 final ApexMain apexMain = new ApexMain(args);
132 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
133 throw new IllegalStateException("cannot connect to Apex Rest Server");
135 final Client client = ClientBuilder.newClient();
137 Response response = null;
138 Map<String, Object> jsonMap = null;
140 for (int i = 0; i < 20; i++) {
141 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
142 .post(Entity.json(getEvent()));
144 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
148 final String responseString = response.readEntity(String.class);
150 jsonMap = new Gson().fromJson(responseString, Map.class);
155 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
157 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
158 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
159 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
160 LOGGER.debug("testRestServerPost end");
164 * Test rest server get status.
166 * @throws MessagingException the messaging exception
167 * @throws ApexException the apex exception
168 * @throws IOException Signals that an I/O exception has occurred.
169 * @throws InterruptedException interrupted exception
172 public void testRestServerGetStatus() throws MessagingException, ApexException, IOException, InterruptedException {
173 LOGGER.debug("testRestServerGetStatus start");
174 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
175 final ApexMain apexMain = new ApexMain(args);
176 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
177 throw new IllegalStateException("cannot connect to Apex Rest Server");
179 final Client client = ClientBuilder.newClient();
181 Response postResponse = null;
182 Response putResponse = null;
184 // trigger 10 POST & PUT events
185 for (int i = 0; i < 10; i++) {
186 postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
187 .request("application/json").post(Entity.json(getEvent()));
188 if (Response.Status.OK.getStatusCode() != postResponse.getStatus()) {
191 putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
192 .put(Entity.json(getEvent()));
194 if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
199 final Response statResponse =
200 client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
202 final String responseString = statResponse.readEntity(String.class);
206 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
208 assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
209 assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
210 assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
212 @SuppressWarnings("unchecked")
213 final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
214 assertEquals("[FirstConsumer", ((String) jsonMap.get("INPUTS")).substring(0, 14));
215 assertEquals(1.0, jsonMap.get("STAT"));
216 assertTrue((double) jsonMap.get("POST") >= 10.0);
217 assertTrue((double) jsonMap.get("PUT") >= 10.0);
218 LOGGER.debug("testRestServerGetStatus end");
222 * Test rest server multi inputs.
224 * @throws MessagingException the messaging exception
225 * @throws ApexException the apex exception
226 * @throws IOException Signals that an I/O exception has occurred.
227 * @throws InterruptedException interrupted exception
229 @SuppressWarnings("unchecked")
231 public void testRestServerMultiInputs()
232 throws MessagingException, ApexException, IOException, InterruptedException {
233 LOGGER.debug("testRestServerMultiInputs start");
234 final String[] args =
235 {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEventMultiIn.json"};
236 final ApexMain apexMain = new ApexMain(args);
237 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
238 throw new IllegalStateException("cannot connect to Apex Rest Server");
240 final Client client = ClientBuilder.newClient();
242 Response firstResponse = null;
243 Response secondResponse = null;
245 Map<String, Object> firstJsonMap = null;
246 Map<String, Object> secondJsonMap = null;
248 for (int i = 0; i < 20; i++) {
249 firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
250 .request("application/json").post(Entity.json(getEvent()));
252 if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
256 final String firstResponseString = firstResponse.readEntity(String.class);
258 firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
260 secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
261 .request("application/json").post(Entity.json(getEvent()));
263 if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
267 final String secondResponseString = secondResponse.readEntity(String.class);
269 secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
274 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
276 assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus());
277 assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace"));
278 assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan"));
280 assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus());
281 assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace"));
282 assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan"));
283 LOGGER.debug("testRestServerMultiInputs end");
287 * Test rest server producer standalone.
289 * @throws MessagingException the messaging exception
290 * @throws ApexException the apex exception
291 * @throws IOException Signals that an I/O exception has occurred.
292 * @throws InterruptedException interrupted exception
295 public void testRestServerProducerStandalone()
296 throws MessagingException, ApexException, IOException, InterruptedException {
297 LOGGER.debug("testRestServerProducerStandalone start");
298 System.setOut(new PrintStream(outContent));
299 System.setErr(new PrintStream(errContent));
301 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
303 final ApexMain apexMain = new ApexMain(args);
304 ThreadUtilities.sleep(200);
307 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
309 final String outString = outContent.toString();
311 System.setOut(stdout);
312 System.setErr(stderr);
315 .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer"));
316 LOGGER.debug("testRestServerProducerStandalone end");
320 * Test rest server producer host.
322 * @throws MessagingException the messaging exception
323 * @throws ApexException the apex exception
324 * @throws IOException Signals that an I/O exception has occurred.
325 * @throws InterruptedException interrupted exception
328 public void testRestServerProducerHost()
329 throws MessagingException, ApexException, IOException, InterruptedException {
330 LOGGER.debug("testRestServerProducerHost start");
331 System.setOut(new PrintStream(outContent));
332 System.setErr(new PrintStream(errContent));
334 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
336 final ApexMain apexMain = new ApexMain(args);
337 ThreadUtilities.sleep(200);
340 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
342 final String outString = outContent.toString();
344 System.setOut(stdout);
345 System.setErr(stderr);
347 assertTrue(outString.contains(" host is specified only in standalone mode"));
348 LOGGER.debug("testRestServerProducerHost end");
352 * Test rest server producer port.
354 * @throws MessagingException the messaging exception
355 * @throws ApexException the apex exception
356 * @throws IOException Signals that an I/O exception has occurred.
357 * @throws InterruptedException interrupted exception
360 public void testRestServerProducerPort()
361 throws MessagingException, ApexException, IOException, InterruptedException {
362 LOGGER.debug("testRestServerProducerPort start");
363 System.setOut(new PrintStream(outContent));
364 System.setErr(new PrintStream(errContent));
366 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
368 final ApexMain apexMain = new ApexMain(args);
369 ThreadUtilities.sleep(200);
372 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
374 final String outString = outContent.toString();
376 System.setOut(stdout);
377 System.setErr(stderr);
379 assertTrue(outString.contains(" port is specified only in standalone mode"));
380 LOGGER.debug("testRestServerProducerPort end");
384 * Test rest server consumer standalone no host.
386 * @throws MessagingException the messaging exception
387 * @throws ApexException the apex exception
388 * @throws IOException Signals that an I/O exception has occurred.
391 public void testRestServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException {
392 LOGGER.debug("testRestServerConsumerStandaloneNoHost start");
393 System.setOut(new PrintStream(outContent));
394 System.setErr(new PrintStream(errContent));
396 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"};
398 final ApexMain apexMain = new ApexMain(args);
399 ThreadUtilities.sleep(200);
402 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
404 final String outString = outContent.toString();
406 System.setOut(stdout);
407 System.setErr(stderr);
409 assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
410 + "(FirstConsumer) in standalone mode"));
411 LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
415 * Test rest server consumer standalone no port.
417 * @throws MessagingException the messaging exception
418 * @throws ApexException the apex exception
419 * @throws IOException Signals that an I/O exception has occurred.
422 public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException {
423 LOGGER.debug("testRestServerConsumerStandaloneNoPort start");
424 System.setOut(new PrintStream(outContent));
425 System.setErr(new PrintStream(errContent));
427 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
429 final ApexMain apexMain = new ApexMain(args);
430 ThreadUtilities.sleep(200);
433 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
435 final String outString = outContent.toString();
437 System.setOut(stdout);
438 System.setErr(stderr);
440 assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
441 + "(FirstConsumer) in standalone mode"));
442 LOGGER.debug("testRestServerConsumerStandaloneNoPort end");
446 * Test rest server producer not sync.
448 * @throws MessagingException the messaging exception
449 * @throws ApexException the apex exception
450 * @throws IOException Signals that an I/O exception has occurred.
453 public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException {
454 LOGGER.debug("testRestServerProducerNotSync start");
455 System.setOut(new PrintStream(outContent));
456 System.setErr(new PrintStream(errContent));
458 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
460 final ApexMain apexMain = new ApexMain(args);
461 ThreadUtilities.sleep(200);
464 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
466 final String outString = outContent.toString();
468 System.setOut(stdout);
469 System.setErr(stderr);
471 assertTrue(outString.contains(
472 "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer"));
473 LOGGER.debug("testRestServerProducerNotSync end");
477 * Test rest server consumer not sync.
479 * @throws MessagingException the messaging exception
480 * @throws ApexException the apex exception
481 * @throws IOException Signals that an I/O exception has occurred.
484 public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException {
485 LOGGER.debug("testRestServerConsumerNotSync start");
486 System.setOut(new PrintStream(outContent));
487 System.setErr(new PrintStream(errContent));
489 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
491 final ApexMain apexMain = new ApexMain(args);
492 ThreadUtilities.sleep(200);
495 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
497 final String outString = outContent.toString();
499 System.setOut(stdout);
500 System.setErr(stderr);
503 outString.contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined "
504 + "with the same peered mode"));
505 LOGGER.debug("testRestServerConsumerNotSync end");
513 private String getEvent() {
514 final Random rand = new Random();
515 final int nextMatchCase = rand.nextInt(4);
516 final String nextEventName = "Event0" + rand.nextInt(2) + "00";
518 final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
519 + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n"
520 + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
521 + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
522 + "\"TestTemperature\": 9080.866\n" + "}";