Changes for checkstyle 8.32
[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 import java.io.ByteArrayOutputStream;
30 import java.io.IOException;
31 import java.io.PrintStream;
32 import java.util.Map;
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;
48
49 /**
50  * The Class TestRestServer.
51  */
52 public class TestRestServer {
53     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRestServer.class);
54
55     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
56     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
57
58     private final PrintStream stdout = System.out;
59     private final PrintStream stderr = System.err;
60
61     private static int eventsSent = 0;
62
63     /**
64      * Clear relative file root environment variable.
65      */
66     @Before
67     public void clearRelativeFileRoot() {
68         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
69     }
70
71     /**
72      * Test rest server put.
73      *
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
78      */
79     @SuppressWarnings("unchecked")
80     @Test
81     public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
82         LOGGER.debug("testRestServerPut start");
83
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");
88         }
89         final Client client = ClientBuilder.newClient();
90
91         Response response = null;
92         Map<String, Object> jsonMap = null;
93
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()));
97
98             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
99                 break;
100             }
101
102             final String responseString = response.readEntity(String.class);
103
104             jsonMap = new Gson().fromJson(responseString, Map.class);
105         }
106
107         apexMain.shutdown();
108
109         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
110
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");
115     }
116
117     /**
118      * Test rest server post.
119      *
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
124      */
125     @SuppressWarnings("unchecked")
126     @Test
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");
133         }
134         final Client client = ClientBuilder.newClient();
135
136         Response response = null;
137         Map<String, Object> jsonMap = null;
138
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()));
142
143             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
144                 break;
145             }
146
147             final String responseString = response.readEntity(String.class);
148
149             jsonMap = new Gson().fromJson(responseString, Map.class);
150         }
151
152         apexMain.shutdown();
153
154         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
155
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");
160     }
161
162     /**
163      * Test rest server get status.
164      *
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
169      */
170     @Test
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");
177         }
178         final Client client = ClientBuilder.newClient();
179
180         Response postResponse = null;
181         Response putResponse = null;
182
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()) {
188                 break;
189             }
190             putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
191                 .put(Entity.json(getEvent()));
192
193             if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
194                 break;
195             }
196         }
197
198         final Response statResponse =
199             client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
200
201         final String responseString = statResponse.readEntity(String.class);
202
203         apexMain.shutdown();
204
205         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
206
207         assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
208         assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
209         assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
210
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");
218     }
219
220     /**
221      * Test rest server multi inputs.
222      *
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
227      */
228     @SuppressWarnings("unchecked")
229     @Test
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");
238         }
239         final Client client = ClientBuilder.newClient();
240
241         Response firstResponse = null;
242         Response secondResponse = null;
243
244         Map<String, Object> firstJsonMap = null;
245         Map<String, Object> secondJsonMap = null;
246
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()));
250
251             if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
252                 break;
253             }
254
255             final String firstResponseString = firstResponse.readEntity(String.class);
256
257             firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
258
259             secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
260                 .request("application/json").post(Entity.json(getEvent()));
261
262             if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
263                 break;
264             }
265
266             final String secondResponseString = secondResponse.readEntity(String.class);
267
268             secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
269         }
270
271         apexMain.shutdown();
272
273         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
274
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"));
278
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");
283     }
284
285     /**
286      * Test rest server producer standalone.
287      *
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
292      */
293     @Test
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));
299
300         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
301
302         final ApexMain apexMain = new ApexMain(args);
303         ThreadUtilities.sleep(200);
304         apexMain.shutdown();
305
306         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
307
308         final String outString = outContent.toString();
309
310         System.setOut(stdout);
311         System.setErr(stderr);
312
313         assertTrue(outString
314             .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer"));
315         LOGGER.debug("testRestServerProducerStandalone end");
316     }
317
318     /**
319      * Test rest server producer host.
320      *
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
325      */
326     @Test
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));
332
333         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
334
335         final ApexMain apexMain = new ApexMain(args);
336         ThreadUtilities.sleep(200);
337         apexMain.shutdown();
338
339         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
340
341         final String outString = outContent.toString();
342
343         System.setOut(stdout);
344         System.setErr(stderr);
345
346         assertTrue(outString.contains(" host is specified only in standalone mode"));
347         LOGGER.debug("testRestServerProducerHost end");
348     }
349
350     /**
351      * Test rest server producer port.
352      *
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
357      */
358     @Test
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));
364
365         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
366
367         final ApexMain apexMain = new ApexMain(args);
368         ThreadUtilities.sleep(200);
369         apexMain.shutdown();
370
371         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
372
373         final String outString = outContent.toString();
374
375         System.setOut(stdout);
376         System.setErr(stderr);
377
378         assertTrue(outString.contains(" port is specified only in standalone mode"));
379         LOGGER.debug("testRestServerProducerPort end");
380     }
381
382     /**
383      * Test rest server consumer standalone no host.
384      *
385      * @throws MessagingException the messaging exception
386      * @throws ApexException the apex exception
387      * @throws IOException Signals that an I/O exception has occurred.
388      */
389     @Test
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));
394
395         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"};
396
397         final ApexMain apexMain = new ApexMain(args);
398         ThreadUtilities.sleep(200);
399         apexMain.shutdown();
400
401         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
402
403         final String outString = outContent.toString();
404
405         System.setOut(stdout);
406         System.setErr(stderr);
407
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");
411     }
412
413     /**
414      * Test rest server consumer standalone no port.
415      *
416      * @throws MessagingException the messaging exception
417      * @throws ApexException the apex exception
418      * @throws IOException Signals that an I/O exception has occurred.
419      */
420     @Test
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));
425
426         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
427
428         final ApexMain apexMain = new ApexMain(args);
429         ThreadUtilities.sleep(200);
430         apexMain.shutdown();
431
432         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
433
434         final String outString = outContent.toString();
435
436         System.setOut(stdout);
437         System.setErr(stderr);
438
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");
442     }
443
444     /**
445      * Test rest server producer not sync.
446      *
447      * @throws MessagingException the messaging exception
448      * @throws ApexException the apex exception
449      * @throws IOException Signals that an I/O exception has occurred.
450      */
451     @Test
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));
456
457         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
458
459         final ApexMain apexMain = new ApexMain(args);
460         ThreadUtilities.sleep(200);
461         apexMain.shutdown();
462
463         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
464
465         final String outString = outContent.toString();
466
467         System.setOut(stdout);
468         System.setErr(stderr);
469
470         assertTrue(outString.contains(
471             "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer"));
472         LOGGER.debug("testRestServerProducerNotSync end");
473     }
474
475     /**
476      * Test rest server consumer not sync.
477      *
478      * @throws MessagingException the messaging exception
479      * @throws ApexException the apex exception
480      * @throws IOException Signals that an I/O exception has occurred.
481      */
482     @Test
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));
487
488         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
489
490         final ApexMain apexMain = new ApexMain(args);
491         ThreadUtilities.sleep(200);
492         apexMain.shutdown();
493
494         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
495
496         final String outString = outContent.toString();
497
498         System.setOut(stdout);
499         System.setErr(stderr);
500
501         assertTrue(
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");
505     }
506
507     /**
508      * Gets the event.
509      *
510      * @return the event
511      */
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";
516
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" + "}";
522
523         return eventString;
524     }
525 }