2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019-2020 Nordix Foundation.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertTrue;
28 import com.google.gson.Gson;
29 import java.io.ByteArrayOutputStream;
30 import java.io.IOException;
31 import java.io.PrintStream;
33 import java.util.Random;
34 import java.util.concurrent.TimeUnit;
35 import javax.ws.rs.client.Client;
36 import javax.ws.rs.client.ClientBuilder;
37 import javax.ws.rs.client.Entity;
38 import javax.ws.rs.core.Response;
39 import org.junit.Before;
40 import org.junit.Test;
41 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
42 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
43 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
44 import org.onap.policy.apex.service.engine.main.ApexMain;
45 import org.onap.policy.common.utils.network.NetworkUtil;
46 import org.slf4j.ext.XLogger;
47 import org.slf4j.ext.XLoggerFactory;
50 * The Class TestRestServer.
52 public class TestRestServer {
53 private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRestServer.class);
55 private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
56 private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
58 private final PrintStream stdout = System.out;
59 private final PrintStream stderr = System.err;
61 private static int eventsSent = 0;
64 * Clear relative file root environment variable.
67 public void clearRelativeFileRoot() {
68 System.clearProperty("APEX_RELATIVE_FILE_ROOT");
72 * Test rest server put.
74 * @throws MessagingException the messaging exception
75 * @throws ApexException the apex exception
76 * @throws IOException Signals that an I/O exception has occurred.
77 * @throws InterruptedException interrupted exception
79 @SuppressWarnings("unchecked")
81 public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
82 LOGGER.debug("testRestServerPut start");
84 final String[] args = {"-rfr", "target", "-c", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
85 final ApexMain apexMain = new ApexMain(args);
86 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
87 throw new IllegalStateException("cannot connect to Apex Rest Server");
89 final Client client = ClientBuilder.newClient();
91 Response response = null;
92 Map<String, Object> jsonMap = null;
94 for (int i = 0; i < 20; i++) {
95 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
96 .put(Entity.json(getEvent()));
98 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
102 final String responseString = response.readEntity(String.class);
104 jsonMap = new Gson().fromJson(responseString, Map.class);
109 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
111 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
112 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
113 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
114 LOGGER.debug("testRestServerPut end");
118 * Test rest server post.
120 * @throws MessagingException the messaging exception
121 * @throws ApexException the apex exception
122 * @throws IOException Signals that an I/O exception has occurred.
123 * @throws InterruptedException interrupted exception
125 @SuppressWarnings("unchecked")
127 public void testRestServerPost() throws MessagingException, ApexException, IOException, InterruptedException {
128 LOGGER.debug("testRestServerPost start");
129 final String[] args = {"-rfr", "target", "-c", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
130 final ApexMain apexMain = new ApexMain(args);
131 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
132 throw new IllegalStateException("cannot connect to Apex Rest Server");
134 final Client client = ClientBuilder.newClient();
136 Response response = null;
137 Map<String, Object> jsonMap = null;
139 for (int i = 0; i < 20; i++) {
140 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
141 .post(Entity.json(getEvent()));
143 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
147 final String responseString = response.readEntity(String.class);
149 jsonMap = new Gson().fromJson(responseString, Map.class);
154 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
156 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
157 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
158 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
159 LOGGER.debug("testRestServerPost end");
163 * Test rest server get status.
165 * @throws MessagingException the messaging exception
166 * @throws ApexException the apex exception
167 * @throws IOException Signals that an I/O exception has occurred.
168 * @throws InterruptedException interrupted exception
171 public void testRestServerGetStatus() throws MessagingException, ApexException, IOException, InterruptedException {
172 LOGGER.debug("testRestServerGetStatus start");
173 final String[] args = {"-rfr", "target", "-c", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
174 final ApexMain apexMain = new ApexMain(args);
175 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
176 throw new IllegalStateException("cannot connect to Apex Rest Server");
178 final Client client = ClientBuilder.newClient();
180 Response postResponse = null;
181 Response putResponse = null;
183 // trigger 10 POST & PUT events
184 for (int i = 0; i < 10; i++) {
185 postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
186 .request("application/json").post(Entity.json(getEvent()));
187 if (Response.Status.OK.getStatusCode() != postResponse.getStatus()) {
190 putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
191 .put(Entity.json(getEvent()));
193 if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
198 final Response statResponse =
199 client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
201 final String responseString = statResponse.readEntity(String.class);
205 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
207 assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
208 assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
209 assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
211 @SuppressWarnings("unchecked")
212 final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
213 assertEquals("[FirstConsumer", ((String) jsonMap.get("INPUTS")).substring(0, 14));
214 assertEquals(1.0, jsonMap.get("STAT"));
215 assertTrue((double) jsonMap.get("POST") >= 10.0);
216 assertTrue((double) jsonMap.get("PUT") >= 10.0);
217 LOGGER.debug("testRestServerGetStatus end");
221 * Test rest server multi inputs.
223 * @throws MessagingException the messaging exception
224 * @throws ApexException the apex exception
225 * @throws IOException Signals that an I/O exception has occurred.
226 * @throws InterruptedException interrupted exception
228 @SuppressWarnings("unchecked")
230 public void testRestServerMultiInputs()
231 throws MessagingException, ApexException, IOException, InterruptedException {
232 LOGGER.debug("testRestServerMultiInputs start");
233 final String[] args =
234 {"-rfr", "target", "-c", "target/examples/config/SampleDomain/RESTServerJsonEventMultiIn.json"};
235 final ApexMain apexMain = new ApexMain(args);
236 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
237 throw new IllegalStateException("cannot connect to Apex Rest Server");
239 final Client client = ClientBuilder.newClient();
241 Response firstResponse = null;
242 Response secondResponse = null;
244 Map<String, Object> firstJsonMap = null;
245 Map<String, Object> secondJsonMap = null;
247 for (int i = 0; i < 20; i++) {
248 firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
249 .request("application/json").post(Entity.json(getEvent()));
251 if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
255 final String firstResponseString = firstResponse.readEntity(String.class);
257 firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
259 secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
260 .request("application/json").post(Entity.json(getEvent()));
262 if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
266 final String secondResponseString = secondResponse.readEntity(String.class);
268 secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
273 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
275 assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus());
276 assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace"));
277 assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan"));
279 assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus());
280 assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace"));
281 assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan"));
282 LOGGER.debug("testRestServerMultiInputs end");
286 * Test rest server producer standalone.
288 * @throws MessagingException the messaging exception
289 * @throws ApexException the apex exception
290 * @throws IOException Signals that an I/O exception has occurred.
291 * @throws InterruptedException interrupted exception
294 public void testRestServerProducerStandalone()
295 throws MessagingException, ApexException, IOException, InterruptedException {
296 LOGGER.debug("testRestServerProducerStandalone start");
297 System.setOut(new PrintStream(outContent));
298 System.setErr(new PrintStream(errContent));
300 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
302 final ApexMain apexMain = new ApexMain(args);
303 ThreadUtilities.sleep(200);
306 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
308 final String outString = outContent.toString();
310 System.setOut(stdout);
311 System.setErr(stderr);
314 .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer"));
315 LOGGER.debug("testRestServerProducerStandalone end");
319 * Test rest server producer host.
321 * @throws MessagingException the messaging exception
322 * @throws ApexException the apex exception
323 * @throws IOException Signals that an I/O exception has occurred.
324 * @throws InterruptedException interrupted exception
327 public void testRestServerProducerHost()
328 throws MessagingException, ApexException, IOException, InterruptedException {
329 LOGGER.debug("testRestServerProducerHost start");
330 System.setOut(new PrintStream(outContent));
331 System.setErr(new PrintStream(errContent));
333 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
335 final ApexMain apexMain = new ApexMain(args);
336 ThreadUtilities.sleep(200);
339 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
341 final String outString = outContent.toString();
343 System.setOut(stdout);
344 System.setErr(stderr);
346 assertTrue(outString.contains(" host is specified only in standalone mode"));
347 LOGGER.debug("testRestServerProducerHost end");
351 * Test rest server producer port.
353 * @throws MessagingException the messaging exception
354 * @throws ApexException the apex exception
355 * @throws IOException Signals that an I/O exception has occurred.
356 * @throws InterruptedException interrupted exception
359 public void testRestServerProducerPort()
360 throws MessagingException, ApexException, IOException, InterruptedException {
361 LOGGER.debug("testRestServerProducerPort start");
362 System.setOut(new PrintStream(outContent));
363 System.setErr(new PrintStream(errContent));
365 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
367 final ApexMain apexMain = new ApexMain(args);
368 ThreadUtilities.sleep(200);
371 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
373 final String outString = outContent.toString();
375 System.setOut(stdout);
376 System.setErr(stderr);
378 assertTrue(outString.contains(" port is specified only in standalone mode"));
379 LOGGER.debug("testRestServerProducerPort end");
383 * Test rest server consumer standalone no host.
385 * @throws MessagingException the messaging exception
386 * @throws ApexException the apex exception
387 * @throws IOException Signals that an I/O exception has occurred.
390 public void testRestServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException {
391 LOGGER.debug("testRestServerConsumerStandaloneNoHost start");
392 System.setOut(new PrintStream(outContent));
393 System.setErr(new PrintStream(errContent));
395 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"};
397 final ApexMain apexMain = new ApexMain(args);
398 ThreadUtilities.sleep(200);
401 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
403 final String outString = outContent.toString();
405 System.setOut(stdout);
406 System.setErr(stderr);
408 assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
409 + "(FirstConsumer) in standalone mode"));
410 LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
414 * Test rest server consumer standalone no port.
416 * @throws MessagingException the messaging exception
417 * @throws ApexException the apex exception
418 * @throws IOException Signals that an I/O exception has occurred.
421 public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException {
422 LOGGER.debug("testRestServerConsumerStandaloneNoPort start");
423 System.setOut(new PrintStream(outContent));
424 System.setErr(new PrintStream(errContent));
426 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
428 final ApexMain apexMain = new ApexMain(args);
429 ThreadUtilities.sleep(200);
432 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
434 final String outString = outContent.toString();
436 System.setOut(stdout);
437 System.setErr(stderr);
439 assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
440 + "(FirstConsumer) in standalone mode"));
441 LOGGER.debug("testRestServerConsumerStandaloneNoPort end");
445 * Test rest server producer not sync.
447 * @throws MessagingException the messaging exception
448 * @throws ApexException the apex exception
449 * @throws IOException Signals that an I/O exception has occurred.
452 public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException {
453 LOGGER.debug("testRestServerProducerNotSync start");
454 System.setOut(new PrintStream(outContent));
455 System.setErr(new PrintStream(errContent));
457 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
459 final ApexMain apexMain = new ApexMain(args);
460 ThreadUtilities.sleep(200);
463 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
465 final String outString = outContent.toString();
467 System.setOut(stdout);
468 System.setErr(stderr);
470 assertTrue(outString.contains(
471 "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer"));
472 LOGGER.debug("testRestServerProducerNotSync end");
476 * Test rest server consumer not sync.
478 * @throws MessagingException the messaging exception
479 * @throws ApexException the apex exception
480 * @throws IOException Signals that an I/O exception has occurred.
483 public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException {
484 LOGGER.debug("testRestServerConsumerNotSync start");
485 System.setOut(new PrintStream(outContent));
486 System.setErr(new PrintStream(errContent));
488 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
490 final ApexMain apexMain = new ApexMain(args);
491 ThreadUtilities.sleep(200);
494 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
496 final String outString = outContent.toString();
498 System.setOut(stdout);
499 System.setErr(stderr);
502 outString.contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined "
503 + "with the same peered mode"));
504 LOGGER.debug("testRestServerConsumerNotSync end");
512 private String getEvent() {
513 final Random rand = new Random();
514 final int nextMatchCase = rand.nextInt(4);
515 final String nextEventName = "Event0" + rand.nextInt(2) + "00";
517 final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
518 + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n"
519 + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
520 + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
521 + "\"TestTemperature\": 9080.866\n" + "}";