Update for SNI Chcecking
[policy/apex-pdp.git] / testsuites / integration / integration-uservice-test / src / test / java / org / onap / policy / apex / testsuites / integration / uservice / adapt / restclient / TestFile2Rest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020,2023 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.testsuites.integration.uservice.adapt.restclient;
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 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.After;
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.core.infrastructure.threading.ThreadUtilities;
46 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
47 import org.onap.policy.apex.service.engine.main.ApexMain;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
49 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
50 import org.onap.policy.common.gson.GsonMessageBodyHandler;
51 import org.onap.policy.common.utils.network.NetworkUtil;
52 import org.slf4j.ext.XLogger;
53 import org.slf4j.ext.XLoggerFactory;
54
55 /**
56  * The Class TestFile2Rest.
57  */
58 public class TestFile2Rest {
59     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestFile2Rest.class);
60
61     private static final int PORT = 32801;
62     private static HttpServletServer server;
63
64     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
65     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
66
67     private final PrintStream stdout = System.out;
68     private final PrintStream stderr = System.err;
69     private ApexMain apexMain;
70
71     /**
72      * Sets the up.
73      *
74      * @throws Exception the exception
75      */
76     @BeforeClass
77     public static void setUp() throws Exception {
78         server = HttpServletServerFactoryInstance.getServerFactory().build("TestFile2Rest", false, null, PORT, false,
79                 "/TestFile2Rest", false, false);
80
81         server.addServletClass(null, TestRestClientEndpoint.class.getName());
82         server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
83
84         server.start();
85
86         if (!NetworkUtil.isTcpPortOpen("localHost", PORT, 60, 500L)) {
87             throw new IllegalStateException("port " + PORT + " is still not in use");
88         }
89     }
90
91     /**
92      * Tear down.
93      *
94      * @throws Exception the exception
95      */
96     @AfterClass
97     public static void tearDown() throws Exception {
98         if (server != null) {
99             server.stop();
100         }
101     }
102
103     /**
104      * Before test.
105      */
106     @Before
107     public void beforeTest() {
108         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
109         System.setOut(new PrintStream(outContent));
110         System.setErr(new PrintStream(errContent));
111     }
112
113     /**
114      * After test.
115      * @throws ApexException the exception.
116      */
117     @After
118     public void afterTest() throws ApexException {
119         if (null != apexMain) {
120             apexMain.shutdown();
121         }
122         System.setOut(stdout);
123         System.setErr(stderr);
124     }
125
126     /**
127      * Test file events post.
128      *
129      * @throws MessagingException the messaging exception
130      * @throws ApexException the apex exception
131      * @throws IOException Signals that an I/O exception has occurred.
132      */
133     @Test
134     public void testFileEventsPost() throws MessagingException, ApexException, IOException {
135         final Client client = ClientBuilder.newClient();
136
137         // @formatter:off
138         final String[] args = {
139             "-rfr",
140             "target",
141             "-c",
142             "target/examples/config/SampleDomain/File2RESTJsonEventPost.json"
143         };
144         // @formatter:on
145         final ApexMain apexMain = new ApexMain(args);
146
147         Response response = null;
148
149         // Wait for the required amount of events to be received or for 10 seconds
150         for (int i = 0; i < 100; i++) {
151             ThreadUtilities.sleep(100);
152             response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats")
153                     .request("application/json").get();
154
155             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
156                 break;
157             }
158
159             final String responseString = response.readEntity(String.class);
160
161             @SuppressWarnings("unchecked")
162             final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
163             if ((double) jsonMap.get("POST") == 100) {
164                 break;
165             }
166         }
167
168         apexMain.shutdown();
169
170         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
171     }
172
173     /**
174      * Test file events 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 testFileEventsPut() throws MessagingException, ApexException, IOException {
182         // @formatter:off
183         final String[] args = {
184             "-rfr",
185             "target",
186             "-c",
187             "target/examples/config/SampleDomain/File2RESTJsonEventPut.json"
188         };
189         // @formatter:on
190         final ApexMain apexMain = new ApexMain(args);
191
192         final Client client = ClientBuilder.newClient();
193
194         Response response = null;
195
196         // Wait for the required amount of events to be received or for 10 seconds
197         for (int i = 0; i < 20; i++) {
198             ThreadUtilities.sleep(300);
199             response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats")
200                     .request("application/json").get();
201
202             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
203                 break;
204             }
205
206             final String responseString = response.readEntity(String.class);
207
208             @SuppressWarnings("unchecked")
209             final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
210             if ((double) jsonMap.get("PUT") == 20) {
211                 break;
212             }
213         }
214
215         apexMain.shutdown();
216
217         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
218     }
219
220     /**
221      * Test file events no url.
222      *
223      * @throws MessagingException the messaging exception
224      * @throws ApexException the apex exception
225      * @throws IOException Signals that an I/O exception has occurred.
226      */
227     @Test
228     public void testFileEventsNoUrl() throws MessagingException, ApexException, IOException {
229
230         final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventNoURL.json"};
231         apexMain = new ApexMain(args);
232         final String outString = outContent.toString();
233         LOGGER.info("NoUrl-OUTSTRING=\n {} \nEnd-NoUrl", outString);
234         assertThat(outString).contains(" no URL has been set for event sending on RESTCLIENT");
235     }
236
237     /**
238      * Test file events bad url.
239      *
240      * @throws MessagingException the messaging exception
241      * @throws ApexException the apex exception
242      * @throws IOException Signals that an I/O exception has occurred.
243      */
244     @Test
245     public void testFileEventsBadUrl() throws MessagingException, ApexException, IOException {
246
247         final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventBadURL.json"};
248         apexMain = new ApexMain(args);
249         await().atMost(5, TimeUnit.SECONDS)
250             .until(() -> outContent.toString()
251                 .contains("send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/Bad\" "
252                     + "using HTTP \"POST\" failed with status code 404"));
253         assertTrue(apexMain.isAlive());
254         LOGGER.info("BadUrl-OUTSTRING=\n {} \nEnd-BadUrl", outContent.toString());
255     }
256
257     /**
258      * Test file events bad http method.
259      *
260      * @throws MessagingException the messaging exception
261      * @throws ApexException the apex exception
262      * @throws IOException Signals that an I/O exception has occurred.
263      */
264     @Test
265     public void testFileEventsBadHttpMethod() throws MessagingException, ApexException, IOException {
266
267         final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json"};
268         apexMain = new ApexMain(args);
269         final String outString = outContent.toString();
270         LOGGER.info("BadHttpMethod-OUTSTRING=\n {} \nEnd-BadHttpMethod", outString);
271         assertThat(outString)
272             .contains("specified HTTP method of \"DELETE\" is invalid, only HTTP methods \"POST\" and \"PUT\" "
273                 + "are supported for event sending on REST client producer");
274     }
275
276     /**
277      * Test file events bad response.
278      *
279      * @throws MessagingException the messaging exception
280      * @throws ApexException the apex exception
281      * @throws IOException Signals that an I/O exception has occurred.
282      */
283     @Test
284     public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException {
285
286         final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json"};
287         apexMain = new ApexMain(args);
288
289         await().atMost(5, TimeUnit.SECONDS)
290             .until(() -> outContent.toString().contains(
291                 "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/PostEventBadResponse\""
292                     + " using HTTP \"POST\" failed with status code 400"));
293         assertTrue(apexMain.isAlive());
294         LOGGER.info("BadResponse-OUTSTRING=\n {} \nEnd-BadResponse", outContent.toString());
295     }
296 }