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