Changes for checkstyle 8.32
[policy/apex-pdp.git] / testsuites / performance / performance-benchmark-test / src / main / java / org / onap / policy / apex / testsuites / performance / benchmark / eventgenerator / EventGenerator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 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.apex.testsuites.performance.benchmark.eventgenerator;
23
24 import java.io.IOException;
25 import java.net.URI;
26 import java.nio.file.InvalidPathException;
27 import java.util.Arrays;
28 import org.apache.commons.cli.ParseException;
29 import org.glassfish.grizzly.http.server.HttpServer;
30 import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
31 import org.glassfish.jersey.server.ResourceConfig;
32 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
33 import org.onap.policy.common.utils.resources.TextFileUtils;
34 import org.slf4j.ext.XLogger;
35 import org.slf4j.ext.XLoggerFactory;
36
37 /**
38  * This class is the main class of a REST server that generates sample events.
39  */
40 public class EventGenerator {
41     // Get a reference to the logger
42     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventGenerator.class);
43
44     // Parameters for event generation
45     private final EventGeneratorParameters parameters;
46
47     // The HTTP server we are running
48     private final HttpServer eventGeneratorServer;
49
50     /**
51      * Instantiates a new event generator with the given parameters.
52      *
53      * @param parameters the parameters for the event generator
54      */
55     public EventGenerator(final EventGeneratorParameters parameters) {
56         this.parameters = parameters;
57
58         // Set the parameters in the event generator endpoint
59         EventGeneratorEndpoint.clearEventGenerationStats();
60         EventGeneratorEndpoint.setParameters(parameters);
61
62         // Add a shutdown hook to shut down the rest services when the process is exiting
63         Runtime.getRuntime().addShutdownHook(new Thread(new EventGeneratorShutdownHook()));
64
65         LOGGER.info("Event generator REST server starting");
66
67         final ResourceConfig rc = new ResourceConfig(EventGeneratorEndpoint.class);
68         eventGeneratorServer = GrizzlyHttpServerFactory.createHttpServer(getBaseUri(), rc);
69
70         // Wait for the HTTP server to come up
71         while (!eventGeneratorServer.isStarted()) {
72             ThreadUtilities.sleep(50);
73         }
74
75         LOGGER.info("Event generator REST server started");
76     }
77
78     /**
79      * Get the current event generation statistics.
80      *
81      * @return the statistics as a JSON string
82      */
83     public String getEventGenerationStats() {
84         return EventGeneratorEndpoint.getEventGenerationStats();
85     }
86
87     /**
88      * Check if event generation is finished.
89      *
90      * @return true if event generation is finished
91      */
92     public boolean isFinished() {
93         return EventGeneratorEndpoint.isFinished();
94     }
95
96     /**
97      * Tear down the event generator.
98      */
99     public void tearDown() {
100         LOGGER.info("Event generator shutting down");
101
102         eventGeneratorServer.shutdown();
103
104         if (parameters.getOutFile() != null) {
105             try {
106                 TextFileUtils.putStringAsTextFile(getEventGenerationStats(), parameters.getOutFile());
107             } catch (IOException | InvalidPathException ioe) {
108                 LOGGER.warn("could not output statistics to file \"" + parameters.getOutFile() + "\"", ioe);
109             }
110         }
111
112         LOGGER.info("Event generator shut down");
113     }
114
115     /**
116      * Get the base URI for the server.
117      *
118      * @return the base URI
119      */
120     private URI getBaseUri() {
121         String baseUri = "http://" + parameters.getHost() + ':' + parameters.getPort() + '/' + "/EventGenerator";
122         return URI.create(baseUri);
123     }
124
125     /**
126      * This class is a shutdown hook for the Apex editor command.
127      */
128     private class EventGeneratorShutdownHook implements Runnable {
129         /**
130          * {@inheritDoc}.
131          */
132         @Override
133         public void run() {
134             tearDown();
135         }
136     }
137
138     /**
139      * The main method.
140      *
141      * @param args the arguments
142      * @throws Exception the exception
143      */
144     public static void main(final String[] args) {
145         LOGGER.info("Starting event generator with arguments: " + Arrays.toString(args));
146
147         EventGeneratorParameterHandler parameterHandler = new EventGeneratorParameterHandler();
148
149         EventGeneratorParameters parameters = null;
150
151         try {
152             parameters = parameterHandler.parse(args);
153         } catch (ParseException pe) {
154             LOGGER.trace("Event generator start exception", pe);
155             LOGGER.info("Start of event generator failed: {}", pe.getMessage());
156             return;
157         }
158
159         // Null parameters means we print help
160         if (parameters == null) {
161             LOGGER.info(parameterHandler.getHelp(EventGenerator.class.getName()));
162             return;
163         }
164
165         // Start the event generator
166         EventGenerator eventGenerator = new EventGenerator(parameters);
167         LOGGER.info("Event generator started");
168
169         // Wait for event generation to finish
170         while (!eventGenerator.isFinished()) {
171             ThreadUtilities.sleep(200);
172         }
173
174         // Shut down the server
175         eventGenerator.tearDown();
176
177         LOGGER.info("Event generator statistics\n" + eventGenerator.getEventGenerationStats());
178
179         LOGGER.info("Event generator finished");
180     }
181 }