Remove topic.properties and incorporate into overall config file for xacml
[policy/xacml-pdp.git] / main / src / test / java / org / onap / policy / pdpx / main / CommonRest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019 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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.pdpx.main;
25
26 import java.io.File;
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 javax.net.ssl.SSLContext;
33 import javax.ws.rs.client.Client;
34 import javax.ws.rs.client.ClientBuilder;
35 import javax.ws.rs.client.Invocation;
36 import javax.ws.rs.client.WebTarget;
37 import javax.ws.rs.core.MediaType;
38 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
39 import org.junit.After;
40 import org.junit.AfterClass;
41 import org.junit.Before;
42 import org.junit.BeforeClass;
43 import org.onap.policy.common.utils.network.NetworkUtil;
44 import org.onap.policy.common.utils.resources.ResourceUtils;
45 import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
46 import org.onap.policy.pdpx.main.startstop.Main;
47 import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
48 import org.powermock.reflect.Whitebox;
49
50 /**
51  * Common base class for REST service tests.
52  */
53 public class CommonRest {
54     private static final String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
55
56     /**
57      * Full path to the config file.
58      */
59     public static final String CONFIG_FILE;
60
61     /**
62      * Path corresponding to {@link #CONFIG_FILE}.
63      */
64     private static final Path CONFIG_PATH;
65
66     /**
67      * Contents read from the "standard" config file, which still contains ${xxx}
68      * place-holders.
69      */
70     private static final String STD_CONFIG;
71
72     /**
73      * Port that was last allocated for the server.
74      */
75     protected static int port;
76
77     /**
78      * "Main" that was last started.
79      */
80     private static Main main;
81
82     /**
83      * Records the "alive" state of the activator while it's temporarily updated by
84      * various junit tests. The {@link #tearDown()} method restores the "alive" state back
85      * to this value.
86      */
87     private boolean activatorWasAlive;
88
89     static {
90         try {
91             File file = new File(ResourceUtils.getFilePath4Resource("parameters/XacmlPdpConfigParameters_Std.json"));
92             STD_CONFIG = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
93
94             file = new File(file.getParentFile(), "Test_XacmlPdpConfigParameters.json");
95             file.deleteOnExit();
96
97             CONFIG_FILE = file.getAbsolutePath();
98             CONFIG_PATH = new File(CONFIG_FILE).toPath();
99
100         } catch (IOException e) {
101             throw new ExceptionInInitializerError(e);
102         }
103     }
104
105     /**
106      * Configures system properties and creates a JSON config file.
107      *
108      * @throws Exception if an error occurs
109      */
110     @BeforeClass
111     public static void setUpBeforeClass() throws Exception {
112         System.setProperty("javax.net.ssl.keyStore", KEYSTORE);
113         System.setProperty("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
114
115         System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
116         System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
117
118         writeJsonConfig();
119
120         final String[] xacmlPdpConfigParameters = {"-c", CommonRest.CONFIG_FILE};
121         main = new Main(xacmlPdpConfigParameters);
122
123         if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
124             throw new IllegalStateException("server is not listening on port " + port);
125         }
126     }
127
128     /**
129      * Stops the "Main".
130      */
131     @AfterClass
132     public static void tearDownAfterClass() {
133         stopMain();
134     }
135
136     /**
137      * Resets the statistics.
138      */
139     @Before
140     public void setUp() {
141         activatorWasAlive = XacmlPdpActivator.getCurrent().isAlive();
142         XacmlPdpStatisticsManager.getCurrent().resetAllStatistics();
143     }
144
145     /**
146      * Restores the "alive" status of the activator.
147      */
148     @After
149     public void tearDown() {
150         markActivator(activatorWasAlive);
151     }
152
153     /**
154      * Stops the "main".
155      */
156     protected static void stopMain() {
157         main.shutdown();
158     }
159
160     /**
161      * Writes a JSON config file, substituting an allocated port number for occurrences of
162      * "${port}".
163      *
164      * @return the allocated server port
165      * @throws IOException if the config file cannot be created
166      */
167     public static int writeJsonConfig() throws IOException {
168         port = NetworkUtil.allocPort();
169
170         String config = STD_CONFIG.replace("${port}", String.valueOf(port));
171         Files.write(CONFIG_PATH, config.getBytes(StandardCharsets.UTF_8));
172
173         return port;
174     }
175
176     /**
177      * Sends an HTTPS request to an endpoint of the PDP's REST API.
178      *
179      * @param endpoint target endpoint
180      * @return a request builder
181      * @throws Exception if an error occurs
182      */
183     protected Invocation.Builder sendHttpsRequest(final String endpoint) throws Exception {
184         // always trust the certificate
185         final SSLContext sc = SSLContext.getInstance("TLSv1.2");
186         sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
187
188         // always trust the host name
189         final ClientBuilder clientBuilder =
190                         ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
191
192         final Client client = clientBuilder.build();
193         final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
194         client.register(feature);
195
196         final WebTarget webTarget = client.target("https://localhost:" + port + "/policy/pdpx/v1/" + endpoint);
197
198         return webTarget.request(MediaType.APPLICATION_JSON);
199     }
200
201     /**
202      * Mark the activator as dead, but leave its REST server running.
203      */
204     protected void markActivatorDead() {
205         markActivator(false);
206     }
207
208     /**
209      * Changes the internal "alive" status of the activator to a new value.
210      *
211      * @param newAlive the new "alive" status
212      */
213     private void markActivator(boolean newAlive) {
214         Object manager = Whitebox.getInternalState(XacmlPdpActivator.getCurrent(), "serviceManager");
215         Whitebox.setInternalState(manager, "running", newAlive);
216     }
217 }