00b9c67151c4f93292cab3d8122c54d0d7cc1c1a
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.controlloop.runtime.util.rest;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertTrue;
25
26 import java.io.File;
27 import java.io.FileNotFoundException;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.nio.charset.StandardCharsets;
31 import javax.ws.rs.client.Client;
32 import javax.ws.rs.client.ClientBuilder;
33 import javax.ws.rs.client.Entity;
34 import javax.ws.rs.client.Invocation;
35 import javax.ws.rs.client.WebTarget;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38 import org.glassfish.jersey.client.ClientProperties;
39 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
40 import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException;
41 import org.onap.policy.clamp.controlloop.runtime.main.startstop.Main;
42 import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData;
43 import org.onap.policy.common.gson.GsonMessageBodyHandler;
44 import org.onap.policy.common.utils.network.NetworkUtil;
45 import org.onap.policy.common.utils.services.Registry;
46 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Class to perform Rest unit tests.
52  *
53  */
54 public class CommonRestController {
55
56     private static final String CONFIG_FILE = "src/test/resources/parameters/RuntimeConfigParameters%d.json";
57
58     private static final Logger LOGGER = LoggerFactory.getLogger(CommonRestController.class);
59
60     public static final String SELF = NetworkUtil.getHostname();
61     public static final String ENDPOINT_PREFIX = "onap/controlloop/v2/";
62
63     private static int port;
64     private static String httpPrefix;
65     private static Main main;
66
67     /**
68      * Allocates a port for the server, writes a config file, and then starts Main.
69      *
70      * @param dbName database name
71      * @throws Exception if an error occurs
72      */
73     public static void setUpBeforeClass(final String dbName) throws Exception {
74         port = NetworkUtil.allocPort();
75
76         httpPrefix = "http://" + SELF + ":" + port + "/";
77
78         makeConfigFile(dbName);
79         startMain();
80     }
81
82     /**
83      * Stops Main.
84      */
85     public static void teardownAfterClass() {
86         try {
87             stopMain();
88         } catch (Exception ex) {
89             LOGGER.error("cannot stop main", ex);
90         }
91     }
92
93     protected static PolicyModelsProviderParameters getParameters() {
94         return main.getParameters().getDatabaseProviderParameters();
95     }
96
97     /**
98      * Verifies that an endpoint appears within the swagger response.
99      *
100      * @param endpoint the endpoint of interest
101      * @throws Exception if an error occurs
102      */
103     protected void testSwagger(final String endpoint) throws Exception {
104         final Invocation.Builder invocationBuilder = sendFqeRequest(httpPrefix + "swagger.yaml", true);
105         final String resp = invocationBuilder.get(String.class);
106
107         assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":"));
108     }
109
110     /**
111      * Makes a parameter configuration file.
112      *
113      * @param dbName database name
114      * @throws IOException if an error occurs writing the configuration file
115      * @throws FileNotFoundException if an error occurs writing the configuration file
116      */
117     private static void makeConfigFile(final String dbName) throws FileNotFoundException, IOException {
118         String json = CommonTestData.getParameterGroupAsString(port, dbName);
119
120         File file = new File(String.format(CONFIG_FILE, port));
121         file.deleteOnExit();
122
123         try (FileOutputStream output = new FileOutputStream(file)) {
124             output.write(json.getBytes(StandardCharsets.UTF_8));
125         }
126     }
127
128     /**
129      * Starts the "Main".
130      *
131      * @throws InterruptedException if the NetworkUtil method calls are interrupted
132      * @throws IllegalStateException if a controller cannot be started on the requested port
133      */
134     protected static void startMain() throws InterruptedException {
135         Registry.newRegistry();
136
137         // make sure port is available
138         if (NetworkUtil.isTcpPortOpen(SELF, port, 1, 1L)) {
139             throw new IllegalStateException("port " + port + " is not available");
140         }
141
142         final String[] configParameters = {"-c", String.format(CONFIG_FILE, port)};
143
144         main = new Main(configParameters);
145
146         if (!NetworkUtil.isTcpPortOpen(SELF, port, 40, 250L)) {
147             throw new IllegalStateException("server is not listening on port " + port);
148         }
149     }
150
151     /**
152      * Stops the "Main".
153      *
154      * @throws ControlLoopException if an error occurs shutting down the controller
155      * @throws InterruptedException if the NetworkUtil method calls are interrupted
156      * @throws IllegalStateException if a controller cannot be started on the requested port
157      */
158     private static void stopMain() throws ControlLoopException, InterruptedException {
159         if (main != null) {
160             Main main2 = main;
161             main = null;
162
163             main2.shutdown();
164         }
165         // make sure port is close
166         if (NetworkUtil.isTcpPortOpen(SELF, port, 1, 1L)) {
167             throw new IllegalStateException("port " + port + " is still in use");
168         }
169     }
170
171     /**
172      * Sends a request to an endpoint.
173      *
174      * @param endpoint the target endpoint
175      * @return a request builder
176      * @throws Exception if an error occurs
177      */
178     protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
179         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, true);
180     }
181
182     /**
183      * Sends a request to an endpoint, without any authorization header.
184      *
185      * @param endpoint the target endpoint
186      * @return a request builder
187      * @throws Exception if an error occurs
188      */
189     protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
190         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, false);
191     }
192
193     /**
194      * Sends a request to a fully qualified endpoint.
195      *
196      * @param fullyQualifiedEndpoint the fully qualified target endpoint
197      * @param includeAuth if authorization header should be included
198      * @return a request builder
199      * @throws Exception if an error occurs
200      */
201     protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
202             throws Exception {
203         final Client client = ClientBuilder.newBuilder().build();
204
205         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
206         client.register(GsonMessageBodyHandler.class);
207
208         if (includeAuth) {
209             client.register(HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"));
210         }
211
212         final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
213
214         return webTarget.request(MediaType.APPLICATION_JSON);
215     }
216
217     /**
218      * Assert that POST call is Unauthorized.
219      *
220      * @param endPoint the endpoint
221      * @param entity the entity ofthe body
222      * @throws Exception if an error occurs
223      */
224     protected void assertUnauthorizedPost(final String endPoint, final Entity<?> entity) throws Exception {
225         Response rawresp = sendNoAuthRequest(endPoint).post(entity);
226         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
227     }
228
229     /**
230      * Assert that PUT call is Unauthorized.
231      *
232      * @param endPoint the endpoint
233      * @param entity the entity ofthe body
234      * @throws Exception if an error occurs
235      */
236     protected void assertUnauthorizedPut(final String endPoint, final Entity<?> entity) throws Exception {
237         Response rawresp = sendNoAuthRequest(endPoint).put(entity);
238         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
239     }
240
241     /**
242      * Assert that GET call is Unauthorized.
243      *
244      * @param endPoint the endpoint
245      * @throws Exception if an error occurs
246      */
247     protected void assertUnauthorizedGet(final String endPoint) throws Exception {
248         Response rawresp = sendNoAuthRequest(endPoint).buildGet().invoke();
249         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
250     }
251
252     /**
253      * Assert that DELETE call is Unauthorized.
254      *
255      * @param endPoint the endpoint
256      * @throws Exception if an error occurs
257      */
258     protected void assertUnauthorizedDelete(final String endPoint) throws Exception {
259         Response rawresp = sendNoAuthRequest(endPoint).delete();
260         assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), rawresp.getStatus());
261     }
262 }