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