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