Flesh out DMaaP simulator
[policy/models.git] / models-sim / models-sim-dmaap / src / main / java / org / onap / policy / models / sim / dmaap / startstop / DmaapSimCommandLineArguments.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
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.models.sim.dmaap.startstop;
23
24 import java.io.File;
25 import java.io.PrintWriter;
26 import java.io.StringWriter;
27 import java.net.URL;
28 import java.util.Arrays;
29 import lombok.Getter;
30 import lombok.Setter;
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.apache.commons.lang3.StringUtils;
38 import org.onap.policy.common.utils.resources.ResourceUtils;
39 import org.onap.policy.models.sim.dmaap.DmaapSimException;
40 import org.onap.policy.models.sim.dmaap.DmaapSimRuntimeException;
41
42
43 /**
44  * This class reads and handles command line parameters for the DMaaP simulator service.
45  */
46 public class DmaapSimCommandLineArguments {
47     private static final String FILE_MESSAGE_PREAMBLE = " file \"";
48     private static final int HELP_LINE_LENGTH = 120;
49
50     private final Options options;
51
52     @Getter
53     @Setter
54     private String configurationFilePath = null;
55
56     /**
57      * Construct the options for the CLI editor.
58      */
59     public DmaapSimCommandLineArguments() {
60         //@formatter:off
61         options = new Options();
62         options.addOption(Option.builder("h")
63                 .longOpt("help")
64                 .desc("outputs the usage of this command")
65                 .required(false)
66                 .type(Boolean.class)
67                 .build());
68         options.addOption(Option.builder("v")
69                 .longOpt("version")
70                 .desc("outputs the version of DMaaP simulator")
71                 .required(false)
72                 .type(Boolean.class)
73                 .build());
74         options.addOption(Option.builder("c")
75                 .longOpt("config-file")
76                 .desc("the full path to the configuration file to use, "
77                         + "the configuration file must be a Json file containing the DMaaP simulator parameters")
78                 .hasArg()
79                 .argName("CONFIG_FILE")
80                 .required(false)
81                 .type(String.class)
82                 .build());
83         //@formatter:on
84     }
85
86     /**
87      * Construct the options for the CLI editor and parse in the given arguments.
88      *
89      * @param args The command line arguments
90      */
91     public DmaapSimCommandLineArguments(final String[] args) {
92         // Set up the options with the default constructor
93         this();
94
95         // Parse the arguments
96         try {
97             parse(args);
98         } catch (final DmaapSimException e) {
99             throw new DmaapSimRuntimeException("parse error on DMaaP simulator parameters", e);
100         }
101     }
102
103     /**
104      * Parse the command line options.
105      *
106      * @param args The command line arguments
107      * @return a string with a message for help and version, or null if there is no message
108      * @throws DmaapSimException on command argument errors
109      */
110     public String parse(final String[] args) throws DmaapSimException {
111         // Clear all our arguments
112         setConfigurationFilePath(null);
113
114         CommandLine commandLine = null;
115         try {
116             commandLine = new DefaultParser().parse(options, args);
117         } catch (final ParseException e) {
118             throw new DmaapSimException("invalid command line arguments specified : " + e.getMessage());
119         }
120
121         // Arguments left over after Commons CLI does its stuff
122         final String[] remainingArgs = commandLine.getArgs();
123
124         if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 0) {
125             throw new DmaapSimException("too many command line arguments specified : " + Arrays.toString(args));
126         }
127
128         if (remainingArgs.length == 1) {
129             configurationFilePath = remainingArgs[0];
130         }
131
132         if (commandLine.hasOption('h')) {
133             return help(Main.class.getName());
134         }
135
136         if (commandLine.hasOption('v')) {
137             return version();
138         }
139
140         if (commandLine.hasOption('c')) {
141             setConfigurationFilePath(commandLine.getOptionValue('c'));
142         }
143
144         return null;
145     }
146
147     /**
148      * Validate the command line options.
149      *
150      * @throws DmaapSimException on command argument validation errors
151      */
152     public void validate() throws DmaapSimException {
153         validateFileExists("DMaaP simulator configuration", configurationFilePath);
154     }
155
156     /**
157      * Print version information for DMaaP simulator.
158      *
159      * @return the version string
160      */
161     public String version() {
162         return ResourceUtils.getResourceAsString("version.txt");
163     }
164
165     /**
166      * Print help information for DMaaP simulator.
167      *
168      * @param mainClassName the main class name
169      * @return the help string
170      */
171     public String help(final String mainClassName) {
172         final HelpFormatter helpFormatter = new HelpFormatter();
173         final StringWriter stringWriter = new StringWriter();
174         final PrintWriter printWriter = new PrintWriter(stringWriter);
175
176         helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0,
177                 0, "");
178
179         return stringWriter.toString();
180     }
181
182     /**
183      * Gets the full expanded configuration file path.
184      *
185      * @return the configuration file path
186      */
187     public String getFullConfigurationFilePath() {
188         return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
189     }
190
191     /**
192      * Check set configuration file path.
193      *
194      * @return true, if check set configuration file path
195      */
196     public boolean checkSetConfigurationFilePath() {
197         return configurationFilePath != null && configurationFilePath.length() > 0;
198     }
199
200     /**
201      * Validate file exists.
202      *
203      * @param fileTag the file tag
204      * @param fileName the file name
205      * @throws DmaapSimException on the file name passed as a parameter
206      */
207     private void validateFileExists(final String fileTag, final String fileName) throws DmaapSimException {
208         if (StringUtils.isBlank(fileName)) {
209             throw new DmaapSimException(fileTag + " file was not specified as an argument");
210         }
211
212         // The file name refers to a resource on the local file system
213         final URL fileUrl = ResourceUtils.getUrl4Resource(fileName);
214         if (fileUrl == null) {
215             throw new DmaapSimException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
216         }
217
218         final File theFile = new File(fileUrl.getPath());
219         if (!theFile.exists()) {
220             throw new DmaapSimException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
221         }
222     }
223 }