0d7560f89a3c8e89a1128dee13da2bdb03e96c53
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modification Copyright (C) 2020-2021 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.service.engine.main;
23
24 import java.io.File;
25 import java.util.Arrays;
26 import lombok.Getter;
27 import lombok.Setter;
28 import org.apache.commons.cli.CommandLine;
29 import org.apache.commons.cli.DefaultParser;
30 import org.apache.commons.cli.Option;
31 import org.apache.commons.cli.Options;
32 import org.apache.commons.cli.ParseException;
33 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
34 import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
35 import org.onap.policy.common.utils.cmd.CommandLineArgumentsHandler;
36 import org.onap.policy.common.utils.cmd.CommandLineException;
37 import org.onap.policy.common.utils.resources.MessageConstants;
38 import org.onap.policy.common.utils.validation.ParameterValidationUtils;
39
40 /**
41  * This class reads and handles command line parameters for the Apex main
42  * program.
43  *
44  * @author Liam Fallon (liam.fallon@ericsson.com)
45  */
46 public class ApexCommandLineArguments extends CommandLineArgumentsHandler {
47     // A system property holding the root directory for relative paths in the
48     // configuration file
49     public static final String APEX_RELATIVE_FILE_ROOT = "APEX_RELATIVE_FILE_ROOT";
50     private static final String RELATIVE_FILE_ROOT = "relative file root \"";
51
52     @Getter
53     @Setter
54     private String toscaPolicyFilePath = null;
55
56     @Getter
57     private String relativeFileRoot = null;
58
59     private CommandLine cmd = null;
60
61     /**
62      * Construct the options for the CLI editor.
63      */
64     public ApexCommandLineArguments() {
65         super(ApexMain.class.getName(), MessageConstants.POLICY_APEX_PDP, apexCustomOptions());
66     }
67
68     /**
69      * Builds Apex custom options.
70      */
71     private static Options apexCustomOptions() {
72         //@formatter:off
73         Options options = new Options();
74         options.addOption(Option.builder("h")
75                 .longOpt("help")
76                 .desc("outputs the usage of this command")
77                 .required(false)
78                 .type(Boolean.class)
79                 .build());
80         options.addOption(Option.builder("v")
81                 .longOpt("version")
82                 .desc("outputs the version of Apex")
83                 .required(false)
84                 .type(Boolean.class)
85                 .build());
86         options.addOption(Option.builder("rfr")
87                 .longOpt("relative-file-root")
88                 .desc("the root file path for relative file paths specified in the Apex configuration file, "
89                         + "defaults to the current directory from where Apex is executed")
90                 .hasArg()
91                 .argName(APEX_RELATIVE_FILE_ROOT)
92                 .required(false)
93                 .type(String.class)
94                 .build());
95         options.addOption(Option.builder("p").longOpt("tosca-policy-file")
96             .desc("the full path to the ToscaPolicy file to use.").hasArg().argName("TOSCA_POLICY_FILE")
97             .required(false)
98             .type(String.class).build());
99         //@formatter:on
100         return options;
101     }
102
103     /**
104      * Construct the options for the CLI editor and parse in the given arguments.
105      *
106      * @param args The command line arguments
107      */
108     public ApexCommandLineArguments(final String[] args) {
109         // Set up the options with the default constructor
110         this();
111
112         // Parse the arguments
113         try {
114             parse(args);
115         } catch (final CommandLineException e) {
116             throw new ApexRuntimeException("parse error on Apex parameters", e);
117         }
118     }
119
120     @Override
121     public String parse(final String[] args) throws CommandLineException {
122         // Clear all our arguments
123         setToscaPolicyFilePath(null);
124         setRelativeFileRoot(null);
125
126         try {
127             cmd = new DefaultParser().parse(apexCustomOptions(), args);
128         } catch (final ParseException e) {
129             throw new CommandLineException("invalid command line arguments specified", e);
130         }
131
132         // Arguments left over after Commons CLI does its stuff
133         final String[] remainingArgs = cmd.getArgs();
134
135         if (remainingArgs.length > 0 && cmd.hasOption('p') || remainingArgs.length > 1) {
136             throw new CommandLineException("too many command line arguments specified: " + Arrays.toString(args));
137         }
138
139         if (remainingArgs.length == 1) {
140             toscaPolicyFilePath = remainingArgs[0];
141         }
142
143         if (cmd.hasOption('h')) {
144             return help();
145         }
146
147         if (cmd.hasOption('v')) {
148             return version();
149         }
150
151         if (cmd.hasOption("rfr")) {
152             setRelativeFileRoot(cmd.getOptionValue("rfr"));
153         }
154
155         if (cmd.hasOption('p')) {
156             setToscaPolicyFilePath(cmd.getOptionValue('p'));
157         }
158         return null;
159     }
160
161     @Override
162     public CommandLine getCommandLine() {
163         return this.cmd;
164     }
165
166     /**
167      * Validate the command line options.
168      *
169      * @throws ApexException on command argument validation errors
170      */
171     public void validateInputFiles() throws ApexException {
172         try {
173             validateReadableFile("Tosca Policy", toscaPolicyFilePath);
174         } catch (CommandLineException e) {
175             throw new ApexException(e.getMessage());
176         }
177         validateRelativeFileRoot();
178     }
179
180     /**
181      * Sets the root file path for relative file paths in the configuration file.
182      *
183      * @param relativeFileRoot the configuration file path
184      */
185     public void setRelativeFileRoot(final String relativeFileRoot) {
186         String relativeFileRootValue = relativeFileRoot;
187
188         if (!ParameterValidationUtils.validateStringParameter(relativeFileRoot)) {
189             relativeFileRootValue = System.getProperty(APEX_RELATIVE_FILE_ROOT);
190         }
191
192         if (!ParameterValidationUtils.validateStringParameter(relativeFileRootValue)) {
193             relativeFileRootValue = System.getProperty("user.dir");
194         } else if (!(new File(relativeFileRootValue).isAbsolute())) {
195             relativeFileRootValue = System.getProperty("user.dir") + File.separator + relativeFileRootValue;
196         }
197
198         this.relativeFileRoot = relativeFileRootValue;
199         System.setProperty(APEX_RELATIVE_FILE_ROOT, relativeFileRootValue);
200     }
201
202     /**
203      * Validate the relative file root.
204      */
205     private void validateRelativeFileRoot() throws ApexException {
206         File relativeFileRootPath = new File(relativeFileRoot);
207         if (!relativeFileRootPath.isDirectory()) {
208             throw new ApexException(RELATIVE_FILE_ROOT + relativeFileRoot + "\" does not exist or is not a directory");
209         }
210
211         if (!relativeFileRootPath.canRead()) {
212             throw new ApexException(RELATIVE_FILE_ROOT + relativeFileRoot + "\" is not a readable directory");
213         }
214
215         if (!relativeFileRootPath.canExecute()) {
216             throw new ApexException(RELATIVE_FILE_ROOT + relativeFileRoot + "\" is not an executable directory");
217         }
218     }
219
220 }