ae004de49e0913d675f257c6f1bf354435b51f8e
[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.assertj.core.api.Assertions.assertThat;
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         assertThat(invocationBuilder.get(String.class)).contains(ENDPOINT_PREFIX + endpoint + ":");
131     }
132
133     /**
134      * Makes a parameter configuration file.
135      *
136      * @throws IOException if an error occurs writing the configuration file
137      * @throws FileNotFoundException if an error occurs writing the configuration file
138      *
139      * @throws Exception if an error occurs
140      */
141     private static void makeConfigFile() throws FileNotFoundException, IOException {
142         String json = CommonTestData.getParticipantParameterGroupAsString(port);
143         File file = new File(String.format(CONFIG_FILE, port));
144         file.deleteOnExit();
145         try (FileOutputStream output = new FileOutputStream(file)) {
146             output.write(json.getBytes(StandardCharsets.UTF_8));
147         }
148     }
149
150     /**
151      * Starts the "Main".
152      *
153      * @throws InterruptedException
154      *
155      * @throws Exception if an error occurs
156      */
157     protected static void startMain() throws InterruptedException {
158         // make sure port is available
159         if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) {
160             throw new IllegalStateException("port " + port + " is still in use");
161         }
162
163         final String[] configParameters = { "-c", CONFIG_FILE };
164
165         main = new Main(configParameters);
166
167         if (!NetworkUtil.isTcpPortOpen("localhost", port, 40, 250L)) {
168             throw new IllegalStateException("server is not listening on port " + port);
169         }
170     }
171
172     /**
173      * Stops the "Main".
174      *
175      * @throws ControlLoopException
176      *
177      * @throws Exception if an error occurs
178      */
179     private static void stopMain() throws ControlLoopException {
180         if (main != null) {
181             main.shutdown();
182             main = null;
183         }
184     }
185
186     /**
187      * Sends a request to an endpoint.
188      *
189      * @param endpoint the target endpoint
190      * @return a request builder
191      * @throws Exception if an error occurs
192      */
193     protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
194         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, true);
195     }
196
197     /**
198      * Sends a request to an endpoint, without any authorization header.
199      *
200      * @param endpoint the target endpoint
201      * @return a request builder
202      * @throws Exception if an error occurs
203      */
204     protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
205         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint, false);
206     }
207
208     /**
209      * Sends a request to a fully qualified endpoint.
210      *
211      * @param fullyQualifiedEndpoint the fully qualified target endpoint
212      * @param includeAuth if authorization header should be included
213      * @return a request builder
214      * @throws Exception if an error occurs
215      */
216     protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
217             throws Exception {
218         final Client client = ClientBuilder.newBuilder().build();
219         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
220         client.register(GsonMessageBodyHandler.class);
221         if (includeAuth) {
222             client.register(HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"));
223         }
224         final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
225         return webTarget.request(MediaType.APPLICATION_JSON);
226     }
227 }