2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 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.apex.services.onappf.rest;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertTrue;
27 import java.security.SecureRandom;
29 import java.util.Properties;
30 import java.util.function.Function;
31 import javax.net.ssl.SSLContext;
32 import javax.ws.rs.client.Client;
33 import javax.ws.rs.client.ClientBuilder;
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.junit.After;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.onap.policy.apex.services.onappf.ApexStarterActivator;
45 import org.onap.policy.apex.services.onappf.ApexStarterConstants;
46 import org.onap.policy.apex.services.onappf.ApexStarterMain;
47 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
48 import org.onap.policy.apex.services.onappf.parameters.CommonTestData;
49 import org.onap.policy.common.gson.GsonMessageBodyHandler;
50 import org.onap.policy.common.utils.coder.Coder;
51 import org.onap.policy.common.utils.coder.StandardCoder;
52 import org.onap.policy.common.utils.network.NetworkUtil;
53 import org.onap.policy.common.utils.services.Registry;
54 import org.powermock.reflect.Whitebox;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * Class to perform unit test of {@link ApexStarterRestServer}.
61 * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
63 public class CommonApexStarterRestServer {
65 private static final Logger LOGGER = LoggerFactory.getLogger(CommonApexStarterRestServer.class);
67 private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
69 private static Coder coder = new StandardCoder();
71 public static final String NOT_ALIVE = "not alive";
72 public static final String ALIVE = "alive";
73 public static final String SELF = "self";
74 public static final String NAME = "Policy PDP-A";
75 public static final String ENDPOINT_PREFIX = "policy/apex-pdp/v1/";
77 private static int port;
78 protected static String httpsPrefix;
80 private static ApexStarterMain main;
82 private boolean activatorWasAlive;
85 * Allocates a port for the server, writes a config file, and then starts Main.
87 * @throws Exception if an error occurs
90 public static void setUpBeforeClass() throws Exception {
91 port = NetworkUtil.allocPort();
93 httpsPrefix = "https://localhost:" + port + "/";
104 public static void teardownAfterClass() {
108 } catch (final ApexStarterException exp) {
109 LOGGER.error("cannot stop main", exp);
116 * @throws Exception if an error occurs
119 public void setUp() throws Exception {
120 // restart, if not currently running
126 Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class).isAlive();
130 * Restores the activator's "alive" state.
133 public void tearDown() {
134 markActivator(activatorWasAlive);
138 * Verifies that an endpoint appears within the swagger response.
140 * @param endpoint the endpoint of interest
141 * @throws Exception if an error occurs
143 protected void testSwagger(final String endpoint) throws Exception {
144 final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml", true);
145 final String resp = invocationBuilder.get(String.class);
147 assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":"));
151 * Makes a parameter configuration file.
153 * @throws Exception if an error occurs
155 private static void makeConfigFile() throws Exception {
156 final Map<String, Object> config =
157 new CommonTestData().getApexStarterParameterGroupMap("ApexStarterParameterGroup");
159 @SuppressWarnings("unchecked")
160 final Map<String, Object> restParams = (Map<String, Object>) config.get("restServerParameters");
161 restParams.put("port", port);
163 final File file = new File("src/test/resources/TestConfigParams.json");
166 coder.encode(file, config);
172 * @throws Exception if an error occurs
174 private static void startMain() throws Exception {
175 Registry.newRegistry();
177 // make sure port is available
178 if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) {
179 throw new IllegalStateException("port " + port + " is still in use");
182 final Properties systemProps = System.getProperties();
183 systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
184 systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
185 System.setProperties(systemProps);
187 final String[] apexStarterConfigParameters = { "-c", "src/test/resources/TestConfigParams.json" };
189 main = new ApexStarterMain(apexStarterConfigParameters);
191 if (!NetworkUtil.isTcpPortOpen("localhost", port, 6, 10000L)) {
192 throw new IllegalStateException("server is not listening on port " + port);
199 * @throws Exception if an error occurs
201 private static void stopMain() throws ApexStarterException {
203 final ApexStarterMain main2 = main;
210 private void markActivator(final boolean wasAlive) {
211 final Object manager = Whitebox.getInternalState(
212 Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class), "manager");
213 Whitebox.setInternalState(manager, "running", wasAlive);
217 * Verifies that unauthorized requests fail.
219 * @param endpoint the target end point
220 * @param sender function that sends the requests to the target
221 * @throws Exception if an error occurs
223 protected void checkUnauthRequest(final String endpoint, final Function<Invocation.Builder, Response> sender)
225 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(),
226 sender.apply(sendNoAuthRequest(endpoint)).getStatus());
230 * Sends a request to an endpoint.
232 * @param endpoint the target endpoint
233 * @return a request builder
234 * @throws Exception if an error occurs
236 protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
237 return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, true);
241 * Sends a request to an endpoint, without any authorization header.
243 * @param endpoint the target endpoint
244 * @return a request builder
245 * @throws Exception if an error occurs
247 protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
248 return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, false);
252 * Sends a request to a fully qualified endpoint.
254 * @param fullyQualifiedEndpoint the fully qualified target endpoint
255 * @param includeAuth if authorization header should be included
256 * @return a request builder
257 * @throws Exception if an error occurs
259 protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, final boolean includeAuth)
261 final SSLContext sc = SSLContext.getInstance("TLSv1.2");
262 sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
263 final ClientBuilder clientBuilder =
264 ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
265 final Client client = clientBuilder.build();
267 client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
268 client.register(GsonMessageBodyHandler.class);
271 final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
272 client.register(feature);
275 final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
277 return webTarget.request(MediaType.APPLICATION_JSON);