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