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