7aae326293e599b84ef7167cb01458dd74bad4de
[policy/clamp.git] /
1
2 /*-
3  * ============LICENSE_START=======================================================
4  *  Copyright (C) 2021 Nordix Foundation.
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.clamp.controlloop.participant.simulator.main.rest;
23
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.Invocation;
34 import javax.ws.rs.client.WebTarget;
35 import javax.ws.rs.core.MediaType;
36 import org.glassfish.jersey.client.ClientProperties;
37 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
38 import org.junit.AfterClass;
39 import org.junit.Before;
40 import org.junit.BeforeClass;
41 import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException;
42 import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.CommonTestData;
43 import org.onap.policy.clamp.controlloop.participant.simulator.main.startstop.Main;
44 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
45 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
46 import org.onap.policy.common.gson.GsonMessageBodyHandler;
47 import org.onap.policy.common.utils.network.NetworkUtil;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Class to perform Rest unit tests.
53  *
54  */
55
56 public class CommonParticipantRestServer {
57
58     private static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParameters.json";
59     private static final Logger LOGGER = LoggerFactory.getLogger(CommonParticipantRestServer.class);
60     public static final String SELF = NetworkUtil.getHostname();
61     public static final String ENDPOINT_PREFIX = "onap/participantsim/v2/";
62     private static int port;
63     private static String httpPrefix;
64     private static Main main;
65
66     /**
67      * Allocates a port for the server, writes a config file, and then starts Main.
68      *
69      * @throws Exception if an error occurs
70      */
71     @BeforeClass
72     public static void setUpBeforeClass() throws Exception {
73         setUpBeforeClass(true);
74     }
75
76     /**
77      * Allocates a port for the server, writes a config file, and then starts Main, if
78      * specified.
79      *
80      * @param shouldStart {@code true} if Main should be started, {@code false} otherwise
81      * @throws Exception if an error occurs
82      */
83     public static void setUpBeforeClass(boolean shouldStart) throws Exception {
84         port = NetworkUtil.allocPort();
85         httpPrefix = "http://localhost:" + port + "/";
86
87         makeConfigFile();
88         HttpServletServerFactoryInstance.getServerFactory().destroy();
89         TopicEndpointManager.getManager().shutdown();
90
91         if (shouldStart) {
92             startMain();
93         }
94     }
95
96     /**
97      * Stops Main.
98      */
99     @AfterClass
100     public static void teardownAfterClass() {
101         try {
102             stopMain();
103
104         } catch (ControlLoopException exp) {
105             LOGGER.error("cannot stop main", exp);
106         }
107     }
108
109     /**
110      * Set up.
111      *
112      * @throws Exception if an error occurs
113      */
114     @Before
115     public void setUp() throws Exception {
116         // restart, if not currently running
117         if (main == null) {
118             startMain();
119         }
120     }
121
122     /**
123      * Verifies that an endpoint appears within the swagger response.
124      *
125      * @param endpoint the endpoint of interest
126      * @throws Exception if an error occurs
127      */
128     protected void testSwagger(final String endpoint) throws Exception {
129         final Invocation.Builder invocationBuilder = sendFqeRequest(httpPrefix + "swagger.yaml", true);
130         final String resp = invocationBuilder.get(String.class);
131         assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":"));
132     }
133
134     /**
135      * Makes a parameter configuration file.
136      *
137      * @throws IOException if an error occurs writing the configuration file
138      * @throws FileNotFoundException if an error occurs writing the configuration file
139      *
140      * @throws Exception if an error occurs
141      */
142     private static void makeConfigFile() throws FileNotFoundException, IOException {
143         String json = CommonTestData.getParticipantParameterGroupAsString(port);
144         File file = new File(String.format(CONFIG_FILE, port));
145         file.deleteOnExit();
146         try (FileOutputStream output = new FileOutputStream(file)) {
147             output.write(json.getBytes(StandardCharsets.UTF_8));
148         }
149     }
150
151     /**
152      * Starts the "Main".
153      *
154      * @throws InterruptedException
155      *
156      * @throws Exception if an error occurs
157      */
158     protected static void startMain() throws InterruptedException {
159         // make sure port is available
160         if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) {
161             throw new IllegalStateException("port " + port + " is still in use");
162         }
163
164         final String[] configParameters = { "-c", CONFIG_FILE };
165
166         main = new Main(configParameters);
167
168         if (!NetworkUtil.isTcpPortOpen("localhost", port, 40, 250L)) {
169             throw new IllegalStateException("server is not listening on port " + port);
170         }
171     }
172
173     /**
174      * Stops the "Main".
175      *
176      * @throws ControlLoopException
177      *
178      * @throws Exception if an error occurs
179      */
180     private static void stopMain() throws ControlLoopException {
181         if (main != null) {
182             main.shutdown();
183             main = null;
184         }
185     }
186
187     /**
188      * Sends a request to an endpoint.
189      *
190      * @param endpoint the target endpoint
191      * @return a request builder
192      * @throws Exception if an error occurs
193      */
194     protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
195         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, true);
196     }
197
198     /**
199      * Sends a request to an endpoint, without any authorization header.
200      *
201      * @param endpoint the target endpoint
202      * @return a request builder
203      * @throws Exception if an error occurs
204      */
205     protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
206         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, false);
207     }
208
209     /**
210      * Sends a request to a fully qualified endpoint.
211      *
212      * @param fullyQualifiedEndpoint the fully qualified target endpoint
213      * @param includeAuth if authorization header should be included
214      * @return a request builder
215      * @throws Exception if an error occurs
216      */
217     protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
218             throws Exception {
219         final Client client = ClientBuilder.newBuilder().build();
220         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
221         client.register(GsonMessageBodyHandler.class);
222         if (includeAuth) {
223             client.register(HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"));
224         }
225         final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
226         return webTarget.request(MediaType.APPLICATION_JSON);
227     }
228 }