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