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