Move PAP database provider to spring boot default
[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, 2021 AT&T Intellectual Property.
5  *  Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.rest;
24
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertTrue;
27
28 import java.io.File;
29 import java.io.FileOutputStream;
30 import java.nio.charset.StandardCharsets;
31 import java.security.SecureRandom;
32 import java.util.concurrent.atomic.AtomicBoolean;
33 import java.util.function.Function;
34 import javax.net.ssl.SSLContext;
35 import javax.ws.rs.client.Client;
36 import javax.ws.rs.client.ClientBuilder;
37 import javax.ws.rs.client.Invocation;
38 import javax.ws.rs.client.WebTarget;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.Response;
41 import org.glassfish.jersey.client.ClientProperties;
42 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
43 import org.junit.After;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.junit.runner.RunWith;
47 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
49 import org.onap.policy.common.gson.GsonMessageBodyHandler;
50 import org.onap.policy.common.utils.network.NetworkUtil;
51 import org.onap.policy.common.utils.security.SelfSignedKeyStore;
52 import org.onap.policy.common.utils.services.Registry;
53 import org.onap.policy.pap.main.PolicyPapApplication;
54 import org.onap.policy.pap.main.parameters.CommonTestData;
55 import org.onap.policy.pap.main.startstop.PapActivator;
56 import org.powermock.reflect.Whitebox;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.boot.test.context.SpringBootTest;
59 import org.springframework.boot.web.server.LocalServerPort;
60 import org.springframework.test.annotation.DirtiesContext;
61 import org.springframework.test.annotation.DirtiesContext.ClassMode;
62 import org.springframework.test.context.DynamicPropertyRegistry;
63 import org.springframework.test.context.DynamicPropertySource;
64 import org.springframework.test.context.junit4.SpringRunner;
65
66 /**
67  * Class to perform unit test of {@link PapRestControllerV1}.
68  *
69  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
70  */
71 @RunWith(SpringRunner.class)
72 @SpringBootTest(classes = PolicyPapApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
73     properties = {"db.initialize=false"})
74 @DirtiesContext(classMode = ClassMode.AFTER_CLASS)
75 public abstract class CommonPapRestServer {
76
77     protected static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParams.json";
78
79     public static final String NOT_ALIVE = "not alive";
80     public static final String ALIVE = "alive";
81     public static final String SELF = NetworkUtil.getHostname();
82     public static final String NAME = "Policy PAP";
83     public static final String ENDPOINT_PREFIX = "policy/pap/v1/";
84
85     private static SelfSignedKeyStore keystore;
86
87     private boolean activatorWasAlive;
88     protected String httpsPrefix;
89
90     @LocalServerPort
91     private int port;
92
93     @Autowired
94     private PapActivator papActivator;
95
96     /**
97      * Allocates a new db url, writes a config file.
98      *
99      * @throws Exception if an error occurs
100      */
101     @BeforeClass
102     public static void setUpBeforeClass() throws Exception {
103         keystore = new SelfSignedKeyStore();
104         CommonTestData.newDb();
105         makeConfigFile();
106
107         HttpServletServerFactoryInstance.getServerFactory().destroy();
108         TopicEndpointManager.getManager().shutdown();
109         Registry.newRegistry();
110     }
111
112     @DynamicPropertySource
113     static void registerPgProperties(DynamicPropertyRegistry registry) {
114         registry.add("spring.datasource.url", () -> "jdbc:h2:mem:testdb" + CommonTestData.dbNum);
115         registry.add("server.ssl.enabled", () -> "true");
116         registry.add("server.ssl.key-store", () -> keystore.getKeystoreName());
117         registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD);
118     }
119
120     /**
121      * Set up.
122      *
123      * @throws Exception if an error occurs
124      */
125     @Before
126     public void setUp() throws Exception {
127         httpsPrefix = "https://localhost:" + port + "/";
128         activatorWasAlive = papActivator.isAlive();
129     }
130
131     /**
132      * Restores the activator's "alive" state.
133      */
134     @After
135     public void tearDown() {
136         markActivator(activatorWasAlive);
137     }
138
139     /**
140      * Verifies that an endpoint appears within the swagger response.
141      *
142      * @param endpoint the endpoint of interest
143      * @throws Exception if an error occurs
144      */
145     protected void testSwagger(final String endpoint) throws Exception {
146         final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "v2/api-docs", true);
147         final String resp = invocationBuilder.get(String.class);
148         assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint));
149     }
150
151     /**
152      * Makes a parameter configuration file.
153      *
154      * @throws Exception if an error occurs
155      */
156     private static void makeConfigFile() throws Exception {
157         String json = new CommonTestData().getPapParameterGroupAsString(6969);
158
159         File file = new File(CONFIG_FILE);
160         file.deleteOnExit();
161
162         try (FileOutputStream output = new FileOutputStream(file)) {
163             output.write(json.getBytes(StandardCharsets.UTF_8));
164         }
165     }
166
167     /**
168      * Mark the activator as dead, but leave its REST server running.
169      */
170     protected void markActivatorDead() {
171         markActivator(false);
172     }
173
174     private void markActivator(boolean wasAlive) {
175         Object manager = Whitebox.getInternalState(papActivator, "serviceManager");
176         AtomicBoolean running = Whitebox.getInternalState(manager, "running");
177         running.set(wasAlive);
178     }
179
180     /**
181      * Verifies that unauthorized requests fail.
182      *
183      * @param endpoint the target end point
184      * @param sender function that sends the requests to the target
185      * @throws Exception if an error occurs
186      */
187     protected void checkUnauthRequest(final String endpoint, Function<Invocation.Builder, Response> sender)
188                     throws Exception {
189         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(),
190                         sender.apply(sendNoAuthRequest(endpoint)).getStatus());
191     }
192
193     /**
194      * Sends a request to an endpoint.
195      *
196      * @param endpoint the target endpoint
197      * @return a request builder
198      * @throws Exception if an error occurs
199      */
200     protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
201         return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, true);
202     }
203
204     /**
205      * Sends a request to an endpoint, without any authorization header.
206      *
207      * @param endpoint the target endpoint
208      * @return a request builder
209      * @throws Exception if an error occurs
210      */
211     protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
212         return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, false);
213     }
214
215     /**
216      * Sends a request to a fully qualified endpoint.
217      *
218      * @param fullyQualifiedEndpoint the fully qualified target endpoint
219      * @param includeAuth if authorization header should be included
220      * @return a request builder
221      * @throws Exception if an error occurs
222      */
223     protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
224                     throws Exception {
225         final SSLContext sc = SSLContext.getInstance("TLSv1.2");
226         sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
227         final ClientBuilder clientBuilder =
228                         ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
229         final Client client = clientBuilder.build();
230
231         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
232         client.register(GsonMessageBodyHandler.class);
233
234         if (includeAuth) {
235             final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("policyadmin", "zb!XztG34");
236             client.register(feature);
237         }
238
239         final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
240
241         return webTarget.request(MediaType.APPLICATION_JSON);
242     }
243 }