02dc248b4cd092226fad3b9bc5adf77e1c227b3f
[policy/apex-pdp.git] /
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
29 import org.apache.commons.cli.CommandLine;
30 import org.apache.commons.cli.DefaultParser;
31 import org.apache.commons.cli.HelpFormatter;
32 import org.apache.commons.cli.Option;
33 import org.apache.commons.cli.Options;
34 import org.apache.commons.cli.ParseException;
35 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
36 import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
37 import org.onap.policy.apex.model.utilities.ResourceUtils;
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     private static final int HELP_LINE_LENGTH = 120;
46
47     // Apache Commons CLI options
48     private final Options options;
49
50     // The command line options
51     private String modelFilePath = null;
52     private String configurationFilePath = null;
53
54     /**
55      * Construct the options for the CLI editor.
56      */
57     public ApexCommandLineArguments() {
58         //@formatter:off
59         options = new Options();
60         options.addOption(Option.builder("h")
61                 .longOpt("help")
62                 .desc("outputs the usage of this command")
63                 .required(false)
64                 .type(Boolean.class)
65                 .build());
66         options.addOption(Option.builder("v")
67                 .longOpt("version")
68                 .desc("outputs the version of Apex")
69                 .required(false)
70                 .type(Boolean.class)
71                 .build());
72         options.addOption(Option.builder("c")
73                 .longOpt("config-file")
74                 .desc("the full path to the configuration file to use, the configuration file must be a Json file containing the Apex configuration parameters")
75                 .hasArg()
76                 .argName("CONFIG_FILE")
77                 .required(false)
78                 .type(String.class)
79                 .build());
80         options.addOption(Option.builder("m").longOpt("model-file")
81                 .desc("the full path to the model file to use, if set it overrides the model file set in the configuration file").hasArg().argName("MODEL_FILE")
82                 .required(false)
83                 .type(String.class).build());
84         //@formatter:on
85     }
86
87     /**
88      * Construct the options for the CLI editor and parse in the given arguments.
89      *
90      * @param args The command line arguments
91      */
92     public ApexCommandLineArguments(final String[] args) {
93         // Set up the options with the default constructor
94         this();
95
96         // Parse the arguments
97         try {
98             parse(args);
99         } catch (final ApexException e) {
100             throw new ApexRuntimeException("parse error on Apex parameters");
101         }
102     }
103
104     /**
105      * Parse the command line options.
106      *
107      * @param args The command line arguments
108      * @return a string with a message for help and version, or null if there is no message
109      * @throws ApexException on command argument errors
110      */
111     public String parse(final String[] args) throws ApexException {
112         // Clear all our arguments
113         setConfigurationFilePath(null);
114         setModelFilePath(null);
115
116         CommandLine commandLine = null;
117         try {
118             commandLine = new DefaultParser().parse(options, args);
119         } catch (final ParseException e) {
120             throw new ApexException("invalid command line arguments specified : " + e.getMessage());
121         }
122
123         // Arguments left over after Commons CLI does its stuff
124         final String[] remainingArgs = commandLine.getArgs();
125
126         if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 1) {
127             throw new ApexException("too many command line arguments specified : " + Arrays.toString(args));
128         }
129
130         if (remainingArgs.length == 1) {
131             configurationFilePath = remainingArgs[0];
132         }
133
134         if (commandLine.hasOption('h')) {
135             return help(ApexMain.class.getCanonicalName());
136         }
137
138         if (commandLine.hasOption('v')) {
139             return version();
140         }
141
142         if (commandLine.hasOption('c')) {
143             setConfigurationFilePath(commandLine.getOptionValue('c'));
144         }
145
146         if (commandLine.hasOption('m')) {
147             setModelFilePath(commandLine.getOptionValue('m'));
148         }
149
150         return null;
151     }
152
153     /**
154      * Validate the command line options.
155      *
156      * @throws ApexException on command argument validation errors
157      */
158     public void validate() throws ApexException {
159         validateReadableFile("Apex configuration", configurationFilePath);
160
161         if (checkSetModelFilePath()) {
162             validateReadableFile("Apex model", modelFilePath);
163         }
164     }
165
166     /**
167      * Print version information for Apex.
168      * 
169      * @return the version string
170      */
171     public String version() {
172         return ResourceUtils.getResourceAsString("version.txt");
173     }
174
175     /**
176      * Print help information for Apex.
177      *
178      * @param mainClassName the main class name
179      * @return the help string
180      */
181     public String help(final String mainClassName) {
182         final HelpFormatter helpFormatter = new HelpFormatter();
183         final StringWriter stringWriter = new StringWriter();
184         final PrintWriter stringPW = new PrintWriter(stringWriter);
185
186         helpFormatter.printHelp(stringPW, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0, 0,
187                 "");
188
189         return stringWriter.toString();
190     }
191
192     /**
193      * Gets the model file path.
194      *
195      * @return the model file path
196      */
197     public String getModelFilePath() {
198         return ResourceUtils.getFilePath4Resource(modelFilePath);
199     }
200
201     /**
202      * Sets the model file path.
203      *
204      * @param modelFilePath the model file path
205      */
206     public void setModelFilePath(final String modelFilePath) {
207         this.modelFilePath = modelFilePath;
208     }
209
210     /**
211      * Check set model file path.
212      *
213      * @return true, if check set model file path
214      */
215     public boolean checkSetModelFilePath() {
216         return modelFilePath != null && modelFilePath.length() > 0;
217     }
218
219     /**
220      * Gets the configuration file path.
221      *
222      * @return the configuration file path
223      */
224     public String getConfigurationFilePath() {
225         return configurationFilePath;
226     }
227
228     /**
229      * Gets the full expanded configuration file path.
230      *
231      * @return the configuration file path
232      */
233     public String getFullConfigurationFilePath() {
234         return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
235     }
236
237     /**
238      * Sets the configuration file path.
239      *
240      * @param configurationFilePath the configuration file path
241      */
242     public void setConfigurationFilePath(final String configurationFilePath) {
243         this.configurationFilePath = configurationFilePath;
244
245     }
246
247     /**
248      * Check set configuration file path.
249      *
250      * @return true, if check set configuration file path
251      */
252     public boolean checkSetConfigurationFilePath() {
253         return configurationFilePath != null && configurationFilePath.length() > 0;
254     }
255
256     /**
257      * Validate readable file.
258      *
259      * @param fileTag the file tag
260      * @param fileName the file name
261      * @throws ApexException the apex exception
262      */
263     private void validateReadableFile(final String fileTag, final String fileName) throws ApexException {
264         if (fileName == null || fileName.length() == 0) {
265             throw new ApexException(fileTag + " file was not specified as an argument");
266         }
267
268         // The file name can refer to a resource on the local file system or on the class path
269         final URL fileURL = ResourceUtils.getURL4Resource(fileName);
270         if (fileURL == null) {
271             throw new ApexException(fileTag + " file \"" + fileName + "\" does not exist");
272         }
273
274         final File theFile = new File(fileURL.getPath());
275         if (!theFile.exists()) {
276             throw new ApexException(fileTag + " file \"" + fileName + "\" does not exist");
277         }
278         if (!theFile.isFile()) {
279             throw new ApexException(fileTag + " file \"" + fileName + "\" is not a normal file");
280         }
281         if (!theFile.canRead()) {
282             throw new ApexException(fileTag + " file \"" + fileName + "\" is ureadable");
283         }
284     }
285 }