APEX standalone support for ToscaPolicy format
[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  *  Modifications Copyright (C) 2020 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver;
24
25 import static org.awaitility.Awaitility.await;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28
29 import com.google.gson.Gson;
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 import javax.ws.rs.client.Client;
37 import javax.ws.rs.client.ClientBuilder;
38 import javax.ws.rs.client.Entity;
39 import javax.ws.rs.core.Response;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
43 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
44 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
45 import org.onap.policy.apex.service.engine.main.ApexMain;
46 import org.onap.policy.common.utils.network.NetworkUtil;
47 import org.slf4j.ext.XLogger;
48 import org.slf4j.ext.XLoggerFactory;
49
50 /**
51  * The Class TestRestServer.
52  */
53 public class TestRestServer {
54     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRestServer.class);
55
56     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
57     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
58
59     private final PrintStream stdout = System.out;
60     private final PrintStream stderr = System.err;
61
62     private static int eventsSent = 0;
63
64     /**
65      * Clear relative file root environment variable.
66      */
67     @Before
68     public void clearRelativeFileRoot() {
69         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
70     }
71
72     /**
73      * Test rest server put.
74      *
75      * @throws MessagingException the messaging exception
76      * @throws ApexException the apex exception
77      * @throws IOException Signals that an I/O exception has occurred.
78      * @throws InterruptedException interrupted exception
79      */
80     @SuppressWarnings("unchecked")
81     @Test
82     public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
83         LOGGER.debug("testRestServerPut start");
84
85         final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
86         final ApexMain apexMain = new ApexMain(args);
87         if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
88             throw new IllegalStateException("cannot connect to Apex Rest Server");
89         }
90         final Client client = ClientBuilder.newClient();
91
92         Response response = null;
93         Map<String, Object> jsonMap = null;
94
95         for (int i = 0; i < 20; i++) {
96             response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
97                 .put(Entity.json(getEvent()));
98
99             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
100                 break;
101             }
102
103             final String responseString = response.readEntity(String.class);
104
105             jsonMap = new Gson().fromJson(responseString, Map.class);
106         }
107
108         apexMain.shutdown();
109
110         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
111
112         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
113         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
114         assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
115         LOGGER.debug("testRestServerPut end");
116     }
117
118     /**
119      * Test rest server post.
120      *
121      * @throws MessagingException the messaging exception
122      * @throws ApexException the apex exception
123      * @throws IOException Signals that an I/O exception has occurred.
124      * @throws InterruptedException interrupted exception
125      */
126     @SuppressWarnings("unchecked")
127     @Test
128     public void testRestServerPost() throws MessagingException, ApexException, IOException, InterruptedException {
129         LOGGER.debug("testRestServerPost start");
130         final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
131         final ApexMain apexMain = new ApexMain(args);
132         if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
133             throw new IllegalStateException("cannot connect to Apex Rest Server");
134         }
135         final Client client = ClientBuilder.newClient();
136
137         Response response = null;
138         Map<String, Object> jsonMap = null;
139
140         for (int i = 0; i < 20; i++) {
141             response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
142                 .post(Entity.json(getEvent()));
143
144             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
145                 break;
146             }
147
148             final String responseString = response.readEntity(String.class);
149
150             jsonMap = new Gson().fromJson(responseString, Map.class);
151         }
152
153         apexMain.shutdown();
154
155         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
156
157         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
158         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
159         assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
160         LOGGER.debug("testRestServerPost end");
161     }
162
163     /**
164      * Test rest server get status.
165      *
166      * @throws MessagingException the messaging exception
167      * @throws ApexException the apex exception
168      * @throws IOException Signals that an I/O exception has occurred.
169      * @throws InterruptedException interrupted exception
170      */
171     @Test
172     public void testRestServerGetStatus() throws MessagingException, ApexException, IOException, InterruptedException {
173         LOGGER.debug("testRestServerGetStatus start");
174         final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
175         final ApexMain apexMain = new ApexMain(args);
176         if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
177             throw new IllegalStateException("cannot connect to Apex Rest Server");
178         }
179         final Client client = ClientBuilder.newClient();
180
181         Response postResponse = null;
182         Response putResponse = null;
183
184         // trigger 10 POST & PUT events
185         for (int i = 0; i < 10; i++) {
186             postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
187                 .request("application/json").post(Entity.json(getEvent()));
188             if (Response.Status.OK.getStatusCode() != postResponse.getStatus()) {
189                 break;
190             }
191             putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
192                 .put(Entity.json(getEvent()));
193
194             if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
195                 break;
196             }
197         }
198
199         final Response statResponse =
200             client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
201
202         final String responseString = statResponse.readEntity(String.class);
203
204         apexMain.shutdown();
205
206         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
207
208         assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
209         assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
210         assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
211
212         @SuppressWarnings("unchecked")
213         final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
214         assertEquals("[FirstConsumer", ((String) jsonMap.get("INPUTS")).substring(0, 14));
215         assertEquals(1.0, jsonMap.get("STAT"));
216         assertTrue((double) jsonMap.get("POST") >= 10.0);
217         assertTrue((double) jsonMap.get("PUT") >= 10.0);
218         LOGGER.debug("testRestServerGetStatus end");
219     }
220
221     /**
222      * Test rest server multi inputs.
223      *
224      * @throws MessagingException the messaging exception
225      * @throws ApexException the apex exception
226      * @throws IOException Signals that an I/O exception has occurred.
227      * @throws InterruptedException interrupted exception
228      */
229     @SuppressWarnings("unchecked")
230     @Test
231     public void testRestServerMultiInputs()
232         throws MessagingException, ApexException, IOException, InterruptedException {
233         LOGGER.debug("testRestServerMultiInputs start");
234         final String[] args =
235             {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEventMultiIn.json"};
236         final ApexMain apexMain = new ApexMain(args);
237         if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
238             throw new IllegalStateException("cannot connect to Apex Rest Server");
239         }
240         final Client client = ClientBuilder.newClient();
241
242         Response firstResponse = null;
243         Response secondResponse = null;
244
245         Map<String, Object> firstJsonMap = null;
246         Map<String, Object> secondJsonMap = null;
247
248         for (int i = 0; i < 20; i++) {
249             firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
250                 .request("application/json").post(Entity.json(getEvent()));
251
252             if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
253                 break;
254             }
255
256             final String firstResponseString = firstResponse.readEntity(String.class);
257
258             firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
259
260             secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
261                 .request("application/json").post(Entity.json(getEvent()));
262
263             if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
264                 break;
265             }
266
267             final String secondResponseString = secondResponse.readEntity(String.class);
268
269             secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
270         }
271
272         apexMain.shutdown();
273
274         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
275
276         assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus());
277         assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace"));
278         assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan"));
279
280         assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus());
281         assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace"));
282         assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan"));
283         LOGGER.debug("testRestServerMultiInputs end");
284     }
285
286     /**
287      * Test rest server producer standalone.
288      *
289      * @throws MessagingException the messaging exception
290      * @throws ApexException the apex exception
291      * @throws IOException Signals that an I/O exception has occurred.
292      * @throws InterruptedException interrupted exception
293      */
294     @Test
295     public void testRestServerProducerStandalone()
296         throws MessagingException, ApexException, IOException, InterruptedException {
297         LOGGER.debug("testRestServerProducerStandalone start");
298         System.setOut(new PrintStream(outContent));
299         System.setErr(new PrintStream(errContent));
300
301         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
302
303         final ApexMain apexMain = new ApexMain(args);
304         ThreadUtilities.sleep(200);
305         apexMain.shutdown();
306
307         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
308
309         final String outString = outContent.toString();
310
311         System.setOut(stdout);
312         System.setErr(stderr);
313
314         assertTrue(outString
315             .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer"));
316         LOGGER.debug("testRestServerProducerStandalone end");
317     }
318
319     /**
320      * Test rest server producer host.
321      *
322      * @throws MessagingException the messaging exception
323      * @throws ApexException the apex exception
324      * @throws IOException Signals that an I/O exception has occurred.
325      * @throws InterruptedException interrupted exception
326      */
327     @Test
328     public void testRestServerProducerHost()
329         throws MessagingException, ApexException, IOException, InterruptedException {
330         LOGGER.debug("testRestServerProducerHost start");
331         System.setOut(new PrintStream(outContent));
332         System.setErr(new PrintStream(errContent));
333
334         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
335
336         final ApexMain apexMain = new ApexMain(args);
337         ThreadUtilities.sleep(200);
338         apexMain.shutdown();
339
340         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
341
342         final String outString = outContent.toString();
343
344         System.setOut(stdout);
345         System.setErr(stderr);
346
347         assertTrue(outString.contains(" host is specified only in standalone mode"));
348         LOGGER.debug("testRestServerProducerHost end");
349     }
350
351     /**
352      * Test rest server producer port.
353      *
354      * @throws MessagingException the messaging exception
355      * @throws ApexException the apex exception
356      * @throws IOException Signals that an I/O exception has occurred.
357      * @throws InterruptedException interrupted exception
358      */
359     @Test
360     public void testRestServerProducerPort()
361         throws MessagingException, ApexException, IOException, InterruptedException {
362         LOGGER.debug("testRestServerProducerPort start");
363         System.setOut(new PrintStream(outContent));
364         System.setErr(new PrintStream(errContent));
365
366         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
367
368         final ApexMain apexMain = new ApexMain(args);
369         ThreadUtilities.sleep(200);
370         apexMain.shutdown();
371
372         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
373
374         final String outString = outContent.toString();
375
376         System.setOut(stdout);
377         System.setErr(stderr);
378
379         assertTrue(outString.contains(" port is specified only in standalone mode"));
380         LOGGER.debug("testRestServerProducerPort end");
381     }
382
383     /**
384      * Test rest server consumer standalone no host.
385      *
386      * @throws MessagingException the messaging exception
387      * @throws ApexException the apex exception
388      * @throws IOException Signals that an I/O exception has occurred.
389      */
390     @Test
391     public void testRestServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException {
392         LOGGER.debug("testRestServerConsumerStandaloneNoHost start");
393         System.setOut(new PrintStream(outContent));
394         System.setErr(new PrintStream(errContent));
395
396         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"};
397
398         final ApexMain apexMain = new ApexMain(args);
399         ThreadUtilities.sleep(200);
400         apexMain.shutdown();
401
402         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
403
404         final String outString = outContent.toString();
405
406         System.setOut(stdout);
407         System.setErr(stderr);
408
409         assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
410             + "(FirstConsumer) in standalone mode"));
411         LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
412     }
413
414     /**
415      * Test rest server consumer standalone no port.
416      *
417      * @throws MessagingException the messaging exception
418      * @throws ApexException the apex exception
419      * @throws IOException Signals that an I/O exception has occurred.
420      */
421     @Test
422     public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException {
423         LOGGER.debug("testRestServerConsumerStandaloneNoPort start");
424         System.setOut(new PrintStream(outContent));
425         System.setErr(new PrintStream(errContent));
426
427         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
428
429         final ApexMain apexMain = new ApexMain(args);
430         ThreadUtilities.sleep(200);
431         apexMain.shutdown();
432
433         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
434
435         final String outString = outContent.toString();
436
437         System.setOut(stdout);
438         System.setErr(stderr);
439
440         assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
441             + "(FirstConsumer) in standalone mode"));
442         LOGGER.debug("testRestServerConsumerStandaloneNoPort end");
443     }
444
445     /**
446      * Test rest server producer not sync.
447      *
448      * @throws MessagingException the messaging exception
449      * @throws ApexException the apex exception
450      * @throws IOException Signals that an I/O exception has occurred.
451      */
452     @Test
453     public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException {
454         LOGGER.debug("testRestServerProducerNotSync start");
455         System.setOut(new PrintStream(outContent));
456         System.setErr(new PrintStream(errContent));
457
458         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
459
460         final ApexMain apexMain = new ApexMain(args);
461         ThreadUtilities.sleep(200);
462         apexMain.shutdown();
463
464         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
465
466         final String outString = outContent.toString();
467
468         System.setOut(stdout);
469         System.setErr(stderr);
470
471         assertTrue(outString.contains(
472             "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer"));
473         LOGGER.debug("testRestServerProducerNotSync end");
474     }
475
476     /**
477      * Test rest server consumer not sync.
478      *
479      * @throws MessagingException the messaging exception
480      * @throws ApexException the apex exception
481      * @throws IOException Signals that an I/O exception has occurred.
482      */
483     @Test
484     public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException {
485         LOGGER.debug("testRestServerConsumerNotSync start");
486         System.setOut(new PrintStream(outContent));
487         System.setErr(new PrintStream(errContent));
488
489         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
490
491         final ApexMain apexMain = new ApexMain(args);
492         ThreadUtilities.sleep(200);
493         apexMain.shutdown();
494
495         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
496
497         final String outString = outContent.toString();
498
499         System.setOut(stdout);
500         System.setErr(stderr);
501
502         assertTrue(
503             outString.contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined "
504                 + "with the same peered mode"));
505         LOGGER.debug("testRestServerConsumerNotSync end");
506     }
507
508     /**
509      * Gets the event.
510      *
511      * @return the event
512      */
513     private String getEvent() {
514         final Random rand = new Random();
515         final int nextMatchCase = rand.nextInt(4);
516         final String nextEventName = "Event0" + rand.nextInt(2) + "00";
517
518         final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
519             + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n"
520             + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
521             + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
522             + "\"TestTemperature\": 9080.866\n" + "}";
523
524         return eventString;
525     }
526 }