83cfe9b52d1d26fec15e832ea2a5e71fb4c13631
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.controlloop.runtime.util.rest;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertTrue;
25
26 import java.io.File;
27 import java.io.FileNotFoundException;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.nio.charset.StandardCharsets;
31 import javax.ws.rs.client.Client;
32 import javax.ws.rs.client.ClientBuilder;
33 import javax.ws.rs.client.Entity;
34 import javax.ws.rs.client.Invocation;
35 import javax.ws.rs.client.WebTarget;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38 import org.glassfish.jersey.client.ClientProperties;
39 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
40 import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException;
41 import org.onap.policy.clamp.controlloop.runtime.main.startstop.Main;
42 import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData;
43 import org.onap.policy.common.gson.GsonMessageBodyHandler;
44 import org.onap.policy.common.utils.network.NetworkUtil;
45 import org.onap.policy.common.utils.services.Registry;
46 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Class to perform Rest unit tests.
52  *
53  */
54 public class CommonRestController {
55
56     private static final String CONFIG_FILE = "src/test/resources/parameters/RuntimeConfigParameters%d.json";
57
58     private static final Logger LOGGER = LoggerFactory.getLogger(CommonRestController.class);
59
60     public static final String SELF = NetworkUtil.getHostname();
61     public static final String ENDPOINT_PREFIX = "onap/controlloop/v2/";
62
63     private static int port;
64     private static String httpPrefix;
65     private static Main main;
66
67     /**
68      * Allocates a port for the server, writes a config file, and then starts Main.
69      *
70      * @param dbName database name
71      * @throws Exception if an error occurs
72      */
73     public static void setUpBeforeClass(final String dbName) throws Exception {
74         port = NetworkUtil.allocPort();
75
76         httpPrefix = "http://" + SELF + ":" + port + "/";
77
78         makeConfigFile(dbName);
79         startMain();
80     }
81
82     /**
83      * Stops Main.
84      */
85     public static void teardownAfterClass() {
86         try {
87             stopMain();
88         } catch (Exception ex) {
89             LOGGER.error("cannot stop main", ex);
90         }
91     }
92
93     protected static PolicyModelsProviderParameters getParameters() {
94         return main.getParameters().getDatabaseProviderParameters();
95     }
96
97     /**
98      * Verifies that an endpoint appears within the swagger response.
99      *
100      * @param endpoint the endpoint of interest
101      * @throws Exception if an error occurs
102      */
103     protected void testSwagger(final String endpoint) throws Exception {
104         final Invocation.Builder invocationBuilder = sendFqeRequest(httpPrefix + "swagger.yaml", true);
105         final String resp = invocationBuilder.get(String.class);
106
107         assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":"));
108     }
109
110     /**
111      * Makes a parameter configuration file.
112      *
113      * @param dbName database name
114      * @throws IOException if an error occurs writing the configuration file
115      * @throws FileNotFoundException if an error occurs writing the configuration file
116      */
117     private static void makeConfigFile(final String dbName) throws FileNotFoundException, IOException {
118         String json = CommonTestData.getParameterGroupAsString(port, dbName);
119
120         File file = new File(String.format(CONFIG_FILE, port));
121         file.deleteOnExit();
122
123         try (FileOutputStream output = new FileOutputStream(file)) {
124             output.write(json.getBytes(StandardCharsets.UTF_8));
125         }
126     }
127
128     /**
129      * Starts the "Main".
130      *
131      * @throws InterruptedException
132      *
133      * @throws Exception if an error occurs
134      */
135     protected static void startMain() throws InterruptedException {
136         Registry.newRegistry();
137
138         // make sure port is available
139         if (NetworkUtil.isTcpPortOpen(SELF, port, 1, 1L)) {
140             throw new IllegalStateException("port " + port + " is not available");
141         }
142
143         final String[] configParameters = {"-c", String.format(CONFIG_FILE, port)};
144
145         main = new Main(configParameters);
146
147         if (!NetworkUtil.isTcpPortOpen(SELF, port, 40, 250L)) {
148             throw new IllegalStateException("server is not listening on port " + port);
149         }
150     }
151
152     /**
153      * Stops the "Main".
154      *
155      * @throws ControlLoopException
156      *
157      * @throws Exception if an error occurs
158      */
159     private static void stopMain() throws Exception {
160         if (main != null) {
161             Main main2 = main;
162             main = null;
163
164             main2.shutdown();
165         }
166         // make sure port is close
167         if (NetworkUtil.isTcpPortOpen(SELF, port, 1, 1L)) {
168             throw new IllegalStateException("port " + port + " is still in use");
169         }
170     }
171
172     /**
173      * Sends a request to an endpoint.
174      *
175      * @param endpoint the target endpoint
176      * @return a request builder
177      * @throws Exception if an error occurs
178      */
179     protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
180         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, true);
181     }
182
183     /**
184      * Sends a request to an endpoint, without any authorization header.
185      *
186      * @param endpoint the target endpoint
187      * @return a request builder
188      * @throws Exception if an error occurs
189      */
190     protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
191         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, false);
192     }
193
194     /**
195      * Sends a request to a fully qualified endpoint.
196      *
197      * @param fullyQualifiedEndpoint the fully qualified target endpoint
198      * @param includeAuth if authorization header should be included
199      * @return a request builder
200      * @throws Exception if an error occurs
201      */
202     protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
203             throws Exception {
204         final Client client = ClientBuilder.newBuilder().build();
205
206         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
207         client.register(GsonMessageBodyHandler.class);
208
209         if (includeAuth) {
210             client.register(HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"));
211         }
212
213         final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
214
215         return webTarget.request(MediaType.APPLICATION_JSON);
216     }
217
218     /**
219      * Assert that POST call is Unauthorized.
220      *
221      * @param endPoint the endpoint
222      * @param entity the entity ofthe body
223      * @throws Exception if an error occurs
224      */
225     protected void assertUnauthorizedPost(final String endPoint, final Entity<?> entity) throws Exception {
226         Response rawresp = sendNoAuthRequest(endPoint).post(entity);
227         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
228     }
229
230     /**
231      * Assert that PUT call is Unauthorized.
232      *
233      * @param endPoint the endpoint
234      * @param entity the entity ofthe body
235      * @throws Exception if an error occurs
236      */
237     protected void assertUnauthorizedPut(final String endPoint, final Entity<?> entity) throws Exception {
238         Response rawresp = sendNoAuthRequest(endPoint).put(entity);
239         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
240     }
241
242     /**
243      * Assert that GET call is Unauthorized.
244      *
245      * @param endPoint the endpoint
246      * @throws Exception if an error occurs
247      */
248     protected void assertUnauthorizedGet(final String endPoint) throws Exception {
249         Response rawresp = sendNoAuthRequest(endPoint).buildGet().invoke();
250         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
251     }
252
253     /**
254      * Assert that DELETE call is Unauthorized.
255      *
256      * @param endPoint the endpoint
257      * @throws Exception if an error occurs
258      */
259     protected void assertUnauthorizedDelete(final String endPoint) throws Exception {
260         Response rawresp = sendNoAuthRequest(endPoint).delete();
261         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
262     }
263 }