39173bc72bb78061e092463bcd0aba59337b8cd9
[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.assertThatThrownBy;
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.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;
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      * Clear relative file root environment variable.
67      */
68     @Before
69     public void clearRelativeFileRoot() {
70         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
71     }
72
73     /**
74      * Test rest server put.
75      *
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
80      */
81     @SuppressWarnings("unchecked")
82     @Test
83     public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
84         LOGGER.debug("testRestServerPut start");
85
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");
90         }
91         final Client client = ClientBuilder.newClient();
92
93         Response response = null;
94         Map<String, Object> jsonMap = null;
95
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()));
99
100             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
101                 break;
102             }
103
104             final String responseString = response.readEntity(String.class);
105
106             jsonMap = new Gson().fromJson(responseString, Map.class);
107         }
108
109         apexMain.shutdown();
110
111         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
112
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");
117     }
118
119     /**
120      * Test rest server post.
121      *
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
126      */
127     @SuppressWarnings("unchecked")
128     @Test
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");
135         }
136         final Client client = ClientBuilder.newClient();
137
138         Response response = null;
139         Map<String, Object> jsonMap = null;
140
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()));
144
145             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
146                 break;
147             }
148
149             final String responseString = response.readEntity(String.class);
150
151             jsonMap = new Gson().fromJson(responseString, Map.class);
152         }
153
154         apexMain.shutdown();
155
156         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
157
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");
162     }
163
164     /**
165      * Test rest server get status.
166      *
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
171      */
172     @Test
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");
179         }
180         final Client client = ClientBuilder.newClient();
181
182         Response postResponse = null;
183         Response putResponse = null;
184
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()) {
190                 break;
191             }
192             putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
193                 .put(Entity.json(getEvent()));
194
195             if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
196                 break;
197             }
198         }
199
200         final Response statResponse =
201             client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
202
203         final String responseString = statResponse.readEntity(String.class);
204
205         apexMain.shutdown();
206
207         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
208
209         assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
210         assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
211         assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
212
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");
220     }
221
222     /**
223      * Test rest server multi inputs.
224      *
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
229      */
230     @SuppressWarnings("unchecked")
231     @Test
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");
240         }
241         final Client client = ClientBuilder.newClient();
242
243         Response firstResponse = null;
244         Response secondResponse = null;
245
246         Map<String, Object> firstJsonMap = null;
247         Map<String, Object> secondJsonMap = null;
248
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()));
252
253             if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
254                 break;
255             }
256
257             final String firstResponseString = firstResponse.readEntity(String.class);
258
259             firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
260
261             secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
262                 .request("application/json").post(Entity.json(getEvent()));
263
264             if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
265                 break;
266             }
267
268             final String secondResponseString = secondResponse.readEntity(String.class);
269
270             secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
271         }
272
273         apexMain.shutdown();
274
275         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
276
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"));
280
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");
285     }
286
287     /**
288      * Test rest server producer standalone.
289      */
290     @Test
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)");
297     }
298
299     /**
300      * Test rest server producer host.
301      *
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
306      */
307     @Test
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));
313
314         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"};
315
316         final ApexMain apexMain = new ApexMain(args);
317         ThreadUtilities.sleep(200);
318         apexMain.shutdown();
319
320         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
321
322         final String outString = outContent.toString();
323
324         System.setOut(stdout);
325         System.setErr(stderr);
326
327         assertTrue(outString.contains(" host is specified only in standalone mode"));
328         LOGGER.debug("testRestServerProducerHost end");
329     }
330
331     /**
332      * Test rest server producer port.
333      *
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
338      */
339     @Test
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));
345
346         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"};
347
348         final ApexMain apexMain = new ApexMain(args);
349         ThreadUtilities.sleep(200);
350         apexMain.shutdown();
351
352         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
353
354         final String outString = outContent.toString();
355
356         System.setOut(stdout);
357         System.setErr(stderr);
358
359         assertTrue(outString.contains(" port is specified only in standalone mode"));
360         LOGGER.debug("testRestServerProducerPort end");
361     }
362
363     /**
364      * Test rest server consumer standalone no host.
365      */
366     @Test
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");
373
374         LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
375     }
376
377     /**
378      * Test rest server consumer standalone no port.
379      */
380     @Test
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");
388     }
389
390     /**
391      * Test rest server producer not sync.
392      */
393     @Test
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");
400     }
401
402     /**
403      * Test rest server consumer not sync.
404      *
405      * @throws MessagingException the messaging exception
406      * @throws ApexException the apex exception
407      * @throws IOException Signals that an I/O exception has occurred.
408      */
409     @Test
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));
414
415         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
416
417         final ApexMain apexMain = new ApexMain(args);
418         ThreadUtilities.sleep(200);
419         apexMain.shutdown();
420
421         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
422
423         final String outString = outContent.toString();
424
425         System.setOut(stdout);
426         System.setErr(stderr);
427
428         assertTrue(
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");
432     }
433
434     /**
435      * Gets the event.
436      *
437      * @return the event
438      */
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";
443
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" + "}";
449
450         return eventString;
451     }
452 }