aboutsummaryrefslogtreecommitdiffstats
path: root/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/EventGeneratorParameterHandler.java
blob: 912290097c93bbcb8b79636da02b8d58e323ec90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.testsuites.performance.benchmark.eventgenerator;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.onap.policy.common.utils.resources.TextFileUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

/**
 * This class reads and handles command line parameters to the event generator.
 */
public class EventGeneratorParameterHandler {
    // Get a reference to the logger
    private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventGeneratorParameterHandler.class);

    private static final String CONFIGURATION_FILE = "configuration-file";
    private static final String PORT = "port";
    private static final String HOST = "host";
    private static final String HELP = "help";
    private static final String BATCH_SIZE = "batch-size";
    private static final String BATCH_COUNT = "batch-count";
    private static final String BATCH_DELAY = "delay-between-batches";
    private static final String OUTPUT_FILE = "output-file";

    private static final int MAX_HELP_LINE_LENGTH = 120;

    // Apache Commons CLI options
    private final Options options;

    /**
     * Construct the options for the CLI editor.
     */
    public EventGeneratorParameterHandler() {
        options = new Options();
        options.addOption(Option.builder("h").longOpt(HELP).desc("outputs the usage of this command").required(false)
                .type(Boolean.class).build());
        options.addOption(Option.builder("H").longOpt(HOST)
                .desc("the host name on which to start the event generation server, defaults to \"localhost\"").hasArg()
                .argName(HOST).required(false).type(String.class).build());
        options.addOption(Option.builder("p").longOpt(PORT)
                .desc("the port on which to start the event generation server, defaults to 42339").hasArg()
                .argName(PORT).required(false).type(Number.class).build());
        options.addOption(Option.builder("c").longOpt(CONFIGURATION_FILE)
                .desc("name of a file containing the parameters for the event generations server, "
                        + "this option must appear on its own")
                .hasArg().argName(CONFIGURATION_FILE).required(false).type(String.class).build());
        options.addOption(Option.builder("o").longOpt(OUTPUT_FILE)
                .desc("path and name of a file to which output will be written,"
                        + " if not specified no output is written")
                .hasArg().argName(OUTPUT_FILE).required(false).type(String.class).build());
        options.addOption(Option.builder("bc").longOpt(BATCH_COUNT)
                .desc("the number of batches of events to send, must be 0 or more, "
                        + "0 means send event batches forever, defaults to 1")
                .hasArg().argName(BATCH_COUNT).required(false).type(Number.class).build());
        options.addOption(Option.builder("bs").longOpt(BATCH_SIZE)
                .desc("the number of events to send in an event batch, must be 1 or more, defaults to 1").hasArg()
                .argName(BATCH_SIZE).required(false).type(Number.class).build());
        options.addOption(Option.builder("bd").longOpt(BATCH_DELAY)
                .desc("the delay in milliseconds between event batches, must be zero or more, "
                        + "defaults to 10,000 (10 seconds)")
                .hasArg().argName(BATCH_DELAY).required(false).type(Number.class).build());
    }

    /**
     * Parse the command line options.
     *
     * @param args The arguments
     * @return the CLI parameters
     * @throws ParseException on parse errors
     */
    public EventGeneratorParameters parse(final String[] args) throws ParseException {
        CommandLine commandLine = new DefaultParser().parse(options, args);
        final String[] remainingArgs = commandLine.getArgs();

        if (remainingArgs.length > 0) {
            throw new ParseException("too many command line arguments specified : " + Arrays.toString(remainingArgs));
        }

        if (commandLine.hasOption('h')) {
            return null;
        }

        EventGeneratorParameters parameters = new EventGeneratorParameters();

        if (commandLine.hasOption('c')) {
            parameters = getParametersFromJsonFile(commandLine.getOptionValue(CONFIGURATION_FILE));
        }

        parseFlags(commandLine, parameters);

        if (commandLine.hasOption('o')) {
            parameters.setOutFile(commandLine.getOptionValue(OUTPUT_FILE));
        }

        if (!parameters.isValid()) {
            throw new ParseException("specified parameters are not valid: " + parameters.validate().getResult());
        }

        return parameters;
    }

    /**
     * Parse the command flags.
     *
     * @param commandLine the command line to parse
     * @param parameters the parameters we are parsing into
     * @throws ParseException on parse errors
     */
    private void parseFlags(CommandLine commandLine, EventGeneratorParameters parameters) throws ParseException {
        if (commandLine.hasOption('H')) {
            parameters.setHost(commandLine.getOptionValue(HOST));
        }

        if (commandLine.hasOption('p')) {
            parameters.setPort(((Number) commandLine.getParsedOptionValue(PORT)).intValue());
        }

        if (commandLine.hasOption("bc")) {
            parameters.setBatchCount(((Number) commandLine.getParsedOptionValue(BATCH_COUNT)).intValue());
        }

        if (commandLine.hasOption("bs")) {
            parameters.setBatchSize(((Number) commandLine.getParsedOptionValue(BATCH_SIZE)).intValue());
        }

        if (commandLine.hasOption("bd")) {
            parameters.setDelayBetweenBatches(((Number) commandLine.getParsedOptionValue(BATCH_DELAY)).longValue());
        }
    }

    /**
     * Get the parameters from a JSON file.
     *
     * @param configurationFile the location of the configuration file
     * @return the parameters read from the JSON file
     * @throws ParseException on errors reading the parameters
     */
    private EventGeneratorParameters getParametersFromJsonFile(String configurationFile) throws ParseException {
        String parameterJsonString = null;

        try {
            parameterJsonString = TextFileUtils.getTextFileAsString(configurationFile);
        } catch (IOException ioe) {
            String errorMessage = "Could not read parameters from configuration file \"" + configurationFile + "\": "
                    + ioe.getMessage();
            LOGGER.warn(errorMessage, ioe);
            throw new ParseException(errorMessage);
        }

        if (parameterJsonString == null || parameterJsonString.trim().length() == 0) {
            String errorMessage = "No parameters found in configuration file \"" + configurationFile + "\"";
            LOGGER.warn(errorMessage);
            throw new ParseException(errorMessage);
        }

        try {
            return new Gson().fromJson(parameterJsonString, EventGeneratorParameters.class);
        } catch (Exception ge) {
            String errorMessage = "Error parsing JSON parameters from configuration file \"" + configurationFile
                    + "\": " + ge.getMessage();
            LOGGER.warn(errorMessage, ge);
            throw new ParseException(errorMessage);
        }
    }

    /**
     * Get help information.
     *
     * @param mainClassName the main class name for the help output
     * @return help string
     */
    public String getHelp(final String mainClassName) {
        final StringWriter stringWriter = new StringWriter();
        final PrintWriter stringPrintWriter = new PrintWriter(stringWriter);

        final HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(stringPrintWriter, MAX_HELP_LINE_LENGTH, mainClassName + " [options...] ", "", options,
                0, 0, "");

        return stringWriter.toString();
    }

}