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 if the NetworkUtil method calls are interrupted
132 * @throws IllegalStateException if a controller cannot be started on the requested port
134 protected static void startMain() throws InterruptedException {
135 Registry.newRegistry();
137 // make sure port is available
138 if (NetworkUtil.isTcpPortOpen(SELF, port, 1, 1L)) {
139 throw new IllegalStateException("port " + port + " is not available");
142 final String[] configParameters = {"-c", String.format(CONFIG_FILE, port)};
144 main = new Main(configParameters);
146 if (!NetworkUtil.isTcpPortOpen(SELF, port, 40, 250L)) {
147 throw new IllegalStateException("server is not listening on port " + port);
154 * @throws ControlLoopException if an error occurs shutting down the controller
155 * @throws InterruptedException if the NetworkUtil method calls are interrupted
156 * @throws IllegalStateException if a controller cannot be started on the requested port
158 private static void stopMain() throws ControlLoopException, InterruptedException {
165 // make sure port is close
166 if (NetworkUtil.isTcpPortOpen(SELF, port, 1, 1L)) {
167 throw new IllegalStateException("port " + port + " is still in use");
172 * Sends a request to an endpoint.
174 * @param endpoint the target endpoint
175 * @return a request builder
176 * @throws Exception if an error occurs
178 protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
179 return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, true);
183 * Sends a request to an endpoint, without any authorization header.
185 * @param endpoint the target endpoint
186 * @return a request builder
187 * @throws Exception if an error occurs
189 protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
190 return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, false);
194 * Sends a request to a fully qualified endpoint.
196 * @param fullyQualifiedEndpoint the fully qualified target endpoint
197 * @param includeAuth if authorization header should be included
198 * @return a request builder
199 * @throws Exception if an error occurs
201 protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
203 final Client client = ClientBuilder.newBuilder().build();
205 client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
206 client.register(GsonMessageBodyHandler.class);
209 client.register(HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"));
212 final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
214 return webTarget.request(MediaType.APPLICATION_JSON);
218 * Assert that POST call is Unauthorized.
220 * @param endPoint the endpoint
221 * @param entity the entity ofthe body
222 * @throws Exception if an error occurs
224 protected void assertUnauthorizedPost(final String endPoint, final Entity<?> entity) throws Exception {
225 Response rawresp = sendNoAuthRequest(endPoint).post(entity);
226 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
230 * Assert that PUT call is Unauthorized.
232 * @param endPoint the endpoint
233 * @param entity the entity ofthe body
234 * @throws Exception if an error occurs
236 protected void assertUnauthorizedPut(final String endPoint, final Entity<?> entity) throws Exception {
237 Response rawresp = sendNoAuthRequest(endPoint).put(entity);
238 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
242 * Assert that GET call is Unauthorized.
244 * @param endPoint the endpoint
245 * @throws Exception if an error occurs
247 protected void assertUnauthorizedGet(final String endPoint) throws Exception {
248 Response rawresp = sendNoAuthRequest(endPoint).buildGet().invoke();
249 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
253 * Assert that DELETE call is Unauthorized.
255 * @param endPoint the endpoint
256 * @throws Exception if an error occurs
258 protected void assertUnauthorizedDelete(final String endPoint) throws Exception {
259 Response rawresp = sendNoAuthRequest(endPoint).delete();
260 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());