Changes for checkstyle 8.32
[policy/apex-pdp.git] / services / services-engine / src / main / java / org / onap / policy / apex / service / engine / main / ApexCommandLineArguments.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-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.service.engine.main;
22
23 import java.io.File;
24 import java.io.PrintWriter;
25 import java.io.StringWriter;
26 import java.net.URL;
27 import java.util.Arrays;
28 import org.apache.commons.cli.CommandLine;
29 import org.apache.commons.cli.DefaultParser;
30 import org.apache.commons.cli.HelpFormatter;
31 import org.apache.commons.cli.Option;
32 import org.apache.commons.cli.Options;
33 import org.apache.commons.cli.ParseException;
34 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
35 import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
36 import org.onap.policy.common.utils.resources.ResourceUtils;
37 import org.onap.policy.common.utils.validation.ParameterValidationUtils;
38
39 /**
40  * This class reads and handles command line parameters for the Apex main program.
41  *
42  * @author Liam Fallon (liam.fallon@ericsson.com)
43  */
44 public class ApexCommandLineArguments {
45     // A system property holding the root directory for relative paths in the configuration file
46     public static final String RELATIVE_FILE_ROOT = "APEX_RELATIVE_FILE_ROOT";
47
48     // Recurring string constants
49     private static final String FILE_PREAMBLE = " file \"";
50     private static final int HELP_LINE_LENGTH = 120;
51
52     // Apache Commons CLI options
53     private final Options options;
54
55     // The command line options
56     private String modelFilePath = null;
57     private String configurationFilePath = null;
58     private String relativeFileRoot = null;
59
60     /**
61      * Construct the options for the CLI editor.
62      */
63     public ApexCommandLineArguments() {
64         //@formatter:off
65         options = new Options();
66         options.addOption(Option.builder("h")
67                 .longOpt("help")
68                 .desc("outputs the usage of this command")
69                 .required(false)
70                 .type(Boolean.class)
71                 .build());
72         options.addOption(Option.builder("v")
73                         .longOpt("version")
74                         .desc("outputs the version of Apex")
75                         .required(false)
76                         .type(Boolean.class)
77                         .build());
78         options.addOption(Option.builder("c")
79                         .longOpt("config-file")
80                         .desc("the full path to the configuration file to use, "
81                                         + "the configuration file must be a Json file "
82                                         + "containing the Apex configuration parameters")
83                         .hasArg()
84                         .argName("CONFIG_FILE")
85                         .required(false)
86                         .type(String.class)
87                         .build());
88         options.addOption(Option.builder("rfr")
89                         .longOpt("relative-file-root")
90                         .desc("the root file path for relative file paths specified in the Apex configuration file, "
91                                         + "defaults to the current directory from where Apex is executed")
92                         .hasArg()
93                         .argName(RELATIVE_FILE_ROOT)
94                         .required(false)
95                         .type(String.class)
96                         .build());
97         options.addOption(Option.builder("m").longOpt("model-file")
98                 .desc("the full path to the model file to use, if set it overrides the model file set in the "
99                         + "configuration file").hasArg().argName("MODEL_FILE")
100                 .required(false)
101                 .type(String.class).build());
102         //@formatter:on
103     }
104
105     /**
106      * Construct the options for the CLI editor and parse in the given arguments.
107      *
108      * @param args The command line arguments
109      */
110     public ApexCommandLineArguments(final String[] args) {
111         // Set up the options with the default constructor
112         this();
113
114         // Parse the arguments
115         try {
116             parse(args);
117         } catch (final ApexException e) {
118             throw new ApexRuntimeException("parse error on Apex parameters", e);
119         }
120     }
121
122     /**
123      * Parse the command line options.
124      *
125      * @param args The command line arguments
126      * @return a string with a message for help and version, or null if there is no message
127      * @throws ApexException on command argument errors
128      */
129     public String parse(final String[] args) throws ApexException {
130         // Clear all our arguments
131         setConfigurationFilePath(null);
132         setModelFilePath(null);
133
134         CommandLine commandLine = null;
135         try {
136             commandLine = new DefaultParser().parse(options, args);
137         } catch (final ParseException e) {
138             throw new ApexException("invalid command line arguments specified : " + e.getMessage());
139         }
140
141         // Arguments left over after Commons CLI does its stuff
142         final String[] remainingArgs = commandLine.getArgs();
143
144         if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 1) {
145             throw new ApexException("too many command line arguments specified : " + Arrays.toString(args));
146         }
147
148         if (remainingArgs.length == 1) {
149             configurationFilePath = remainingArgs[0];
150         }
151
152         if (commandLine.hasOption('h')) {
153             return help(ApexMain.class.getName());
154         }
155
156         if (commandLine.hasOption('v')) {
157             return version();
158         }
159
160         if (commandLine.hasOption('c')) {
161             setConfigurationFilePath(commandLine.getOptionValue('c'));
162         }
163
164         if (commandLine.hasOption("rfr")) {
165             setRelativeFileRoot(commandLine.getOptionValue("rfr"));
166         } else {
167             setRelativeFileRoot(null);
168         }
169
170         if (commandLine.hasOption('m')) {
171             setModelFilePath(commandLine.getOptionValue('m'));
172         }
173
174         return null;
175     }
176
177     /**
178      * Validate the command line options.
179      *
180      * @throws ApexException on command argument validation errors
181      */
182     public void validate() throws ApexException {
183         validateReadableFile("Apex configuration", configurationFilePath);
184
185         if (checkSetModelFilePath()) {
186             validateReadableFile("Apex model", modelFilePath);
187         }
188
189         validateRelativeFileRoot();
190     }
191
192     /**
193      * Print version information for Apex.
194      * 
195      * @return the version string
196      */
197     public String version() {
198         return ResourceUtils.getResourceAsString("version.txt");
199     }
200
201     /**
202      * Print help information for Apex.
203      *
204      * @param mainClassName the main class name
205      * @return the help string
206      */
207     public String help(final String mainClassName) {
208         final StringWriter stringWriter = new StringWriter();
209         final PrintWriter stringPrintWriter = new PrintWriter(stringWriter);
210
211         new HelpFormatter().printHelp(stringPrintWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options",
212                         options, 0, 0, "");
213
214         return stringWriter.toString();
215     }
216
217     /**
218      * Gets the model file path.
219      *
220      * @return the model file path
221      */
222     public String getModelFilePath() {
223         return ResourceUtils.getFilePath4Resource(modelFilePath);
224     }
225
226     /**
227      * Sets the model file path.
228      *
229      * @param modelFilePath the model file path
230      */
231     public void setModelFilePath(final String modelFilePath) {
232         this.modelFilePath = modelFilePath;
233     }
234
235     /**
236      * Check set model file path.
237      *
238      * @return true, if check set model file path
239      */
240     public boolean checkSetModelFilePath() {
241         return modelFilePath != null && modelFilePath.length() > 0;
242     }
243
244     /**
245      * Gets the configuration file path.
246      *
247      * @return the configuration file path
248      */
249     public String getConfigurationFilePath() {
250         return configurationFilePath;
251     }
252
253     /**
254      * Gets the root file path for relative file paths in the configuration file.
255      *
256      * @return the root file path
257      */
258     public String getRelativeFileRoot() {
259         return relativeFileRoot;
260     }
261
262     /**
263      * Gets the full expanded configuration file path.
264      *
265      * @return the configuration file path
266      */
267     public String getFullConfigurationFilePath() {
268         return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
269     }
270
271     /**
272      * Sets the configuration file path.
273      *
274      * @param configurationFilePath the configuration file path
275      */
276     public void setConfigurationFilePath(final String configurationFilePath) {
277         this.configurationFilePath = configurationFilePath;
278
279     }
280
281     /**
282      * Sets the root file path for relative file paths in the configuration file.
283      *
284      * @param relativeFileRoot the configuration file path
285      */
286     public void setRelativeFileRoot(final String relativeFileRoot) {
287         String relativeFileRootValue = relativeFileRoot;
288
289         if (!ParameterValidationUtils.validateStringParameter(relativeFileRoot)) {
290             relativeFileRootValue = System.getProperty(RELATIVE_FILE_ROOT);
291         }
292
293         if (!ParameterValidationUtils.validateStringParameter(relativeFileRootValue)) {
294             relativeFileRootValue = System.getProperty("user.dir");
295         } else if (!(new File(relativeFileRootValue).isAbsolute())) {
296             relativeFileRootValue = System.getProperty("user.dir") + File.separator + relativeFileRootValue;
297         }
298
299         this.relativeFileRoot = relativeFileRootValue;
300         System.setProperty(RELATIVE_FILE_ROOT, relativeFileRootValue);
301     }
302
303     /**
304      * Check set configuration file path.
305      *
306      * @return true, if check set configuration file path
307      */
308     public boolean checkSetConfigurationFilePath() {
309         return configurationFilePath != null && configurationFilePath.length() > 0;
310     }
311
312     /**
313      * Validate readable file.
314      *
315      * @param fileTag the file tag
316      * @param fileName the file name
317      * @throws ApexException the apex exception
318      */
319     private void validateReadableFile(final String fileTag, final String fileName) throws ApexException {
320         if (fileName == null || fileName.length() == 0) {
321             throw new ApexException(fileTag + " file was not specified as an argument");
322         }
323
324         // The file name can refer to a resource on the local file system or on the class path
325         final URL fileUrl = ResourceUtils.getUrl4Resource(fileName);
326         if (fileUrl == null) {
327             throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" does not exist");
328         }
329
330         final File theFile = new File(fileUrl.getPath());
331         if (!theFile.exists()) {
332             throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" does not exist");
333         }
334         if (!theFile.isFile()) {
335             throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" is not a normal file");
336         }
337         if (!theFile.canRead()) {
338             throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" is ureadable");
339         }
340     }
341
342     /**
343      * Validate the relative file root.
344      */
345     private void validateRelativeFileRoot() throws ApexException {
346         File relativeFileRootPath = new File(relativeFileRoot);
347         if (!relativeFileRootPath.isDirectory()) {
348             throw new ApexException(
349                             "relative file root \"" + relativeFileRoot + "\" does not exist or is not a directory");
350         }
351
352         if (!relativeFileRootPath.canWrite()) {
353             throw new ApexException(
354                             "relative file root \"" + relativeFileRoot + "\" does not exist or is not a directory");
355         }
356     }
357
358 }