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