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