8a506e16b233a2bcce3a7b69eefb81d6233ff2e7
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020, 2023 Nordix Foundation.
5  *  Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
6  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27 import static org.awaitility.Awaitility.await;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertTrue;
30
31 import com.google.gson.Gson;
32 import jakarta.ws.rs.client.Client;
33 import jakarta.ws.rs.client.ClientBuilder;
34 import jakarta.ws.rs.client.Entity;
35 import jakarta.ws.rs.core.Response;
36 import java.io.ByteArrayOutputStream;
37 import java.io.IOException;
38 import java.io.PrintStream;
39 import java.util.Map;
40 import java.util.Random;
41 import java.util.concurrent.TimeUnit;
42 import org.junit.After;
43 import org.junit.Before;
44 import org.junit.Test;
45 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
46 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
47 import org.onap.policy.apex.service.engine.main.ApexMain;
48 import org.onap.policy.common.utils.network.NetworkUtil;
49 import org.slf4j.ext.XLogger;
50 import org.slf4j.ext.XLoggerFactory;
51
52 /**
53  * The Class TestRestServer.
54  */
55 public class TestRestServer {
56     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRestServer.class);
57
58     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
59     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
60
61     private final PrintStream stdout = System.out;
62     private final PrintStream stderr = System.err;
63
64     private static int eventsSent = 0;
65
66     /**
67      * Before Test.
68      */
69     @Before
70     public void beforeTest() {
71         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
72         System.setOut(new PrintStream(outContent));
73         System.setErr(new PrintStream(errContent));
74     }
75
76     /**
77      * After test.
78      */
79     @After
80     public void afterTest() {
81         System.setOut(stdout);
82         System.setErr(stderr);
83     }
84
85     /**
86      * Test rest server put.
87      *
88      * @throws MessagingException the messaging exception
89      * @throws ApexException the apex exception
90      * @throws IOException Signals that an I/O exception has occurred.
91      * @throws InterruptedException interrupted exception
92      */
93     @SuppressWarnings("unchecked")
94     @Test
95     public void testRestServerPut() throws MessagingException, ApexException, IOException, InterruptedException {
96         LOGGER.debug("testRestServerPut start");
97
98         final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
99         final ApexMain apexMain = new ApexMain(args);
100         if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
101             throw new IllegalStateException("cannot connect to Apex Rest Server");
102         }
103         final Client client = ClientBuilder.newClient();
104
105         Response response = null;
106         Map<String, Object> jsonMap = null;
107
108         for (int i = 0; i < 20; i++) {
109             response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
110                 .put(Entity.json(getEvent()));
111
112             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
113                 break;
114             }
115
116             final String responseString = response.readEntity(String.class);
117
118             jsonMap = new Gson().fromJson(responseString, Map.class);
119         }
120
121         apexMain.shutdown();
122
123         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
124
125         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
126         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
127         assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
128         LOGGER.debug("testRestServerPut end");
129     }
130
131     /**
132      * Test rest server post.
133      *
134      * @throws MessagingException the messaging exception
135      * @throws ApexException the apex exception
136      * @throws IOException Signals that an I/O exception has occurred.
137      * @throws InterruptedException interrupted exception
138      */
139     @SuppressWarnings("unchecked")
140     @Test
141     public void testRestServerPost() throws MessagingException, ApexException, IOException, InterruptedException {
142         LOGGER.debug("testRestServerPost start");
143         final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
144         final ApexMain apexMain = new ApexMain(args);
145         if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
146             throw new IllegalStateException("cannot connect to Apex Rest Server");
147         }
148         final Client client = ClientBuilder.newClient();
149
150         Response response = null;
151         Map<String, Object> jsonMap = null;
152
153         for (int i = 0; i < 20; i++) {
154             response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
155                 .post(Entity.json(getEvent()));
156
157             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
158                 break;
159             }
160
161             final String responseString = response.readEntity(String.class);
162
163             jsonMap = new Gson().fromJson(responseString, Map.class);
164         }
165
166         apexMain.shutdown();
167
168         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
169
170         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
171         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
172         assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan"));
173         LOGGER.debug("testRestServerPost end");
174     }
175
176     /**
177      * Test rest server get status.
178      *
179      * @throws MessagingException the messaging exception
180      * @throws ApexException the apex exception
181      * @throws IOException Signals that an I/O exception has occurred.
182      * @throws InterruptedException interrupted exception
183      */
184     @Test
185     public void testRestServerGetStatus() throws MessagingException, ApexException, IOException, InterruptedException {
186         LOGGER.debug("testRestServerGetStatus start");
187         final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEvent.json"};
188         final ApexMain apexMain = new ApexMain(args);
189         if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
190             throw new IllegalStateException("cannot connect to Apex Rest Server");
191         }
192         final Client client = ClientBuilder.newClient();
193
194         Response postResponse = null;
195         Response putResponse = null;
196
197         // trigger 10 POST & PUT events
198         for (int i = 0; i < 10; i++) {
199             postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
200                 .request("application/json").post(Entity.json(getEvent()));
201             if (Response.Status.OK.getStatusCode() != postResponse.getStatus()) {
202                 break;
203             }
204             putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json")
205                 .put(Entity.json(getEvent()));
206
207             if (Response.Status.OK.getStatusCode() != putResponse.getStatus()) {
208                 break;
209             }
210         }
211
212         final Response statResponse =
213             client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get();
214
215         final String responseString = statResponse.readEntity(String.class);
216
217         apexMain.shutdown();
218
219         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
220
221         assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus());
222         assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus());
223         assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus());
224
225         @SuppressWarnings("unchecked")
226         final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
227         assertEquals("[FirstConsumer", ((String) jsonMap.get("INPUTS")).substring(0, 14));
228         assertEquals(1.0, jsonMap.get("STAT"));
229         assertTrue((double) jsonMap.get("POST") >= 10.0);
230         assertTrue((double) jsonMap.get("PUT") >= 10.0);
231         LOGGER.debug("testRestServerGetStatus end");
232     }
233
234     /**
235      * Test rest server multi inputs.
236      *
237      * @throws MessagingException the messaging exception
238      * @throws ApexException the apex exception
239      * @throws IOException Signals that an I/O exception has occurred.
240      * @throws InterruptedException interrupted exception
241      */
242     @SuppressWarnings("unchecked")
243     @Test
244     public void testRestServerMultiInputs()
245         throws MessagingException, ApexException, IOException, InterruptedException {
246         LOGGER.debug("testRestServerMultiInputs start");
247         final String[] args =
248             {"-rfr", "target", "-p", "target/examples/config/SampleDomain/RESTServerJsonEventMultiIn.json"};
249         final ApexMain apexMain = new ApexMain(args);
250         if (!NetworkUtil.isTcpPortOpen("localhost", 23324, 60, 500L)) {
251             throw new IllegalStateException("cannot connect to Apex Rest Server");
252         }
253         final Client client = ClientBuilder.newClient();
254
255         Response firstResponse = null;
256         Response secondResponse = null;
257
258         Map<String, Object> firstJsonMap = null;
259         Map<String, Object> secondJsonMap = null;
260
261         for (int i = 0; i < 20; i++) {
262             firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn")
263                 .request("application/json").post(Entity.json(getEvent()));
264
265             if (Response.Status.OK.getStatusCode() != firstResponse.getStatus()) {
266                 break;
267             }
268
269             final String firstResponseString = firstResponse.readEntity(String.class);
270
271             firstJsonMap = new Gson().fromJson(firstResponseString, Map.class);
272
273             secondResponse = client.target("http://localhost:23325/apex/SecondConsumer/EventIn")
274                 .request("application/json").post(Entity.json(getEvent()));
275
276             if (Response.Status.OK.getStatusCode() != secondResponse.getStatus()) {
277                 break;
278             }
279
280             final String secondResponseString = secondResponse.readEntity(String.class);
281
282             secondJsonMap = new Gson().fromJson(secondResponseString, Map.class);
283         }
284
285         apexMain.shutdown();
286
287         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
288
289         assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus());
290         assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace"));
291         assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan"));
292
293         assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus());
294         assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace"));
295         assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan"));
296         LOGGER.debug("testRestServerMultiInputs end");
297     }
298
299     /**
300      * Test rest server producer standalone.
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 testRestServerProducerStandalone()
309         throws MessagingException, ApexException, IOException, InterruptedException {
310         LOGGER.debug("testRestServerProducerStandalone start");
311         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"};
312
313         final ApexMain apexMain = new ApexMain(args);
314         apexMain.shutdown();
315
316         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
317
318         final String outString = outContent.toString();
319
320         assertThat(outString).contains("\"host\" value \"null\" INVALID, is blank");
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\"", "should be 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\"", "should be 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("\"host\" value \"null\" INVALID, is blank");
391         LOGGER.debug("testRestServerConsumerStandaloneNoHost end");
392     }
393
394     /**
395      * Test rest server consumer standalone no port.
396      *
397      * @throws MessagingException the messaging exception
398      * @throws ApexException the apex exception
399      * @throws IOException Signals that an I/O exception has occurred.
400      */
401     @Test
402     public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException {
403         LOGGER.debug("testRestServerConsumerStandaloneNoPort start");
404         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"};
405
406         final ApexMain apexMain = new ApexMain(args);
407         apexMain.shutdown();
408
409         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
410
411         final String outString = outContent.toString();
412         assertThat(outString).contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer "
413             + "(FirstConsumer) in standalone mode");
414         LOGGER.debug("testRestServerConsumerStandaloneNoPort end");
415     }
416
417     /**
418      * Test rest server producer not sync.
419      *
420      * @throws MessagingException the messaging exception
421      * @throws ApexException the apex exception
422      * @throws IOException Signals that an I/O exception has occurred.
423      */
424     @Test
425     public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException {
426         LOGGER.debug("testRestServerProducerNotSync start");
427         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"};
428
429         final ApexMain apexMain = new ApexMain(args);
430         apexMain.shutdown();
431
432         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
433
434         final String outString = outContent.toString();
435
436         assertThat(outString).contains(
437             "REST Server producer (FirstProducer) must run in synchronous mode " + "with a REST Server consumer");
438         LOGGER.debug("testRestServerProducerNotSync end");
439     }
440
441     /**
442      * Test rest server consumer not sync.
443      *
444      * @throws MessagingException the messaging exception
445      * @throws ApexException the apex exception
446      * @throws IOException Signals that an I/O exception has occurred.
447      */
448     @Test
449     public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException {
450         LOGGER.debug("testRestServerConsumerNotSync start");
451         final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"};
452
453         final ApexMain apexMain = new ApexMain(args);
454         apexMain.shutdown();
455
456         await().atMost(10L, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
457
458         final String outString = outContent.toString();
459
460         assertThat(outString)
461             .contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined "
462                 + "with the same peered mode");
463         LOGGER.debug("testRestServerConsumerNotSync end");
464     }
465
466     /**
467      * Gets the event.
468      *
469      * @return the event
470      */
471     private String getEvent() {
472         final Random rand = new Random();
473         final int nextMatchCase = rand.nextInt(4);
474         final String nextEventName = "Event0" + rand.nextInt(2) + "00";
475
476         final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
477             + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n"
478             + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
479             + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
480             + "\"TestTemperature\": 9080.866\n" + "}";
481
482         return eventString;
483     }
484 }