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