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