1e8105976d016b277d32b946a3b0ee6cb1ea176d
[policy/apex-pdp.git] / plugins / plugins-event / plugins-event-carrier / plugins-event-carrier-restrequestor / src / test / java / org / onap / policy / apex / plugins / event / carrier / restrequestor / RestRequestorTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 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.plugins.event.carrier.restrequestor;
23
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertTrue;
27
28 import com.google.gson.Gson;
29
30 import java.io.ByteArrayOutputStream;
31 import java.io.IOException;
32 import java.io.PrintStream;
33 import java.util.Map;
34 import java.util.concurrent.TimeUnit;
35
36 import javax.ws.rs.client.Client;
37 import javax.ws.rs.client.ClientBuilder;
38 import javax.ws.rs.core.Response;
39
40 import org.junit.AfterClass;
41 import org.junit.Before;
42 import org.junit.BeforeClass;
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.endpoints.http.server.HttpServletServer;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
49 import org.onap.policy.common.gson.GsonMessageBodyHandler;
50 import org.onap.policy.common.utils.network.NetworkUtil;
51
52 /**
53  * The Class TestRestRequestor.
54  */
55 public class RestRequestorTest {
56     private static final int PORT = 32801;
57     private static HttpServletServer server;
58
59     private ByteArrayOutputStream outContent = new ByteArrayOutputStream();
60     private ByteArrayOutputStream errContent = new ByteArrayOutputStream();
61
62     private final PrintStream stdout = System.out;
63     private final PrintStream stderr = System.err;
64
65     /**
66      * Sets the up.
67      *
68      * @throws Exception the exception
69      */
70     @BeforeClass
71     public static void setUp() throws Exception {
72         server = HttpServletServerFactoryInstance.getServerFactory().build(null, false, null, PORT,
73             "/TestRESTRequestor", false, false);
74
75         server.addServletClass(null, SupportRestRequestorEndpoint.class.getName());
76         server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
77
78         server.start();
79
80         if (!NetworkUtil.isTcpPortOpen("localHost", PORT, 60, 500L)) {
81             throw new IllegalStateException("port " + PORT + " is still not in use");
82         }
83     }
84
85     /**
86      * Tear down.
87      *
88      * @throws Exception the exception
89      */
90     @AfterClass
91     public static void tearDown() throws Exception {
92         if (server != null) {
93             server.stop();
94         }
95     }
96
97     /**
98      * Reset counters.
99      */
100     @Before
101     public void resetCounters() {
102         SupportRestRequestorEndpoint.resetCounters();
103     }
104
105     /**
106      * Test rest requestor get.
107      *
108      * @throws MessagingException the messaging exception
109      * @throws Exception an exception
110      */
111     @Test
112     public void testRestRequestorGet() throws Exception {
113         final Client client = ClientBuilder.newClient();
114
115         final String[] args = {"src/test/resources/prodcons/File2RESTRequest2FileGet.json"};
116         final ApexMain apexMain = new ApexMain(args);
117         await().atMost(2, TimeUnit.SECONDS).until(() -> apexMain.isAlive());
118
119         await().pollInterval(300, TimeUnit.MILLISECONDS).atMost(10, TimeUnit.SECONDS)
120             .until(() -> getStatsFromServer(client, "GET") >= 50.0);
121
122         apexMain.shutdown();
123         await().atMost(2, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
124
125         client.close();
126     }
127
128     /**
129      * Test rest requestor get empty.
130      *
131      * @throws MessagingException the messaging exception
132      * @throws ApexException the apex exception
133      * @throws IOException Signals that an I/O exception has occurred.
134      */
135     @Test
136     public void testRestRequestorGetEmpty() throws MessagingException, ApexException, IOException {
137         final Client client = ClientBuilder.newClient();
138
139         final String[] args = {"src/test/resources/prodcons/File2RESTRequest2FileGetEmpty.json"};
140         final ApexMain apexMain = new ApexMain(args);
141         await().atMost(2, TimeUnit.SECONDS).until(() -> apexMain.isAlive());
142
143         Response response = null;
144
145         // Wait for the required amount of events to be received or for 10 seconds
146         double getsSoFar = 0.0;
147         for (int i = 0; i < 40; i++) {
148             response = client.target("http://localhost:32801/TestRESTRequestor/apex/event/Stats")
149                 .request("application/json").get();
150
151             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
152                 break;
153             }
154
155             final String responseString = response.readEntity(String.class);
156
157             @SuppressWarnings("unchecked")
158             final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
159             getsSoFar = Double.parseDouble(jsonMap.get("GET").toString());
160
161             if (getsSoFar >= 50.0) {
162                 break;
163             }
164         }
165
166         apexMain.shutdown();
167         await().atMost(2, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
168
169         client.close();
170
171         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
172     }
173
174     /**
175      * Test REST requestor put.
176      *
177      * @throws MessagingException the messaging exception
178      * @throws ApexException the apex exception
179      * @throws IOException Signals that an I/O exception has occurred.
180      */
181     @Test
182     public void testRestRequestorPut() throws MessagingException, ApexException, IOException {
183         final Client client = ClientBuilder.newClient();
184
185         final String[] args = {"src/test/resources/prodcons/File2RESTRequest2FilePut.json"};
186         final ApexMain apexMain = new ApexMain(args);
187         await().atMost(2, TimeUnit.SECONDS).until(() -> apexMain.isAlive());
188
189         await().pollInterval(300, TimeUnit.MILLISECONDS).atMost(10, TimeUnit.SECONDS)
190             .until(() -> getStatsFromServer(client, "PUT") >= 50.0);
191
192         apexMain.shutdown();
193         await().atMost(2, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
194
195         client.close();
196     }
197
198     /**
199      * Test REST requestor post.
200      *
201      * @throws MessagingException the messaging exception
202      * @throws ApexException the apex exception
203      * @throws IOException Signals that an I/O exception has occurred.
204      */
205     @Test
206     public void testRestRequestorPost() throws MessagingException, ApexException, IOException {
207         final Client client = ClientBuilder.newClient();
208
209         final String[] args = {"src/test/resources/prodcons/File2RESTRequest2FilePost.json"};
210         final ApexMain apexMain = new ApexMain(args);
211         await().atMost(2, TimeUnit.SECONDS).until(() -> apexMain.isAlive());
212
213         await().pollInterval(300, TimeUnit.MILLISECONDS).atMost(10, TimeUnit.SECONDS)
214             .until(() -> getStatsFromServer(client, "POST") >= 50.0);
215
216         apexMain.shutdown();
217         await().atMost(2, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
218
219         client.close();
220     }
221
222     /**
223      * Test REST requestor delete.
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      */
229     @Test
230     public void testRestRequestorDelete() throws MessagingException, ApexException, IOException {
231         final Client client = ClientBuilder.newClient();
232
233         final String[] args = {"src/test/resources/prodcons/File2RESTRequest2FileDelete.json"};
234         final ApexMain apexMain = new ApexMain(args);
235         await().atMost(2, TimeUnit.SECONDS).until(() -> apexMain.isAlive());
236
237         // Wait for the required amount of events to be received
238         await().pollInterval(300, TimeUnit.MILLISECONDS).atMost(10, TimeUnit.SECONDS)
239             .until(() -> getStatsFromServer(client, "DELETE") >= 50.0);
240
241         apexMain.shutdown();
242         await().atMost(2, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
243
244         client.close();
245     }
246
247     /**
248      * Test REST requestor multi inputs.
249      *
250      * @throws MessagingException the messaging exception
251      * @throws ApexException the apex exception
252      * @throws IOException Signals that an I/O exception has occurred.
253      */
254     @Test
255     public void testRestRequestorMultiInputs() throws MessagingException, ApexException, IOException {
256         final Client client = ClientBuilder.newClient();
257
258         final String[] args = {"src/test/resources/prodcons/File2RESTRequest2FileGetMulti.json"};
259         final ApexMain apexMain = new ApexMain(args);
260         await().atMost(10, TimeUnit.SECONDS).until(() -> apexMain.isAlive());
261
262         await().pollInterval(300, TimeUnit.MILLISECONDS).atMost(10, TimeUnit.SECONDS)
263             .until(() -> getStatsFromServer(client, "GET") >= 8.0);
264
265         apexMain.shutdown();
266         await().atMost(2, TimeUnit.SECONDS).until(() -> !apexMain.isAlive());
267
268         client.close();
269     }
270
271     /**
272      * Test REST requestor producer alone.
273      *
274      * @throws MessagingException the messaging exception
275      * @throws ApexException the apex exception
276      * @throws IOException Signals that an I/O exception has occurred.
277      */
278     @Test
279     public void testRestRequestorProducerAlone() throws MessagingException, ApexException, IOException {
280         System.setOut(new PrintStream(outContent));
281         System.setErr(new PrintStream(errContent));
282
283         final String[] args = {"src/test/resources/prodcons/File2RESTRequest2FileGetProducerAlone.json"};
284
285         ApexMain apexMain = new ApexMain(args);
286         apexMain.shutdown();
287
288         final String outString = outContent.toString();
289
290         System.setOut(stdout);
291         System.setErr(stderr);
292
293         assertTrue(outString.contains("REST Requestor producer (RestRequestorProducer) "
294             + "must run in peered requestor mode with a REST Requestor consumer"));
295     }
296
297     /**
298      * Test REST requestor consumer alone.
299      *
300      * @throws MessagingException the messaging exception
301      * @throws ApexException the apex exception
302      * @throws IOException Signals that an I/O exception has occurred.
303      */
304     @Test
305     public void testRestRequestorConsumerAlone() throws MessagingException, ApexException, IOException {
306         System.setOut(new PrintStream(outContent));
307         System.setErr(new PrintStream(errContent));
308
309         final String[] args = {"src/test/resources/prodcons/File2RESTRequest2FileGetConsumerAlone.json"};
310
311         ApexMain apexMain = new ApexMain(args);
312         apexMain.shutdown();
313
314         final String outString = outContent.toString();
315
316         System.setOut(stdout);
317         System.setErr(stderr);
318
319         assertTrue(outString.contains("peer \"RestRequestorProducer for peered mode REQUESTOR "
320             + "does not exist or is not defined with the same peered mode"));
321     }
322
323     private double getStatsFromServer(final Client client, final String statToGet) {
324         final Response response = client.target("http://localhost:32801/TestRESTRequestor/apex/event/Stats")
325             .request("application/json").get();
326
327         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
328         final String responseString = response.readEntity(String.class);
329
330         @SuppressWarnings("unchecked")
331         final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
332         return Double.parseDouble(jsonMap.get(statToGet).toString());
333     }
334 }