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;
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;
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;
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.core.infrastructure.threading.ThreadUtilities;
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;
67 * Clear relative file root environment variable.
70 public void clearRelativeFileRoot() {
71 System.clearProperty("APEX_RELATIVE_FILE_ROOT");
75 * Test rest server put.
77 * @throws MessagingException the messaging exception
78 * @throws ApexException the apex exception
79 * @throws IOException Signals that an I/O exception has occurred.
80 * @throws InterruptedException interrupted exception
82 @SuppressWarnings("unchecked")
84 public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
85 LOGGER.debug("testRestServerPut start");
87 final String[] args = {"-rfr", "target", "-c", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
88 final ApexMain apexMain = new ApexMain(args);
89 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
90 throw new IllegalStateException("cannot connect to Apex Rest Server");
92 final Client client = ClientBuilder.newClient();
94 Response response = null;
95 Map<String, Object> jsonMap = null;
97 for (int i = 0; i < 20; i++) {
98 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
99 .put(Entity.json(getEvent()));
101 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
105 final String responseString = response.readEntity(String.class);
107 jsonMap = new Gson().fromJson(responseString, Map.class);
112 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
114 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
115 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
116 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
117 LOGGER.debug("testRestServerPut end");
121 * Test rest server post.
123 * @throws MessagingException the messaging exception
124 * @throws ApexException the apex exception
125 * @throws IOException Signals that an I/O exception has occurred.
126 * @throws InterruptedException interrupted exception
128 @SuppressWarnings("unchecked")
130 public void testRestServerPost() throws MessagingException, ApexException, IOException, InterruptedException {
131 LOGGER.debug("testRestServerPost start");
132 final String[] args = {"-rfr", "target", "-c", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
133 final ApexMain apexMain = new ApexMain(args);
134 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
135 throw new IllegalStateException("cannot connect to Apex Rest Server");
137 final Client client = ClientBuilder.newClient();
139 Response response = null;
140 Map<String, Object> jsonMap = null;
142 for (int i = 0; i < 20; i++) {
143 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
144 .post(Entity.json(getEvent()));
146 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
150 final String responseString = response.readEntity(String.class);
152 jsonMap = new Gson().fromJson(responseString, Map.class);
157 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
159 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
160 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
161 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
162 LOGGER.debug("testRestServerPost end");
166 * Test rest server get status.
168 * @throws MessagingException the messaging exception
169 * @throws ApexException the apex exception
170 * @throws IOException Signals that an I/O exception has occurred.
171 * @throws InterruptedException interrupted exception
174 public void testRestServerGetStatus() throws MessagingException, ApexException, IOException, InterruptedException {
175 LOGGER.debug("testRestServerGetStatus start");
176 final String[] args = {"-rfr", "target", "-c", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
177 final ApexMain apexMain = new ApexMain(args);
178 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
179 throw new IllegalStateException("cannot connect to Apex Rest Server");
181 final Client client = ClientBuilder.newClient();
183 Response postResponse = null;
184 Response putResponse = null;
186 // trigger 10 POST & PUT events
187 for (int i = 0; i < 10; i++) {
188 postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
189 .request("application/json").post(Entity.json(getEvent()));
190 if (Response.Status.OK.getStatusCode() != postResponse.getStatus()) {
193 putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
194 .put(Entity.json(getEvent()));
196 if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
201 final Response statResponse =
202 client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
204 final String responseString = statResponse.readEntity(String.class);
208 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
210 assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
211 assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
212 assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
214 @SuppressWarnings("unchecked")
215 final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
216 assertEquals("[FirstConsumer", ((String) jsonMap.get("INPUTS")).substring(0, 14));
217 assertEquals(1.0, jsonMap.get("STAT"));
218 assertTrue((double) jsonMap.get("POST") >= 10.0);
219 assertTrue((double) jsonMap.get("PUT") >= 10.0);
220 LOGGER.debug("testRestServerGetStatus end");
224 * Test rest server multi inputs.
226 * @throws MessagingException the messaging exception
227 * @throws ApexException the apex exception
228 * @throws IOException Signals that an I/O exception has occurred.
229 * @throws InterruptedException interrupted exception
231 @SuppressWarnings("unchecked")
233 public void testRestServerMultiInputs()
234 throws MessagingException, ApexException, IOException, InterruptedException {
235 LOGGER.debug("testRestServerMultiInputs start");
236 final String[] args =
237 {"-rfr", "target", "-c", "target/examples/config/SampleDomain/RESTServerJsonEventMultiIn.json"};
238 final ApexMain apexMain = new ApexMain(args);
239 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
240 throw new IllegalStateException("cannot connect to Apex Rest Server");
242 final Client client = ClientBuilder.newClient();
244 Response firstResponse = null;
245 Response secondResponse = null;
247 Map<String, Object> firstJsonMap = null;
248 Map<String, Object> secondJsonMap = null;
250 for (int i = 0; i < 20; i++) {
251 firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
252 .request("application/json").post(Entity.json(getEvent()));
254 if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
258 final String firstResponseString = firstResponse.readEntity(String.class);
260 firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
262 secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
263 .request("application/json").post(Entity.json(getEvent()));
265 if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
269 final String secondResponseString = secondResponse.readEntity(String.class);
271 secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
276 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
278 assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus());
279 assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace"));
280 assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan"));
282 assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus());
283 assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace"));
284 assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan"));
285 LOGGER.debug("testRestServerMultiInputs end");
289 * Test rest server producer standalone.
291 * @throws MessagingException the messaging exception
292 * @throws ApexException the apex exception
293 * @throws IOException Signals that an I/O exception has occurred.
294 * @throws InterruptedException interrupted exception
297 public void testRestServerProducerStandalone()
298 throws MessagingException, ApexException, IOException, InterruptedException {
299 LOGGER.debug("testRestServerProducerStandalone start");
300 System.setOut(new PrintStream(outContent));
301 System.setErr(new PrintStream(errContent));
303 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
305 final ApexMain apexMain = new ApexMain(args);
306 ThreadUtilities.sleep(200);
309 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
311 final String outString = outContent.toString();
313 System.setOut(stdout);
314 System.setErr(stderr);
317 .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer"));
318 LOGGER.debug("testRestServerProducerStandalone end");
322 * Test rest server producer host.
324 * @throws MessagingException the messaging exception
325 * @throws ApexException the apex exception
326 * @throws IOException Signals that an I/O exception has occurred.
327 * @throws InterruptedException interrupted exception
330 public void testRestServerProducerHost()
331 throws MessagingException, ApexException, IOException, InterruptedException {
332 LOGGER.debug("testRestServerProducerHost start");
333 System.setOut(new PrintStream(outContent));
334 System.setErr(new PrintStream(errContent));
336 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
338 final ApexMain apexMain = new ApexMain(args);
339 ThreadUtilities.sleep(200);
342 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
344 final String outString = outContent.toString();
346 System.setOut(stdout);
347 System.setErr(stderr);
349 assertTrue(outString.contains(" host is specified only in standalone mode"));
350 LOGGER.debug("testRestServerProducerHost end");
354 * Test rest server producer port.
356 * @throws MessagingException the messaging exception
357 * @throws ApexException the apex exception
358 * @throws IOException Signals that an I/O exception has occurred.
359 * @throws InterruptedException interrupted exception
362 public void testRestServerProducerPort()
363 throws MessagingException, ApexException, IOException, InterruptedException {
364 LOGGER.debug("testRestServerProducerPort start");
365 System.setOut(new PrintStream(outContent));
366 System.setErr(new PrintStream(errContent));
368 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
370 final ApexMain apexMain = new ApexMain(args);
371 ThreadUtilities.sleep(200);
374 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
376 final String outString = outContent.toString();
378 System.setOut(stdout);
379 System.setErr(stderr);
381 assertTrue(outString.contains(" port is specified only in standalone mode"));
382 LOGGER.debug("testRestServerProducerPort end");
386 * Test rest server consumer standalone no host.
388 * @throws MessagingException the messaging exception
389 * @throws ApexException the apex exception
390 * @throws IOException Signals that an I/O exception has occurred.
393 public void testRestServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException {
394 LOGGER.debug("testRestServerConsumerStandaloneNoHost start");
395 System.setOut(new PrintStream(outContent));
396 System.setErr(new PrintStream(errContent));
398 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"};
400 final ApexMain apexMain = new ApexMain(args);
401 ThreadUtilities.sleep(200);
404 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
406 final String outString = outContent.toString();
408 System.setOut(stdout);
409 System.setErr(stderr);
411 assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
412 + "(FirstConsumer) in standalone mode"));
413 LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
417 * Test rest server consumer standalone no port.
419 * @throws MessagingException the messaging exception
420 * @throws ApexException the apex exception
421 * @throws IOException Signals that an I/O exception has occurred.
424 public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException {
425 LOGGER.debug("testRestServerConsumerStandaloneNoPort start");
426 System.setOut(new PrintStream(outContent));
427 System.setErr(new PrintStream(errContent));
429 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
431 final ApexMain apexMain = new ApexMain(args);
432 ThreadUtilities.sleep(200);
435 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
437 final String outString = outContent.toString();
439 System.setOut(stdout);
440 System.setErr(stderr);
442 assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
443 + "(FirstConsumer) in standalone mode"));
444 LOGGER.debug("testRestServerConsumerStandaloneNoPort end");
448 * Test rest server producer not sync.
450 * @throws MessagingException the messaging exception
451 * @throws ApexException the apex exception
452 * @throws IOException Signals that an I/O exception has occurred.
455 public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException {
456 LOGGER.debug("testRestServerProducerNotSync start");
457 System.setOut(new PrintStream(outContent));
458 System.setErr(new PrintStream(errContent));
460 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
462 final ApexMain apexMain = new ApexMain(args);
463 ThreadUtilities.sleep(200);
466 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
468 final String outString = outContent.toString();
470 System.setOut(stdout);
471 System.setErr(stderr);
473 assertTrue(outString.contains(
474 "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer"));
475 LOGGER.debug("testRestServerProducerNotSync end");
479 * Test rest server consumer not sync.
481 * @throws MessagingException the messaging exception
482 * @throws ApexException the apex exception
483 * @throws IOException Signals that an I/O exception has occurred.
486 public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException {
487 LOGGER.debug("testRestServerConsumerNotSync start");
488 System.setOut(new PrintStream(outContent));
489 System.setErr(new PrintStream(errContent));
491 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
493 final ApexMain apexMain = new ApexMain(args);
494 ThreadUtilities.sleep(200);
497 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
499 final String outString = outContent.toString();
501 System.setOut(stdout);
502 System.setErr(stderr);
505 outString.contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined "
506 + "with the same peered mode"));
507 LOGGER.debug("testRestServerConsumerNotSync end");
515 private String getEvent() {
516 final Random rand = new Random();
517 final int nextMatchCase = rand.nextInt(4);
518 final String nextEventName = "Event0" + rand.nextInt(2) + "00";
520 final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
521 + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n"
522 + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
523 + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
524 + "\"TestTemperature\": 9080.866\n" + "}";