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 / EventGeneratorParameterHandler.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 com.google.gson.Gson;
25 import java.io.IOException;
26 import java.io.PrintWriter;
27 import java.io.StringWriter;
28 import java.util.Arrays;
29 import org.apache.commons.cli.CommandLine;
30 import org.apache.commons.cli.DefaultParser;
31 import org.apache.commons.cli.HelpFormatter;
32 import org.apache.commons.cli.Option;
33 import org.apache.commons.cli.Options;
34 import org.apache.commons.cli.ParseException;
35 import org.onap.policy.common.utils.resources.TextFileUtils;
36 import org.slf4j.ext.XLogger;
37 import org.slf4j.ext.XLoggerFactory;
38
39 /**
40  * This class reads and handles command line parameters to the event generator.
41  */
42 public class EventGeneratorParameterHandler {
43     // Get a reference to the logger
44     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventGeneratorParameterHandler.class);
45
46     private static final String CONFIGURATION_FILE = "configuration-file";
47     private static final String PORT = "port";
48     private static final String HOST = "host";
49     private static final String HELP = "help";
50     private static final String BATCH_SIZE = "batch-size";
51     private static final String BATCH_COUNT = "batch-count";
52     private static final String BATCH_DELAY = "delay-between-batches";
53     private static final String OUTPUT_FILE = "output-file";
54
55     private static final int MAX_HELP_LINE_LENGTH = 120;
56
57     // Apache Commons CLI options
58     private final Options options;
59
60     /**
61      * Construct the options for the CLI editor.
62      */
63     public EventGeneratorParameterHandler() {
64         options = new Options();
65         options.addOption(Option.builder("h").longOpt(HELP).desc("outputs the usage of this command").required(false)
66                 .type(Boolean.class).build());
67         options.addOption(Option.builder("H").longOpt(HOST)
68                 .desc("the host name on which to start the event generation server, defaults to \"localhost\"").hasArg()
69                 .argName(HOST).required(false).type(String.class).build());
70         options.addOption(Option.builder("p").longOpt(PORT)
71                 .desc("the port on which to start the event generation server, defaults to 42339").hasArg()
72                 .argName(PORT).required(false).type(Number.class).build());
73         options.addOption(Option.builder("c").longOpt(CONFIGURATION_FILE)
74                 .desc("name of a file containing the parameters for the event generations server, "
75                         + "this option must appear on its own")
76                 .hasArg().argName(CONFIGURATION_FILE).required(false).type(String.class).build());
77         options.addOption(Option.builder("o").longOpt(OUTPUT_FILE)
78                 .desc("path and name of a file to which output will be written,"
79                         + " if not specified no output is written")
80                 .hasArg().argName(OUTPUT_FILE).required(false).type(String.class).build());
81         options.addOption(Option.builder("bc").longOpt(BATCH_COUNT)
82                 .desc("the number of batches of events to send, must be 0 or more, "
83                         + "0 means send event batches forever, defaults to 1")
84                 .hasArg().argName(BATCH_COUNT).required(false).type(Number.class).build());
85         options.addOption(Option.builder("bs").longOpt(BATCH_SIZE)
86                 .desc("the number of events to send in an event batch, must be 1 or more, defaults to 1").hasArg()
87                 .argName(BATCH_SIZE).required(false).type(Number.class).build());
88         options.addOption(Option.builder("bd").longOpt(BATCH_DELAY)
89                 .desc("the delay in milliseconds between event batches, must be zero or more, "
90                         + "defaults to 10,000 (10 seconds)")
91                 .hasArg().argName(BATCH_DELAY).required(false).type(Number.class).build());
92     }
93
94     /**
95      * Parse the command line options.
96      *
97      * @param args The arguments
98      * @return the CLI parameters
99      * @throws ParseException on parse errors
100      */
101     public EventGeneratorParameters parse(final String[] args) throws ParseException {
102         CommandLine commandLine = new DefaultParser().parse(options, args);
103         final String[] remainingArgs = commandLine.getArgs();
104
105         if (remainingArgs.length > 0) {
106             throw new ParseException("too many command line arguments specified : " + Arrays.toString(remainingArgs));
107         }
108
109         if (commandLine.hasOption('h')) {
110             return null;
111         }
112
113         EventGeneratorParameters parameters = new EventGeneratorParameters();
114
115         if (commandLine.hasOption('c')) {
116             parameters = getParametersFromJsonFile(commandLine.getOptionValue(CONFIGURATION_FILE));
117         }
118
119         parseFlags(commandLine, parameters);
120
121         if (commandLine.hasOption('o')) {
122             parameters.setOutFile(commandLine.getOptionValue(OUTPUT_FILE));
123         }
124
125         if (!parameters.isValid()) {
126             throw new ParseException("specified parameters are not valid: " + parameters.validate().getResult());
127         }
128
129         return parameters;
130     }
131
132     /**
133      * Parse the command flags.
134      *
135      * @param commandLine the command line to parse
136      * @param parameters the parameters we are parsing into
137      * @throws ParseException on parse errors
138      */
139     private void parseFlags(CommandLine commandLine, EventGeneratorParameters parameters) throws ParseException {
140         if (commandLine.hasOption('H')) {
141             parameters.setHost(commandLine.getOptionValue(HOST));
142         }
143
144         if (commandLine.hasOption('p')) {
145             parameters.setPort(((Number) commandLine.getParsedOptionValue(PORT)).intValue());
146         }
147
148         if (commandLine.hasOption("bc")) {
149             parameters.setBatchCount(((Number) commandLine.getParsedOptionValue(BATCH_COUNT)).intValue());
150         }
151
152         if (commandLine.hasOption("bs")) {
153             parameters.setBatchSize(((Number) commandLine.getParsedOptionValue(BATCH_SIZE)).intValue());
154         }
155
156         if (commandLine.hasOption("bd")) {
157             parameters.setDelayBetweenBatches(((Number) commandLine.getParsedOptionValue(BATCH_DELAY)).longValue());
158         }
159     }
160
161     /**
162      * Get the parameters from a JSON file.
163      *
164      * @param configurationFile the location of the configuration file
165      * @return the parameters read from the JSON file
166      * @throws ParseException on errors reading the parameters
167      */
168     private EventGeneratorParameters getParametersFromJsonFile(String configurationFile) throws ParseException {
169         String parameterJsonString = null;
170
171         try {
172             parameterJsonString = TextFileUtils.getTextFileAsString(configurationFile);
173         } catch (IOException ioe) {
174             String errorMessage = "Could not read parameters from configuration file \"" + configurationFile + "\": "
175                     + ioe.getMessage();
176             LOGGER.warn(errorMessage, ioe);
177             throw new ParseException(errorMessage);
178         }
179
180         if (parameterJsonString == null || parameterJsonString.trim().length() == 0) {
181             String errorMessage = "No parameters found in configuration file \"" + configurationFile + "\"";
182             LOGGER.warn(errorMessage);
183             throw new ParseException(errorMessage);
184         }
185
186         try {
187             return new Gson().fromJson(parameterJsonString, EventGeneratorParameters.class);
188         } catch (Exception ge) {
189             String errorMessage = "Error parsing JSON parameters from configuration file \"" + configurationFile
190                     + "\": " + ge.getMessage();
191             LOGGER.warn(errorMessage, ge);
192             throw new ParseException(errorMessage);
193         }
194     }
195
196     /**
197      * Get help information.
198      *
199      * @param mainClassName the main class name for the help output
200      * @return help string
201      */
202     public String getHelp(final String mainClassName) {
203         final StringWriter stringWriter = new StringWriter();
204         final PrintWriter stringPrintWriter = new PrintWriter(stringWriter);
205
206         final HelpFormatter helpFormatter = new HelpFormatter();
207         helpFormatter.printHelp(stringPrintWriter, MAX_HELP_LINE_LENGTH, mainClassName + " [options...] ", "", options,
208                 0, 0, "");
209
210         return stringWriter.toString();
211     }
212
213 }