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.assertThatThrownBy;
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.Before;
42 import org.junit.Test;
43 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
44 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
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;
66 * Clear relative file root environment variable.
69 public void clearRelativeFileRoot() {
70 System.clearProperty("APEX_RELATIVE_FILE_ROOT");
74 * Test rest server put.
76 * @throws MessagingException the messaging exception
77 * @throws ApexException the apex exception
78 * @throws IOException Signals that an I/O exception has occurred.
79 * @throws InterruptedException interrupted exception
81 @SuppressWarnings("unchecked")
83 public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
84 LOGGER.debug("testRestServerPut start");
86 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
87 final ApexMain apexMain = new ApexMain(args);
88 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
89 throw new IllegalStateException("cannot connect to Apex Rest Server");
91 final Client client = ClientBuilder.newClient();
93 Response response = null;
94 Map<String, Object> jsonMap = null;
96 for (int i = 0; i < 20; i++) {
97 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
98 .put(Entity.json(getEvent()));
100 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
104 final String responseString = response.readEntity(String.class);
106 jsonMap = new Gson().fromJson(responseString, Map.class);
111 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
113 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
114 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
115 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
116 LOGGER.debug("testRestServerPut end");
120 * Test rest server post.
122 * @throws MessagingException the messaging exception
123 * @throws ApexException the apex exception
124 * @throws IOException Signals that an I/O exception has occurred.
125 * @throws InterruptedException interrupted exception
127 @SuppressWarnings("unchecked")
129 public void testRestServerPost() throws MessagingException, ApexException, IOException, InterruptedException {
130 LOGGER.debug("testRestServerPost start");
131 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
132 final ApexMain apexMain = new ApexMain(args);
133 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
134 throw new IllegalStateException("cannot connect to Apex Rest Server");
136 final Client client = ClientBuilder.newClient();
138 Response response = null;
139 Map<String, Object> jsonMap = null;
141 for (int i = 0; i < 20; i++) {
142 response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
143 .post(Entity.json(getEvent()));
145 if (Response.Status.OK.getStatusCode() != response.getStatus()) {
149 final String responseString = response.readEntity(String.class);
151 jsonMap = new Gson().fromJson(responseString, Map.class);
156 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
158 assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
159 assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
160 assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
161 LOGGER.debug("testRestServerPost end");
165 * Test rest server get status.
167 * @throws MessagingException the messaging exception
168 * @throws ApexException the apex exception
169 * @throws IOException Signals that an I/O exception has occurred.
170 * @throws InterruptedException interrupted exception
173 public void testRestServerGetStatus() throws MessagingException, ApexException, IOException, InterruptedException {
174 LOGGER.debug("testRestServerGetStatus start");
175 final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
176 final ApexMain apexMain = new ApexMain(args);
177 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
178 throw new IllegalStateException("cannot connect to Apex Rest Server");
180 final Client client = ClientBuilder.newClient();
182 Response postResponse = null;
183 Response putResponse = null;
185 // trigger 10 POST & PUT events
186 for (int i = 0; i < 10; i++) {
187 postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
188 .request("application/json").post(Entity.json(getEvent()));
189 if (Response.Status.OK.getStatusCode() != postResponse.getStatus()) {
192 putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
193 .put(Entity.json(getEvent()));
195 if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
200 final Response statResponse =
201 client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
203 final String responseString = statResponse.readEntity(String.class);
207 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
209 assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
210 assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
211 assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
213 @SuppressWarnings("unchecked")
214 final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
215 assertEquals("[FirstConsumer", ((String) jsonMap.get("INPUTS")).substring(0, 14));
216 assertEquals(1.0, jsonMap.get("STAT"));
217 assertTrue((double) jsonMap.get("POST") >= 10.0);
218 assertTrue((double) jsonMap.get("PUT") >= 10.0);
219 LOGGER.debug("testRestServerGetStatus end");
223 * Test rest server multi inputs.
225 * @throws MessagingException the messaging exception
226 * @throws ApexException the apex exception
227 * @throws IOException Signals that an I/O exception has occurred.
228 * @throws InterruptedException interrupted exception
230 @SuppressWarnings("unchecked")
232 public void testRestServerMultiInputs()
233 throws MessagingException, ApexException, IOException, InterruptedException {
234 LOGGER.debug("testRestServerMultiInputs start");
235 final String[] args =
236 {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEventMultiIn.json"};
237 final ApexMain apexMain = new ApexMain(args);
238 if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
239 throw new IllegalStateException("cannot connect to Apex Rest Server");
241 final Client client = ClientBuilder.newClient();
243 Response firstResponse = null;
244 Response secondResponse = null;
246 Map<String, Object> firstJsonMap = null;
247 Map<String, Object> secondJsonMap = null;
249 for (int i = 0; i < 20; i++) {
250 firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
251 .request("application/json").post(Entity.json(getEvent()));
253 if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
257 final String firstResponseString = firstResponse.readEntity(String.class);
259 firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
261 secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
262 .request("application/json").post(Entity.json(getEvent()));
264 if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
268 final String secondResponseString = secondResponse.readEntity(String.class);
270 secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
275 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
277 assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus());
278 assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace"));
279 assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan"));
281 assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus());
282 assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace"));
283 assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan"));
284 LOGGER.debug("testRestServerMultiInputs end");
288 * Test rest server producer standalone.
291 public void testRestServerProducerStandalone() {
292 LOGGER.debug("testRestServerProducerStandalone start");
293 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
294 assertThatThrownBy(() -> new ApexMain(args))
295 .hasRootCauseMessage("the parameters \"host\", \"port\", and \"standalone\" are illegal"
296 + " on REST Server producer (FirstProducer)");
300 * Test rest server producer host.
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 testRestServerProducerHost()
309 throws MessagingException, ApexException, IOException, InterruptedException {
310 LOGGER.debug("testRestServerProducerHost start");
311 System.setOut(new PrintStream(outContent));
312 System.setErr(new PrintStream(errContent));
314 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
316 final ApexMain apexMain = new ApexMain(args);
317 ThreadUtilities.sleep(200);
320 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
322 final String outString = outContent.toString();
324 System.setOut(stdout);
325 System.setErr(stderr);
327 assertTrue(outString.contains(" host is specified only in standalone mode"));
328 LOGGER.debug("testRestServerProducerHost end");
332 * Test rest server producer port.
334 * @throws MessagingException the messaging exception
335 * @throws ApexException the apex exception
336 * @throws IOException Signals that an I/O exception has occurred.
337 * @throws InterruptedException interrupted exception
340 public void testRestServerProducerPort()
341 throws MessagingException, ApexException, IOException, InterruptedException {
342 LOGGER.debug("testRestServerProducerPort start");
343 System.setOut(new PrintStream(outContent));
344 System.setErr(new PrintStream(errContent));
346 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
348 final ApexMain apexMain = new ApexMain(args);
349 ThreadUtilities.sleep(200);
352 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
354 final String outString = outContent.toString();
356 System.setOut(stdout);
357 System.setErr(stderr);
359 assertTrue(outString.contains(" port is specified only in standalone mode"));
360 LOGGER.debug("testRestServerProducerPort end");
364 * Test rest server consumer standalone no host.
367 public void testRestServerConsumerStandaloneNoHost() {
368 LOGGER.debug("testRestServerConsumerStandaloneNoHost start");
369 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"};
370 assertThatThrownBy(() -> new ApexMain(args))
371 .hasRootCauseMessage("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
372 + "(FirstConsumer) in standalone mode");
374 LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
378 * Test rest server consumer standalone no port.
381 public void testRestServerConsumerStandaloneNoPort() {
382 LOGGER.debug("testRestServerConsumerStandaloneNoPort start");
383 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
384 assertThatThrownBy(() -> new ApexMain(args))
385 .hasRootCauseMessage("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
386 + "(FirstConsumer) in standalone mode");
387 LOGGER.debug("testRestServerConsumerStandaloneNoPort end");
391 * Test rest server producer not sync.
394 public void testRestServerProducerNotSync() {
395 LOGGER.debug("testRestServerProducerNotSync start");
396 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
397 assertThatThrownBy(() -> new ApexMain(args)).hasRootCauseMessage(
398 "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer");
399 LOGGER.debug("testRestServerProducerNotSync end");
403 * Test rest server consumer not sync.
405 * @throws MessagingException the messaging exception
406 * @throws ApexException the apex exception
407 * @throws IOException Signals that an I/O exception has occurred.
410 public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException {
411 LOGGER.debug("testRestServerConsumerNotSync start");
412 System.setOut(new PrintStream(outContent));
413 System.setErr(new PrintStream(errContent));
415 final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
417 final ApexMain apexMain = new ApexMain(args);
418 ThreadUtilities.sleep(200);
421 await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
423 final String outString = outContent.toString();
425 System.setOut(stdout);
426 System.setErr(stderr);
429 outString.contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined "
430 + "with the same peered mode"));
431 LOGGER.debug("testRestServerConsumerNotSync end");
439 private String getEvent() {
440 final Random rand = new Random();
441 final int nextMatchCase = rand.nextInt(4);
442 final String nextEventName = "Event0" + rand.nextInt(2) + "00";
444 final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
445 + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n"
446 + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
447 + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
448 + "\"TestTemperature\": 9080.866\n" + "}";