Changes for checkstyle 8.32
[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 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.testsuites.integration.uservice.adapt.restclient;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
26
27 import com.google.gson.Gson;
28 import java.io.ByteArrayOutputStream;
29 import java.io.IOException;
30 import java.io.PrintStream;
31 import java.util.Map;
32 import javax.ws.rs.client.Client;
33 import javax.ws.rs.client.ClientBuilder;
34 import javax.ws.rs.core.Response;
35 import org.junit.AfterClass;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
40 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
41 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
42 import org.onap.policy.apex.service.engine.main.ApexMain;
43 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
44 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
45 import org.onap.policy.common.gson.GsonMessageBodyHandler;
46 import org.onap.policy.common.utils.network.NetworkUtil;
47 import org.slf4j.ext.XLogger;
48 import org.slf4j.ext.XLoggerFactory;
49
50 /**
51  * The Class TestFile2Rest.
52  */
53 public class TestFile2Rest {
54     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestFile2Rest.class);
55
56     private static final int PORT = 32801;
57     private static HttpServletServer server;
58
59     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
60     private final 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("TestFile2Rest", false, null, PORT,
73                 "/TestFile2Rest", false, false);
74
75         server.addServletClass(null, TestRestClientEndpoint.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      * Clear relative file root environment variable.
99      */
100     @Before
101     public void clearRelativeFileRoot() {
102         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
103     }
104
105     /**
106      * Test file events post.
107      *
108      * @throws MessagingException the messaging exception
109      * @throws ApexException the apex exception
110      * @throws IOException Signals that an I/O exception has occurred.
111      */
112     @Test
113     public void testFileEventsPost() throws MessagingException, ApexException, IOException {
114         final Client client = ClientBuilder.newClient();
115
116         // @formatter:off
117         final String[] args = {
118             "-rfr",
119             "target",
120             "-c",
121             "target/examples/config/SampleDomain/File2RESTJsonEventPost.json"
122         };
123         // @formatter:on
124         final ApexMain apexMain = new ApexMain(args);
125
126         Response response = null;
127
128         // Wait for the required amount of events to be received or for 10 seconds
129         for (int i = 0; i < 100; i++) {
130             ThreadUtilities.sleep(100);
131             response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats")
132                     .request("application/json").get();
133
134             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
135                 break;
136             }
137
138             final String responseString = response.readEntity(String.class);
139
140             @SuppressWarnings("unchecked")
141             final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
142             if ((double) jsonMap.get("POST") == 100) {
143                 break;
144             }
145         }
146
147         apexMain.shutdown();
148
149         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
150     }
151
152     /**
153      * Test file events put.
154      *
155      * @throws MessagingException the messaging exception
156      * @throws ApexException the apex exception
157      * @throws IOException Signals that an I/O exception has occurred.
158      */
159     @Test
160     public void testFileEventsPut() throws MessagingException, ApexException, IOException {
161         // @formatter:off
162         final String[] args = {
163             "-rfr",
164             "target",
165             "-c",
166             "target/examples/config/SampleDomain/File2RESTJsonEventPut.json"
167         };
168         // @formatter:on
169         final ApexMain apexMain = new ApexMain(args);
170
171         final Client client = ClientBuilder.newClient();
172
173         Response response = null;
174
175         // Wait for the required amount of events to be received or for 10 seconds
176         for (int i = 0; i < 20; i++) {
177             ThreadUtilities.sleep(300);
178             response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats")
179                     .request("application/json").get();
180
181             if (Response.Status.OK.getStatusCode() != response.getStatus()) {
182                 break;
183             }
184
185             final String responseString = response.readEntity(String.class);
186
187             @SuppressWarnings("unchecked")
188             final Map<String, Object> jsonMap = new Gson().fromJson(responseString, Map.class);
189             if ((double) jsonMap.get("PUT") == 20) {
190                 break;
191             }
192         }
193
194         apexMain.shutdown();
195
196         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
197     }
198
199     /**
200      * Test file events no url.
201      *
202      * @throws MessagingException the messaging exception
203      * @throws ApexException the apex exception
204      * @throws IOException Signals that an I/O exception has occurred.
205      */
206     @Test
207     public void testFileEventsNoUrl() throws MessagingException, ApexException, IOException {
208         System.setOut(new PrintStream(outContent));
209         System.setErr(new PrintStream(errContent));
210
211         final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventNoURL.json"};
212         final ApexMain apexMain = new ApexMain(args);
213
214         ThreadUtilities.sleep(200);
215         apexMain.shutdown();
216
217         final String outString = outContent.toString();
218
219         System.setOut(stdout);
220         System.setErr(stderr);
221
222         LOGGER.info("NoUrl-OUTSTRING=\n" + outString + "\nEnd-NoUrl");
223         assertTrue(outString.contains(" no URL has been set for event sending on RESTCLIENT"));
224     }
225
226     /**
227      * Test file events bad url.
228      *
229      * @throws MessagingException the messaging exception
230      * @throws ApexException the apex exception
231      * @throws IOException Signals that an I/O exception has occurred.
232      */
233     @Test
234     public void testFileEventsBadUrl() throws MessagingException, ApexException, IOException {
235         System.setOut(new PrintStream(outContent));
236         System.setErr(new PrintStream(errContent));
237
238         final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventBadURL.json"};
239         final ApexMain apexMain = new ApexMain(args);
240
241         ThreadUtilities.sleep(2000);
242         apexMain.shutdown();
243
244         final String outString = outContent.toString();
245
246         System.setOut(stdout);
247         System.setErr(stderr);
248
249         LOGGER.info("BadUrl-OUTSTRING=\n" + outString + "\nEnd-BadUrl");
250         assertTrue(outString.contains(
251                 "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/Bad\" using HTTP \"POST\" failed with status code 404"));
252     }
253
254     /**
255      * Test file events bad http method.
256      *
257      * @throws MessagingException the messaging exception
258      * @throws ApexException the apex exception
259      * @throws IOException Signals that an I/O exception has occurred.
260      */
261     @Test
262     public void testFileEventsBadHttpMethod() throws MessagingException, ApexException, IOException {
263         System.setOut(new PrintStream(outContent));
264         System.setErr(new PrintStream(errContent));
265
266         final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json"};
267         final ApexMain apexMain = new ApexMain(args);
268
269         ThreadUtilities.sleep(200);
270         apexMain.shutdown();
271
272         final String outString = outContent.toString();
273
274         System.setOut(stdout);
275         System.setErr(stderr);
276
277         LOGGER.info("BadHttpMethod-OUTSTRING=\n" + outString + "\nEnd-BadHttpMethod");
278         assertTrue(outString
279                 .contains("specified HTTP method of \"DELETE\" is invalid, only HTTP methods \"POST\" and \"PUT\" "
280                         + "are supported for event sending on REST client producer"));
281     }
282
283     /**
284      * Test file events bad response.
285      *
286      * @throws MessagingException the messaging exception
287      * @throws ApexException the apex exception
288      * @throws IOException Signals that an I/O exception has occurred.
289      */
290     @Test
291     public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException {
292         System.setOut(new PrintStream(outContent));
293         System.setErr(new PrintStream(errContent));
294
295         final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json"};
296         final ApexMain apexMain = new ApexMain(args);
297
298         ThreadUtilities.sleep(2000);
299         apexMain.shutdown();
300
301         final String outString = outContent.toString();
302
303         System.setOut(stdout);
304         System.setErr(stderr);
305
306         LOGGER.info("BadResponse-OUTSTRING=\n" + outString + "\nEnd-BadResponse");
307         assertTrue(outString.contains(
308                 "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/PostEventBadResponse\""
309                         + " using HTTP \"POST\" failed with status code 400"));
310     }
311 }