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