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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.service.engine.main;
24 import java.io.PrintWriter;
25 import java.io.StringWriter;
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;
40 * This class reads and handles command line parameters for the Apex main program.
42 * @author Liam Fallon (liam.fallon@ericsson.com)
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";
48 // Recurring string constants
49 private static final String FILE_PREAMBLE = " file \"";
50 private static final int HELP_LINE_LENGTH = 120;
52 // Apache Commons CLI options
53 private final Options options;
55 // The command line options
56 private String modelFilePath = null;
57 private String configurationFilePath = null;
58 private String relativeFileRoot = null;
61 * Construct the options for the CLI editor.
63 public ApexCommandLineArguments() {
65 options = new Options();
66 options.addOption(Option.builder("h")
68 .desc("outputs the usage of this command")
72 options.addOption(Option.builder("v")
74 .desc("outputs the version of Apex")
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")
84 .argName("CONFIG_FILE")
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")
93 .argName(RELATIVE_FILE_ROOT)
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")
101 .type(String.class).build());
106 * Construct the options for the CLI editor and parse in the given arguments.
108 * @param args The command line arguments
110 public ApexCommandLineArguments(final String[] args) {
111 // Set up the options with the default constructor
114 // Parse the arguments
117 } catch (final ApexException e) {
118 throw new ApexRuntimeException("parse error on Apex parameters", e);
123 * Parse the command line options.
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
129 public String parse(final String[] args) throws ApexException {
130 // Clear all our arguments
131 setConfigurationFilePath(null);
132 setModelFilePath(null);
134 CommandLine commandLine = null;
136 commandLine = new DefaultParser().parse(options, args);
137 } catch (final ParseException e) {
138 throw new ApexException("invalid command line arguments specified : " + e.getMessage());
141 // Arguments left over after Commons CLI does its stuff
142 final String[] remainingArgs = commandLine.getArgs();
144 if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 1) {
145 throw new ApexException("too many command line arguments specified : " + Arrays.toString(args));
148 if (remainingArgs.length == 1) {
149 configurationFilePath = remainingArgs[0];
152 if (commandLine.hasOption('h')) {
153 return help(ApexMain.class.getName());
156 if (commandLine.hasOption('v')) {
160 if (commandLine.hasOption('c')) {
161 setConfigurationFilePath(commandLine.getOptionValue('c'));
164 if (commandLine.hasOption("rfr")) {
165 setRelativeFileRoot(commandLine.getOptionValue("rfr"));
167 setRelativeFileRoot(null);
170 if (commandLine.hasOption('m')) {
171 setModelFilePath(commandLine.getOptionValue('m'));
178 * Validate the command line options.
180 * @throws ApexException on command argument validation errors
182 public void validate() throws ApexException {
183 validateReadableFile("Apex configuration", configurationFilePath);
185 if (checkSetModelFilePath()) {
186 validateReadableFile("Apex model", modelFilePath);
189 validateRelativeFileRoot();
193 * Print version information for Apex.
195 * @return the version string
197 public String version() {
198 return ResourceUtils.getResourceAsString("version.txt");
202 * Print help information for Apex.
204 * @param mainClassName the main class name
205 * @return the help string
207 public String help(final String mainClassName) {
208 final StringWriter stringWriter = new StringWriter();
209 final PrintWriter stringPrintWriter = new PrintWriter(stringWriter);
211 new HelpFormatter().printHelp(stringPrintWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options",
214 return stringWriter.toString();
218 * Gets the model file path.
220 * @return the model file path
222 public String getModelFilePath() {
223 return ResourceUtils.getFilePath4Resource(modelFilePath);
227 * Sets the model file path.
229 * @param modelFilePath the model file path
231 public void setModelFilePath(final String modelFilePath) {
232 this.modelFilePath = modelFilePath;
236 * Check set model file path.
238 * @return true, if check set model file path
240 public boolean checkSetModelFilePath() {
241 return modelFilePath != null && modelFilePath.length() > 0;
245 * Gets the configuration file path.
247 * @return the configuration file path
249 public String getConfigurationFilePath() {
250 return configurationFilePath;
254 * Gets the root file path for relative file paths in the configuration file.
256 * @return the root file path
258 public String getRelativeFileRoot() {
259 return relativeFileRoot;
263 * Gets the full expanded configuration file path.
265 * @return the configuration file path
267 public String getFullConfigurationFilePath() {
268 return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
272 * Sets the configuration file path.
274 * @param configurationFilePath the configuration file path
276 public void setConfigurationFilePath(final String configurationFilePath) {
277 this.configurationFilePath = configurationFilePath;
282 * Sets the root file path for relative file paths in the configuration file.
284 * @param relativeFileRoot the configuration file path
286 public void setRelativeFileRoot(final String relativeFileRoot) {
287 String relativeFileRootValue = relativeFileRoot;
289 if (!ParameterValidationUtils.validateStringParameter(relativeFileRoot)) {
290 relativeFileRootValue = System.getProperty(RELATIVE_FILE_ROOT);
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;
299 this.relativeFileRoot = relativeFileRootValue;
300 System.setProperty(RELATIVE_FILE_ROOT, relativeFileRootValue);
304 * Check set configuration file path.
306 * @return true, if check set configuration file path
308 public boolean checkSetConfigurationFilePath() {
309 return configurationFilePath != null && configurationFilePath.length() > 0;
313 * Validate readable file.
315 * @param fileTag the file tag
316 * @param fileName the file name
317 * @throws ApexException the apex exception
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");
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");
330 final File theFile = new File(fileUrl.getPath());
331 if (!theFile.exists()) {
332 throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" does not exist");
334 if (!theFile.isFile()) {
335 throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" is not a normal file");
337 if (!theFile.canRead()) {
338 throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" is ureadable");
343 * Validate the relative file root.
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");
352 if (!relativeFileRootPath.canWrite()) {
353 throw new ApexException(
354 "relative file root \"" + relativeFileRoot + "\" does not exist or is not a directory");