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