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