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