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