2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * Modifications Copyright (C) 2019 AT&T Intellectual Property.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.main.rest;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
28 import java.io.FileOutputStream;
29 import java.nio.charset.StandardCharsets;
30 import java.security.SecureRandom;
31 import java.util.Properties;
32 import java.util.function.Function;
33 import javax.net.ssl.SSLContext;
34 import javax.ws.rs.client.Client;
35 import javax.ws.rs.client.ClientBuilder;
36 import javax.ws.rs.client.Invocation;
37 import javax.ws.rs.client.WebTarget;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.Response;
40 import org.glassfish.jersey.client.ClientProperties;
41 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
42 import org.junit.After;
43 import org.junit.AfterClass;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
48 import org.onap.policy.common.gson.GsonMessageBodyHandler;
49 import org.onap.policy.common.utils.network.NetworkUtil;
50 import org.onap.policy.common.utils.services.Registry;
51 import org.onap.policy.pap.main.PapConstants;
52 import org.onap.policy.pap.main.PolicyPapException;
53 import org.onap.policy.pap.main.parameters.CommonTestData;
54 import org.onap.policy.pap.main.startstop.Main;
55 import org.onap.policy.pap.main.startstop.PapActivator;
56 import org.powermock.reflect.Whitebox;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 * Class to perform unit test of {@link PapRestServer}.
63 * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
65 public class CommonPapRestServer {
67 private static final Logger LOGGER = LoggerFactory.getLogger(CommonPapRestServer.class);
69 private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
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 PAP";
75 public static final String ENDPOINT_PREFIX = "policy/pap/v1/";
77 private static int port;
78 protected static String httpsPrefix;
80 private static Main 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 + "/";
97 HttpServletServer.factory.destroy();
98 TopicEndpoint.manager.shutdown();
100 CommonTestData.newDb();
109 public static void teardownAfterClass() {
113 } catch (PolicyPapException exp) {
114 LOGGER.error("cannot stop main", exp);
121 * @throws Exception if an error occurs
124 public void setUp() throws Exception {
125 // restart, if not currently running
130 activatorWasAlive = Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class).isAlive();
134 * Restores the activator's "alive" state.
137 public void tearDown() {
138 markActivator(activatorWasAlive);
142 * Verifies that an endpoint appears within the swagger response.
144 * @param endpoint the endpoint of interest
145 * @throws Exception if an error occurs
147 protected void testSwagger(final String endpoint) throws Exception {
148 final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml", true);
149 final String resp = invocationBuilder.get(String.class);
151 assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":"));
155 * Makes a parameter configuration file.
157 * @throws Exception if an error occurs
159 private static void makeConfigFile() throws Exception {
160 String json = new CommonTestData().getPapParameterGroupAsString(port);
162 File file = new File("src/test/resources/parameters/TestConfigParams.json");
165 try (FileOutputStream output = new FileOutputStream(file)) {
166 output.write(json.getBytes(StandardCharsets.UTF_8));
173 * @throws Exception if an error occurs
175 private static void startMain() throws Exception {
176 Registry.newRegistry();
178 // make sure port is available
179 if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) {
180 throw new IllegalStateException("port " + port + " is still in use");
183 final Properties systemProps = System.getProperties();
184 systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
185 systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
186 System.setProperties(systemProps);
188 final String[] papConfigParameters = { "-c", "src/test/resources/parameters/TestConfigParams.json" };
190 main = new Main(papConfigParameters);
192 if (!NetworkUtil.isTcpPortOpen("localhost", port, 6, 10000L)) {
193 throw new IllegalStateException("server is not listening on port " + port);
200 * @throws Exception if an error occurs
202 private static void stopMain() throws PolicyPapException {
212 * Mark the activator as dead, but leave its REST server running.
214 protected void markActivatorDead() {
215 markActivator(false);
218 private void markActivator(boolean wasAlive) {
219 Object manager = Whitebox.getInternalState(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class),
221 Whitebox.setInternalState(manager, "running", wasAlive);
225 * Verifies that unauthorized requests fail.
227 * @param endpoint the target end point
228 * @param sender function that sends the requests to the target
229 * @throws Exception if an error occurs
231 protected void checkUnauthRequest(final String endpoint, Function<Invocation.Builder, Response> sender)
233 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(),
234 sender.apply(sendNoAuthRequest(endpoint)).getStatus());
238 * Sends a request to an endpoint.
240 * @param endpoint the target endpoint
241 * @return a request builder
242 * @throws Exception if an error occurs
244 protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
245 return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, true);
249 * Sends a request to an endpoint, without any authorization header.
251 * @param endpoint the target endpoint
252 * @return a request builder
253 * @throws Exception if an error occurs
255 protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
256 return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, false);
260 * Sends a request to a fully qualified endpoint.
262 * @param fullyQualifiedEndpoint the fully qualified target endpoint
263 * @param includeAuth if authorization header should be included
264 * @return a request builder
265 * @throws Exception if an error occurs
267 protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
269 final SSLContext sc = SSLContext.getInstance("TLSv1.2");
270 sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
271 final ClientBuilder clientBuilder =
272 ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
273 final Client client = clientBuilder.build();
275 client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
276 client.register(GsonMessageBodyHandler.class);
279 final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
280 client.register(feature);
283 final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
285 return webTarget.request(MediaType.APPLICATION_JSON);