2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.pdpx.main;
27 import java.io.IOException;
28 import java.nio.charset.StandardCharsets;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.security.SecureRandom;
32 import java.util.concurrent.atomic.AtomicBoolean;
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 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.common.utils.network.NetworkUtil;
45 import org.onap.policy.common.utils.resources.ResourceUtils;
46 import org.onap.policy.common.utils.security.SelfSignedKeyStore;
47 import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
48 import org.onap.policy.pdpx.main.startstop.Main;
49 import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
50 import org.powermock.reflect.Whitebox;
53 * Common base class for REST service tests.
55 public class CommonRest {
58 * Full path to the config file.
60 public static final String CONFIG_FILE;
63 * Path corresponding to {@link #CONFIG_FILE}.
65 private static final Path CONFIG_PATH;
68 * Contents read from the "standard" config file, which still contains ${xxx}
71 private static final String STD_CONFIG;
74 * Port that was last allocated for the server.
76 protected static int port;
79 * "Main" that was last started.
81 private static Main main;
84 * Records the "alive" state of the activator while it's temporarily updated by
85 * various junit tests. The {@link #tearDown()} method restores the "alive" state back
88 private boolean activatorWasAlive;
92 File file = new File(ResourceUtils.getFilePath4Resource("parameters/XacmlPdpConfigParameters_Std.json"));
93 STD_CONFIG = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
95 file = new File(file.getParentFile(), "Test_XacmlPdpConfigParameters.json");
98 CONFIG_FILE = file.getAbsolutePath();
99 CONFIG_PATH = new File(CONFIG_FILE).toPath();
101 } catch (IOException e) {
102 throw new ExceptionInInitializerError(e);
107 * Configures system properties and creates a JSON config file.
109 * @throws Exception if an error occurs
112 public static void setUpBeforeClass() throws Exception {
113 System.setProperty("javax.net.ssl.keyStore", new SelfSignedKeyStore().getKeystoreName());
114 System.setProperty("javax.net.ssl.keyStorePassword", SelfSignedKeyStore.KEYSTORE_PASSWORD);
116 System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
117 System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
121 final String[] xacmlPdpConfigParameters = {"-c", CommonRest.CONFIG_FILE};
122 main = new Main(xacmlPdpConfigParameters);
124 // start xacml rest controller
125 XacmlPdpActivator.getCurrent().startXacmlRestController();
127 if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
128 throw new IllegalStateException("server is not listening on port " + port);
136 public static void tearDownAfterClass() {
141 * Resets the statistics.
144 public void setUp() {
145 activatorWasAlive = XacmlPdpActivator.getCurrent().isAlive();
146 XacmlPdpStatisticsManager.getCurrent().resetAllStatistics();
150 * Restores the "alive" status of the activator.
153 public void tearDown() {
154 markActivator(activatorWasAlive);
160 protected static void stopMain() {
165 * Writes a JSON config file, substituting an allocated port number for occurrences of
168 * @return the allocated server port
169 * @throws IOException if the config file cannot be created
171 public static int writeJsonConfig() throws IOException {
172 port = NetworkUtil.allocPort();
174 String config = STD_CONFIG.replace("${port}", String.valueOf(port));
175 Files.write(CONFIG_PATH, config.getBytes(StandardCharsets.UTF_8));
181 * Sends an HTTPS request to an endpoint of the PDP's REST API.
183 * @param endpoint target endpoint
184 * @return a request builder
185 * @throws Exception if an error occurs
187 protected Invocation.Builder sendHttpsRequest(final String endpoint) throws Exception {
188 // always trust the certificate
189 final SSLContext sc = SSLContext.getInstance("TLSv1.2");
190 sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
192 // always trust the host name
193 final ClientBuilder clientBuilder =
194 ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
196 final Client client = clientBuilder.build();
197 final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
198 client.register(feature);
200 final WebTarget webTarget = client.target("https://localhost:" + port + "/policy/pdpx/v1/" + endpoint);
202 return webTarget.request(MediaType.APPLICATION_JSON);
206 * Mark the activator as dead, but leave its REST server running.
208 protected void markActivatorDead() {
209 markActivator(false);
213 * Changes the internal "alive" status of the activator to a new value.
215 * @param newAlive the new "alive" status
217 private void markActivator(boolean newAlive) {
218 Object manager = Whitebox.getInternalState(XacmlPdpActivator.getCurrent(), "serviceManager");
219 AtomicBoolean running = Whitebox.getInternalState(manager, "running");
220 running.set(newAlive);