Add PDP Group Deploy and Delete REST API stubs
[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.security.SecureRandom;
29 import java.util.HashMap;
30 import java.util.Map;
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.authentication.HttpAuthenticationFeature;
41 import org.junit.After;
42 import org.junit.AfterClass;
43 import org.junit.Before;
44 import org.junit.BeforeClass;
45 import org.onap.policy.common.utils.coder.Coder;
46 import org.onap.policy.common.utils.coder.StandardCoder;
47 import org.onap.policy.common.utils.network.NetworkUtil;
48 import org.onap.policy.pap.main.PolicyPapException;
49 import org.onap.policy.pap.main.startstop.Main;
50 import org.onap.policy.pap.main.startstop.PapActivator;
51 import org.powermock.reflect.Whitebox;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * Class to perform unit test of {@link PapRestServer}.
57  *
58  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
59  */
60 public class CommonPapRestServer {
61
62     private static final Logger LOGGER = LoggerFactory.getLogger(CommonPapRestServer.class);
63
64     private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
65
66     private static Coder coder = new StandardCoder();
67
68     public static final String NOT_ALIVE = "not alive";
69     public static final String ALIVE = "alive";
70     public static final String SELF = "self";
71     public static final String NAME = "Policy PAP";
72     public static final String ENDPOINT_PREFIX = "policy/pap/v1/";
73
74     private static int port;
75     protected static String httpsPrefix;
76
77     private static Main main;
78
79     private boolean activatorWasAlive;
80
81     /**
82      * Allocates a port for the server, writes a config file, and then starts Main.
83      *
84      * @throws Exception if an error occurs
85      */
86     @BeforeClass
87     public static void setUpBeforeClass() throws Exception {
88         port = NetworkUtil.allocPort();
89
90         httpsPrefix = "https://localhost:" + port + "/";
91
92         makeConfigFile();
93
94         startMain();
95     }
96
97     /**
98      * Stops Main.
99      */
100     @AfterClass
101     public static void teardownAfterClass() {
102         try {
103             stopMain();
104
105         } catch (PolicyPapException exp) {
106             LOGGER.error("cannot stop main", exp);
107         }
108     }
109
110     /**
111      * Set up.
112      *
113      * @throws Exception if an error occurs
114      */
115     @Before
116     public void setUp() throws Exception {
117         // restart, if not currently running
118         if (main == null) {
119             startMain();
120         }
121
122         activatorWasAlive = PapActivator.getCurrent().isAlive();
123     }
124
125     /**
126      * Restores the activator's "alive" state.
127      */
128     @After
129     public void tearDown() {
130         Whitebox.setInternalState(PapActivator.getCurrent(), "alive", activatorWasAlive);
131     }
132
133     /**
134      * Verifies that an endpoint appears within the swagger response.
135      *
136      * @param endpoint the endpoint of interest
137      * @throws Exception if an error occurs
138      */
139     protected void testSwagger(final String endpoint) throws Exception {
140         final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml", true);
141         final String resp = invocationBuilder.get(String.class);
142
143         assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":"));
144     }
145
146     /**
147      * Makes a parameter configuration file.
148      *
149      * @throws Exception if an error occurs
150      */
151     private static void makeConfigFile() throws Exception {
152         Map<String, Object> restParams = new HashMap<>();
153         restParams.put("host", "0.0.0.0");
154         restParams.put("port", port);
155         restParams.put("userName", "healthcheck");
156         restParams.put("password", "zb!XztG34");
157         restParams.put("https", true);
158
159         Map<String, Object> pdpGroupDeploy = new HashMap<>();
160         pdpGroupDeploy.put("waitResponseMs", "0");
161
162         Map<String, Object> config = new HashMap<>();
163         config.put("name", "PapGroup");
164         config.put("restServerParameters", restParams);
165         config.put("pdpGroupDeploymentParameters", pdpGroupDeploy);
166
167         File file = new File("src/test/resources/parameters/TestConfigParams.json");
168         file.deleteOnExit();
169
170         coder.encode(file, config);
171     }
172
173     /**
174      * Starts the "Main".
175      *
176      * @throws Exception if an error occurs
177      */
178     private static void startMain() throws Exception {
179         // make sure port is available
180         if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) {
181             throw new IllegalStateException("port " + port + " is still in use");
182         }
183
184         final Properties systemProps = System.getProperties();
185         systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
186         systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
187         System.setProperties(systemProps);
188
189         // @formatter:off
190         final String[] papConfigParameters = {
191             "-c", "src/test/resources/parameters/TestConfigParams.json",
192             "-p", "src/test/resources/parameters/topic.properties"
193         };
194         // @formatter:on
195
196         main = new Main(papConfigParameters);
197
198         if (!NetworkUtil.isTcpPortOpen("localhost", port, 6, 10000L)) {
199             throw new IllegalStateException("server is not listening on port " + port);
200         }
201     }
202
203     /**
204      * Stops the "Main".
205      *
206      * @throws Exception if an error occurs
207      */
208     private static void stopMain() throws PolicyPapException {
209         if (main != null) {
210             Main main2 = main;
211             main = null;
212
213             main2.shutdown();
214         }
215     }
216
217     /**
218      * Mark the activator as dead, but leave its REST server running.
219      */
220     protected void markActivatorDead() {
221         Whitebox.setInternalState(PapActivator.getCurrent(), "alive", false);
222     }
223
224     /**
225      * Verifies that unauthorized requests fail.
226      *
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
230      */
231     protected void checkUnauthRequest(final String endpoint, Function<Invocation.Builder, Response> sender)
232                     throws Exception {
233         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(),
234                         sender.apply(sendNoAuthRequest(endpoint)).getStatus());
235     }
236
237     /**
238      * Sends a request to an endpoint.
239      *
240      * @param endpoint the target endpoint
241      * @return a request builder
242      * @throws Exception if an error occurs
243      */
244     protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
245         return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, true);
246     }
247
248     /**
249      * Sends a request to an endpoint, without any authorization header.
250      *
251      * @param endpoint the target endpoint
252      * @return a request builder
253      * @throws Exception if an error occurs
254      */
255     protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
256         return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, false);
257     }
258
259     /**
260      * Sends a request to a fully qualified endpoint.
261      *
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
266      */
267     protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
268                     throws Exception {
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();
274
275         if (includeAuth) {
276             final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
277             client.register(feature);
278         }
279
280         final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
281
282         return webTarget.request(MediaType.APPLICATION_JSON);
283     }
284 }