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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.clamp.controlloop.runtime.util.rest;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertTrue;
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;
51 * Class to perform Rest unit tests.
54 public class CommonRestController {
56 private static final String CONFIG_FILE = "src/test/resources/parameters/RuntimeConfigParameters%d.json";
58 private static final Logger LOGGER = LoggerFactory.getLogger(CommonRestController.class);
60 public static final String SELF = NetworkUtil.getHostname();
61 public static final String ENDPOINT_PREFIX = "onap/controlloop/v2/";
63 private static int port;
64 private static String httpPrefix;
65 private static Main main;
68 * Allocates a port for the server, writes a config file, and then starts Main.
70 * @param dbName database name
71 * @throws Exception if an error occurs
73 public static void setUpBeforeClass(final String dbName) throws Exception {
74 port = NetworkUtil.allocPort();
76 httpPrefix = "http://" + SELF + ":" + port + "/";
78 makeConfigFile(dbName);
85 public static void teardownAfterClass() {
88 } catch (Exception ex) {
89 LOGGER.error("cannot stop main", ex);
93 protected static PolicyModelsProviderParameters getParameters() {
94 return main.getParameters().getDatabaseProviderParameters();
98 * Verifies that an endpoint appears within the swagger response.
100 * @param endpoint the endpoint of interest
101 * @throws Exception if an error occurs
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);
107 assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":"));
111 * Makes a parameter configuration file.
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
117 private static void makeConfigFile(final String dbName) throws FileNotFoundException, IOException {
118 String json = CommonTestData.getParameterGroupAsString(port, dbName);
120 File file = new File(String.format(CONFIG_FILE, port));
123 try (FileOutputStream output = new FileOutputStream(file)) {
124 output.write(json.getBytes(StandardCharsets.UTF_8));
131 * @throws InterruptedException
133 * @throws Exception if an error occurs
135 protected static void startMain() throws InterruptedException {
136 Registry.newRegistry();
138 // make sure port is available
139 if (NetworkUtil.isTcpPortOpen(SELF, port, 1, 1L)) {
140 throw new IllegalStateException("port " + port + " is not available");
143 final String[] configParameters = {"-c", String.format(CONFIG_FILE, port)};
145 main = new Main(configParameters);
147 if (!NetworkUtil.isTcpPortOpen(SELF, port, 40, 250L)) {
148 throw new IllegalStateException("server is not listening on port " + port);
155 * @throws ControlLoopException
157 * @throws Exception if an error occurs
159 private static void stopMain() throws Exception {
166 // make sure port is close
167 if (NetworkUtil.isTcpPortOpen(SELF, port, 1, 1L)) {
168 throw new IllegalStateException("port " + port + " is still in use");
173 * Sends a request to an endpoint.
175 * @param endpoint the target endpoint
176 * @return a request builder
177 * @throws Exception if an error occurs
179 protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
180 return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, true);
184 * Sends a request to an endpoint, without any authorization header.
186 * @param endpoint the target endpoint
187 * @return a request builder
188 * @throws Exception if an error occurs
190 protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
191 return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, false);
195 * Sends a request to a fully qualified endpoint.
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
202 protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
204 final Client client = ClientBuilder.newBuilder().build();
206 client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
207 client.register(GsonMessageBodyHandler.class);
210 client.register(HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"));
213 final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
215 return webTarget.request(MediaType.APPLICATION_JSON);
219 * Assert that POST call is Unauthorized.
221 * @param endPoint the endpoint
222 * @param entity the entity ofthe body
223 * @throws Exception if an error occurs
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());
231 * Assert that PUT call is Unauthorized.
233 * @param endPoint the endpoint
234 * @param entity the entity ofthe body
235 * @throws Exception if an error occurs
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());
243 * Assert that GET call is Unauthorized.
245 * @param endPoint the endpoint
246 * @throws Exception if an error occurs
248 protected void assertUnauthorizedGet(final String endPoint) throws Exception {
249 Response rawresp = sendNoAuthRequest(endPoint).buildGet().invoke();
250 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
254 * Assert that DELETE call is Unauthorized.
256 * @param endPoint the endpoint
257 * @throws Exception if an error occurs
259 protected void assertUnauthorizedDelete(final String endPoint) throws Exception {
260 Response rawresp = sendNoAuthRequest(endPoint).delete();
261 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());