3823365b038e7cd0caea64cd02703deb48addc7b
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / CommonPapRestServer.java
1 /*
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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.main.rest;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
26
27 import java.io.File;
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.TopicEndpointManager;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
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;
59
60 /**
61  * Class to perform unit test of {@link PapRestServer}.
62  *
63  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
64  */
65 public class CommonPapRestServer {
66
67     protected static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParams.json";
68
69     private static final Logger LOGGER = LoggerFactory.getLogger(CommonPapRestServer.class);
70
71     private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
72
73     public static final String NOT_ALIVE = "not alive";
74     public static final String ALIVE = "alive";
75     public static final String SELF = NetworkUtil.getHostname();
76     public static final String NAME = "Policy PAP";
77     public static final String ENDPOINT_PREFIX = "policy/pap/v1/";
78
79     private static int port;
80     protected static String httpsPrefix;
81
82     private static Main main;
83
84     private boolean activatorWasAlive;
85
86     /**
87      * Allocates a port for the server, writes a config file, and then starts Main.
88      *
89      * @throws Exception if an error occurs
90      */
91     @BeforeClass
92     public static void setUpBeforeClass() throws Exception {
93         setUpBeforeClass(true);
94     }
95
96     /**
97      * Allocates a port for the server, writes a config file, and then starts Main, if
98      * specified.
99      *
100      * @param shouldStart {@code true} if Main should be started, {@code false} otherwise
101      * @throws Exception if an error occurs
102      */
103     public static void setUpBeforeClass(boolean shouldStart) throws Exception {
104         port = NetworkUtil.allocPort();
105
106         httpsPrefix = "https://localhost:" + port + "/";
107
108         makeConfigFile();
109
110         HttpServletServerFactoryInstance.getServerFactory().destroy();
111         TopicEndpointManager.getManager().shutdown();
112
113         CommonTestData.newDb();
114
115         if (shouldStart) {
116             startMain();
117         }
118     }
119
120     /**
121      * Stops Main.
122      */
123     @AfterClass
124     public static void teardownAfterClass() {
125         try {
126             stopMain();
127
128         } catch (PolicyPapException exp) {
129             LOGGER.error("cannot stop main", exp);
130         }
131     }
132
133     /**
134      * Set up.
135      *
136      * @throws Exception if an error occurs
137      */
138     @Before
139     public void setUp() throws Exception {
140         // restart, if not currently running
141         if (main == null) {
142             startMain();
143         }
144
145         activatorWasAlive = Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class).isAlive();
146     }
147
148     /**
149      * Restores the activator's "alive" state.
150      */
151     @After
152     public void tearDown() {
153         markActivator(activatorWasAlive);
154     }
155
156     /**
157      * Verifies that an endpoint appears within the swagger response.
158      *
159      * @param endpoint the endpoint of interest
160      * @throws Exception if an error occurs
161      */
162     protected void testSwagger(final String endpoint) throws Exception {
163         final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml", true);
164         final String resp = invocationBuilder.get(String.class);
165
166         assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":"));
167     }
168
169     /**
170      * Makes a parameter configuration file.
171      *
172      * @throws Exception if an error occurs
173      */
174     private static void makeConfigFile() throws Exception {
175         String json = new CommonTestData().getPapParameterGroupAsString(port);
176
177         File file = new File(CONFIG_FILE);
178         file.deleteOnExit();
179
180         try (FileOutputStream output = new FileOutputStream(file)) {
181             output.write(json.getBytes(StandardCharsets.UTF_8));
182         }
183     }
184
185     /**
186      * Starts the "Main".
187      *
188      * @throws Exception if an error occurs
189      */
190     protected static void startMain() throws Exception {
191         Registry.newRegistry();
192
193         // make sure port is available
194         if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) {
195             throw new IllegalStateException("port " + port + " is still in use");
196         }
197
198         final Properties systemProps = System.getProperties();
199         systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
200         systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
201         System.setProperties(systemProps);
202
203         final String[] papConfigParameters = { "-c", CONFIG_FILE };
204
205         main = new Main(papConfigParameters);
206
207         if (!NetworkUtil.isTcpPortOpen("localhost", port, 6, 10000L)) {
208             throw new IllegalStateException("server is not listening on port " + port);
209         }
210     }
211
212     /**
213      * Stops the "Main".
214      *
215      * @throws Exception if an error occurs
216      */
217     private static void stopMain() throws PolicyPapException {
218         if (main != null) {
219             Main main2 = main;
220             main = null;
221
222             main2.shutdown();
223         }
224     }
225
226     /**
227      * Mark the activator as dead, but leave its REST server running.
228      */
229     protected void markActivatorDead() {
230         markActivator(false);
231     }
232
233     private void markActivator(boolean wasAlive) {
234         Object manager = Whitebox.getInternalState(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class),
235                         "serviceManager");
236         Whitebox.setInternalState(manager, "running", wasAlive);
237     }
238
239     /**
240      * Verifies that unauthorized requests fail.
241      *
242      * @param endpoint the target end point
243      * @param sender function that sends the requests to the target
244      * @throws Exception if an error occurs
245      */
246     protected void checkUnauthRequest(final String endpoint, Function<Invocation.Builder, Response> sender)
247                     throws Exception {
248         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(),
249                         sender.apply(sendNoAuthRequest(endpoint)).getStatus());
250     }
251
252     /**
253      * Sends a request to an endpoint.
254      *
255      * @param endpoint the target endpoint
256      * @return a request builder
257      * @throws Exception if an error occurs
258      */
259     protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
260         return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, true);
261     }
262
263     /**
264      * Sends a request to an endpoint, without any authorization header.
265      *
266      * @param endpoint the target endpoint
267      * @return a request builder
268      * @throws Exception if an error occurs
269      */
270     protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
271         return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, false);
272     }
273
274     /**
275      * Sends a request to a fully qualified endpoint.
276      *
277      * @param fullyQualifiedEndpoint the fully qualified target endpoint
278      * @param includeAuth if authorization header should be included
279      * @return a request builder
280      * @throws Exception if an error occurs
281      */
282     protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
283                     throws Exception {
284         final SSLContext sc = SSLContext.getInstance("TLSv1.2");
285         sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
286         final ClientBuilder clientBuilder =
287                         ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
288         final Client client = clientBuilder.build();
289
290         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
291         client.register(GsonMessageBodyHandler.class);
292
293         if (includeAuth) {
294             final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
295             client.register(feature);
296         }
297
298         final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
299
300         return webTarget.request(MediaType.APPLICATION_JSON);
301     }
302 }