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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.testsuites.performance.benchmark.eventgenerator;
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;
40 * This class reads and handles command line parameters to the event generator.
42 public class EventGeneratorParameterHandler {
43 // Get a reference to the logger
44 private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventGeneratorParameterHandler.class);
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";
55 private static final int MAX_HELP_LINE_LENGTH = 120;
57 // Apache Commons CLI options
58 private final Options options;
61 * Construct the options for the CLI editor.
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());
95 * Parse the command line options.
97 * @param args The arguments
98 * @return the CLI parameters
99 * @throws ParseException on parse errors
101 public EventGeneratorParameters parse(final String[] args) throws ParseException {
102 CommandLine commandLine = new DefaultParser().parse(options, args);
103 final String[] remainingArgs = commandLine.getArgs();
105 if (remainingArgs.length > 0) {
106 throw new ParseException("too many command line arguments specified : " + Arrays.toString(remainingArgs));
109 if (commandLine.hasOption('h')) {
113 EventGeneratorParameters parameters = new EventGeneratorParameters();
115 if (commandLine.hasOption('c')) {
116 parameters = getParametersFromJsonFile(commandLine.getOptionValue(CONFIGURATION_FILE));
119 parseFlags(commandLine, parameters);
121 if (commandLine.hasOption('o')) {
122 parameters.setOutFile(commandLine.getOptionValue(OUTPUT_FILE));
125 if (!parameters.isValid()) {
126 throw new ParseException("specified parameters are not valid: " + parameters.validate().getResult());
133 * Parse the command flags.
135 * @param commandLine the command line to parse
136 * @param parameters the parameters we are parsing into
137 * @throws ParseException on parse errors
139 private void parseFlags(CommandLine commandLine, EventGeneratorParameters parameters) throws ParseException {
140 if (commandLine.hasOption('H')) {
141 parameters.setHost(commandLine.getOptionValue(HOST));
144 if (commandLine.hasOption('p')) {
145 parameters.setPort(((Number) commandLine.getParsedOptionValue(PORT)).intValue());
148 if (commandLine.hasOption("bc")) {
149 parameters.setBatchCount(((Number) commandLine.getParsedOptionValue(BATCH_COUNT)).intValue());
152 if (commandLine.hasOption("bs")) {
153 parameters.setBatchSize(((Number) commandLine.getParsedOptionValue(BATCH_SIZE)).intValue());
156 if (commandLine.hasOption("bd")) {
157 parameters.setDelayBetweenBatches(((Number) commandLine.getParsedOptionValue(BATCH_DELAY)).longValue());
162 * Get the parameters from a JSON file.
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
168 private EventGeneratorParameters getParametersFromJsonFile(String configurationFile) throws ParseException {
169 String parameterJsonString = null;
172 parameterJsonString = TextFileUtils.getTextFileAsString(configurationFile);
173 } catch (IOException ioe) {
174 String errorMessage = "Could not read parameters from configuration file \"" + configurationFile + "\": "
176 LOGGER.warn(errorMessage, ioe);
177 throw new ParseException(errorMessage);
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);
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);
197 * Get help information.
199 * @param mainClassName the main class name for the help output
200 * @return help string
202 public String getHelp(final String mainClassName) {
203 final StringWriter stringWriter = new StringWriter();
204 final PrintWriter stringPrintWriter = new PrintWriter(stringWriter);
206 final HelpFormatter helpFormatter = new HelpFormatter();
207 helpFormatter.printHelp(stringPrintWriter, MAX_HELP_LINE_LENGTH, mainClassName + " [options...] ", "", options,
210 return stringWriter.toString();