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