4f6ef290ab6a507b14113dbfd40d20d303fa0761
[policy/apex-pdp.git] / testsuites / integration / integration-uservice-test / src / test / java / org / onap / policy / apex / testsuites / integration / uservice / adapt / restserver / TestRestServer.java
1 /*-
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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver;
23
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertTrue;
27
28 import com.google.gson.Gson;
29
30 import java.io.ByteArrayOutputStream;
31 import java.io.IOException;
32 import java.io.PrintStream;
33 import java.util.Map;
34 import java.util.Random;
35 import java.util.concurrent.TimeUnit;
36
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
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;
51
52 /**
53  * The Class TestRestServer.
54  */
55 public class TestRestServer {
56     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRestServer.class);
57
58     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
59     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
60
61     private final PrintStream stdout = System.out;
62     private final PrintStream stderr = System.err;
63
64     private static int eventsSent = 0;
65
66     /**
67      * Clear relative file root environment variable.
68      */
69     @Before
70     public void clearRelativeFileRoot() {
71         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
72     }
73
74     /**
75      * Test rest server put.
76      *
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
81      */
82     @SuppressWarnings("unchecked")
83     @Test
84     public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
85         LOGGER.debug("testRestServerPut start");
86
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");
91         }
92         final Client client = ClientBuilder.newClient();
93
94         Response response = null;
95         Map<String, Object> jsonMap = null;
96
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()));
100
101             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
102                 break;
103             }
104
105             final String responseString = response.readEntity(String.class);
106
107             jsonMap = new Gson().fromJson(responseString, Map.class);
108         }
109
110         apexMain.shutdown();
111
112         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
113
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");
118     }
119
120     /**
121      * Test rest server post.
122      *
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
127      */
128     @SuppressWarnings("unchecked")
129     @Test
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");
136         }
137         final Client client = ClientBuilder.newClient();
138
139         Response response = null;
140         Map<String, Object> jsonMap = null;
141
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()));
145
146             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
147                 break;
148             }
149
150             final String responseString = response.readEntity(String.class);
151
152             jsonMap = new Gson().fromJson(responseString, Map.class);
153         }
154
155         apexMain.shutdown();
156
157         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
158
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");
163     }
164
165     /**
166      * Test rest server get status.
167      *
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
172      */
173     @Test
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");
180         }
181         final Client client = ClientBuilder.newClient();
182
183         Response postResponse = null;
184         Response putResponse = null;
185
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()) {
191                 break;
192             }
193             putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
194                 .put(Entity.json(getEvent()));
195
196             if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
197                 break;
198             }
199         }
200
201         final Response statResponse =
202             client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
203
204         final String responseString = statResponse.readEntity(String.class);
205
206         apexMain.shutdown();
207
208         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
209
210         assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
211         assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
212         assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
213
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");
221     }
222
223     /**
224      * Test rest server multi inputs.
225      *
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
230      */
231     @SuppressWarnings("unchecked")
232     @Test
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");
241         }
242         final Client client = ClientBuilder.newClient();
243
244         Response firstResponse = null;
245         Response secondResponse = null;
246
247         Map<String, Object> firstJsonMap = null;
248         Map<String, Object> secondJsonMap = null;
249
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()));
253
254             if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
255                 break;
256             }
257
258             final String firstResponseString = firstResponse.readEntity(String.class);
259
260             firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
261
262             secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
263                 .request("application/json").post(Entity.json(getEvent()));
264
265             if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
266                 break;
267             }
268
269             final String secondResponseString = secondResponse.readEntity(String.class);
270
271             secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
272         }
273
274         apexMain.shutdown();
275
276         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
277
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"));
281
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");
286     }
287
288     /**
289      * Test rest server producer standalone.
290      *
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
295      */
296     @Test
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));
302
303         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
304
305         final ApexMain apexMain = new ApexMain(args);
306         ThreadUtilities.sleep(200);
307         apexMain.shutdown();
308
309         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
310
311         final String outString = outContent.toString();
312
313         System.setOut(stdout);
314         System.setErr(stderr);
315
316         assertTrue(outString
317             .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer"));
318         LOGGER.debug("testRestServerProducerStandalone end");
319     }
320
321     /**
322      * Test rest server producer host.
323      *
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
328      */
329     @Test
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));
335
336         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
337
338         final ApexMain apexMain = new ApexMain(args);
339         ThreadUtilities.sleep(200);
340         apexMain.shutdown();
341
342         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
343
344         final String outString = outContent.toString();
345
346         System.setOut(stdout);
347         System.setErr(stderr);
348
349         assertTrue(outString.contains(" host is specified only in standalone mode"));
350         LOGGER.debug("testRestServerProducerHost end");
351     }
352
353     /**
354      * Test rest server producer port.
355      *
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
360      */
361     @Test
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));
367
368         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
369
370         final ApexMain apexMain = new ApexMain(args);
371         ThreadUtilities.sleep(200);
372         apexMain.shutdown();
373
374         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
375
376         final String outString = outContent.toString();
377
378         System.setOut(stdout);
379         System.setErr(stderr);
380
381         assertTrue(outString.contains(" port is specified only in standalone mode"));
382         LOGGER.debug("testRestServerProducerPort end");
383     }
384
385     /**
386      * Test rest server consumer standalone no host.
387      *
388      * @throws MessagingException the messaging exception
389      * @throws ApexException the apex exception
390      * @throws IOException Signals that an I/O exception has occurred.
391      */
392     @Test
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));
397
398         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"};
399
400         final ApexMain apexMain = new ApexMain(args);
401         ThreadUtilities.sleep(200);
402         apexMain.shutdown();
403
404         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
405
406         final String outString = outContent.toString();
407
408         System.setOut(stdout);
409         System.setErr(stderr);
410
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");
414     }
415
416     /**
417      * Test rest server consumer standalone no port.
418      *
419      * @throws MessagingException the messaging exception
420      * @throws ApexException the apex exception
421      * @throws IOException Signals that an I/O exception has occurred.
422      */
423     @Test
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));
428
429         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
430
431         final ApexMain apexMain = new ApexMain(args);
432         ThreadUtilities.sleep(200);
433         apexMain.shutdown();
434
435         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
436
437         final String outString = outContent.toString();
438
439         System.setOut(stdout);
440         System.setErr(stderr);
441
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");
445     }
446
447     /**
448      * Test rest server producer not sync.
449      *
450      * @throws MessagingException the messaging exception
451      * @throws ApexException the apex exception
452      * @throws IOException Signals that an I/O exception has occurred.
453      */
454     @Test
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));
459
460         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
461
462         final ApexMain apexMain = new ApexMain(args);
463         ThreadUtilities.sleep(200);
464         apexMain.shutdown();
465
466         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
467
468         final String outString = outContent.toString();
469
470         System.setOut(stdout);
471         System.setErr(stderr);
472
473         assertTrue(outString.contains(
474             "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer"));
475         LOGGER.debug("testRestServerProducerNotSync end");
476     }
477
478     /**
479      * Test rest server consumer not sync.
480      *
481      * @throws MessagingException the messaging exception
482      * @throws ApexException the apex exception
483      * @throws IOException Signals that an I/O exception has occurred.
484      */
485     @Test
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));
490
491         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
492
493         final ApexMain apexMain = new ApexMain(args);
494         ThreadUtilities.sleep(200);
495         apexMain.shutdown();
496
497         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
498
499         final String outString = outContent.toString();
500
501         System.setOut(stdout);
502         System.setErr(stderr);
503
504         assertTrue(
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");
508     }
509
510     /**
511      * Gets the event.
512      *
513      * @return the event
514      */
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";
519
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" + "}";
525
526         return eventString;
527     }
528 }