f0ce201c7cda34dde742d88815f6a62aee65c510
[policy/models.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Modifications Copyright (C) 2019-2020 AT&T Intellectual Property.
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.models.sim.dmaap.rest;
22
23 import java.io.File;
24 import java.io.FileOutputStream;
25 import java.nio.charset.StandardCharsets;
26 import javax.ws.rs.client.Client;
27 import javax.ws.rs.client.ClientBuilder;
28 import javax.ws.rs.client.Invocation;
29 import javax.ws.rs.client.WebTarget;
30 import javax.ws.rs.core.MediaType;
31 import lombok.Getter;
32 import org.glassfish.jersey.client.ClientProperties;
33 import org.junit.AfterClass;
34 import org.junit.Before;
35 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
36 import org.onap.policy.common.gson.GsonMessageBodyHandler;
37 import org.onap.policy.common.utils.network.NetworkUtil;
38 import org.onap.policy.common.utils.services.Registry;
39 import org.onap.policy.models.sim.dmaap.DmaapSimException;
40 import org.onap.policy.models.sim.dmaap.startstop.Main;
41 import org.onap.policy.sim.dmaap.parameters.CommonTestData;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * Common base class for rest server tests.
47  */
48 public class CommonRestServer {
49
50     private static final Logger LOGGER = LoggerFactory.getLogger(CommonRestServer.class);
51
52     public static final String NOT_ALIVE = "not alive";
53     public static final String ALIVE = "alive";
54     public static final String SELF = "self";
55     public static final String NAME = "DMaaP Simulator";
56     public static final String ENDPOINT_PREFIX = "events/";
57
58     protected static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParams.json";
59
60     @Getter
61     private static int port;
62
63     protected static String httpPrefix;
64
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 shouldStartMain {@code true} if Main should be started, {@code false}
71      *        otherwise
72      *
73      * @throws Exception if an error occurs
74      */
75     public static void reconfigure(boolean shouldStartMain) throws Exception {
76         port = NetworkUtil.allocPort();
77
78         httpPrefix = "http://localhost:" + port + "/";
79
80         String json = new CommonTestData().getParameterGroupAsString(port);
81         makeConfigFile(CONFIG_FILE, json);
82
83         HttpServletServerFactoryInstance.getServerFactory().destroy();
84
85         if (shouldStartMain) {
86             startMain();
87         }
88     }
89
90     /**
91      * Stops Main.
92      */
93     @AfterClass
94     public static void teardownAfterClass() {
95         try {
96             if (main != null) {
97                 Main main2 = main;
98                 main = null;
99
100                 main2.shutdown();
101             }
102
103         } catch (DmaapSimException exp) {
104             LOGGER.error("cannot stop main", exp);
105         }
106     }
107
108     /**
109      * Set up.
110      *
111      * @throws Exception if an error occurs
112      */
113     @Before
114     public void setUp() throws Exception {
115         // restart, if not currently running
116         if (main == null) {
117             startMain();
118         }
119     }
120
121     /**
122      * Makes a parameter configuration file.
123      * @param fileName name of the config file to be created
124      * @param json json to be written to the file
125      *
126      * @throws Exception if an error occurs
127      */
128     protected static void makeConfigFile(String fileName, String json) throws Exception {
129         File file = new File(fileName);
130         file.deleteOnExit();
131
132         try (FileOutputStream output = new FileOutputStream(file)) {
133             output.write(json.getBytes(StandardCharsets.UTF_8));
134         }
135     }
136
137     /**
138      * Starts the "Main".
139      *
140      * @throws Exception if an error occurs
141      */
142     private static void startMain() throws Exception {
143         Registry.newRegistry();
144
145         // make sure port is available
146         if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) {
147             throw new IllegalStateException("port " + port + " is still in use");
148         }
149
150         final String[] simConfigParameters = {"-c", "src/test/resources/parameters/TestConfigParams.json"};
151
152         main = new Main(simConfigParameters);
153
154         if (!NetworkUtil.isTcpPortOpen("localhost", port, 60, 1000L)) {
155             throw new IllegalStateException("server is not listening on port " + port);
156         }
157     }
158
159     /**
160      * Sends a request to an endpoint.
161      *
162      * @param endpoint the target endpoint
163      * @return a request builder
164      * @throws Exception if an error occurs
165      */
166     protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
167         return sendFqeRequest(httpPrefix + ENDPOINT_PREFIX + endpoint);
168     }
169
170     /**
171      * Sends a request to a fully qualified endpoint.
172      *
173      * @param fullyQualifiedEndpoint the fully qualified target endpoint
174      * @return a request builder
175      */
176     protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint) {
177         final Client client = ClientBuilder.newBuilder().build();
178
179         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
180         client.register(GsonMessageBodyHandler.class);
181
182         final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
183
184         return webTarget.request(MediaType.APPLICATION_JSON);
185     }
186 }