Fix sonars in xacml-pdp
[policy/xacml-pdp.git] / main / src / main / java / org / onap / policy / pdpx / main / startstop / XacmlPdpCommandLineArguments.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019, 2021 AT&T Intellectual Property. 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.pdpx.main.startstop;
22
23 import java.io.File;
24 import java.io.PrintWriter;
25 import java.io.StringWriter;
26 import java.util.Arrays;
27 import org.apache.commons.cli.CommandLine;
28 import org.apache.commons.cli.DefaultParser;
29 import org.apache.commons.cli.HelpFormatter;
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.common.utils.resources.ResourceUtils;
34 import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
35 import org.onap.policy.pdpx.main.PolicyXacmlPdpRuntimeException;
36
37
38 /**
39  * This class reads and handles command line parameters for the policy xacml pdp main program.
40  */
41 public class XacmlPdpCommandLineArguments {
42     private static final String FILE_MESSAGE_PREAMBLE = " file \"";
43     private static final int HELP_LINE_LENGTH = 120;
44
45     // Apache Commons CLI options
46     private final Options options;
47
48     // The command line options
49     private String configurationFilePath = null;
50     private String propertyFilePath = null;
51
52     /**
53      * Construct the options for the CLI editor.
54      */
55     public XacmlPdpCommandLineArguments() {
56         //@formatter:off
57         options = new Options();
58         options.addOption(Option.builder("h")
59                 .longOpt("help")
60                 .desc("outputs the usage of this command")
61                 .required(false)
62                 .type(Boolean.class)
63                 .build());
64         options.addOption(Option.builder("v")
65                 .longOpt("version")
66                 .desc("outputs the version of policy xacml pdp")
67                 .required(false)
68                 .type(Boolean.class)
69                 .build());
70         options.addOption(Option.builder("c")
71                 .longOpt("config-file")
72                 .desc("the full path to the configuration file to use, "
73                         + "the configuration file must be a Json file containing the policy xacml pdp parameters")
74                 .hasArg()
75                 .argName("CONFIG_FILE")
76                 .required(false)
77                 .type(String.class)
78                 .build());
79         options.addOption(Option.builder("p")
80                 .longOpt("property-file")
81                 .desc("the full path to the topic property file to use, "
82                         + "the property file contains the policy pap topic properties")
83                 .hasArg()
84                 .argName("PROP_FILE")
85                 .required(false)
86                 .type(String.class)
87                 .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 XacmlPdpCommandLineArguments(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 PolicyXacmlPdpException e) {
104             throw new PolicyXacmlPdpRuntimeException("parse error on policy xacml pdp parameters", e);
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 PolicyXacmlPdpException on command argument errors
114      */
115     public String parse(final String[] args) throws PolicyXacmlPdpException {
116         // Clear all our arguments
117         setConfigurationFilePath(null);
118         setPropertyFilePath(null);
119
120         CommandLine commandLine = null;
121         try {
122             commandLine = new DefaultParser().parse(options, args);
123         } catch (final ParseException e) {
124             throw new PolicyXacmlPdpException("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) {
131             throw new PolicyXacmlPdpException("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(Main.class.getName());
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('p')) {
151             setPropertyFilePath(commandLine.getOptionValue('p'));
152         }
153
154         return null;
155     }
156
157     /**
158      * Validate the command line options.
159      *
160      * @throws PolicyXacmlPdpException on command argument validation errors
161      */
162     public void validate() throws PolicyXacmlPdpException {
163         validateReadableFile("policy xacml pdp configuration", configurationFilePath);
164     }
165
166     /**
167      * Print version information for policy xacml pdp.
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 policy xacml pdp.
177      *
178      * @param mainClassName the main class name
179      * @return the help string
180      */
181     public String help(final String mainClassName) {
182         final var helpFormatter = new HelpFormatter();
183         final var stringWriter = new StringWriter();
184         final var printWriter = new PrintWriter(stringWriter);
185
186         helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0,
187                 0, "");
188
189         return stringWriter.toString();
190     }
191
192     /**
193      * Gets the configuration file path.
194      *
195      * @return the configuration file path
196      */
197     public String getConfigurationFilePath() {
198         return configurationFilePath;
199     }
200
201     /**
202      * Gets the full expanded configuration file path.
203      *
204      * @return the configuration file path
205      */
206     public String getFullConfigurationFilePath() {
207         return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
208     }
209
210     /**
211      * Sets the configuration file path.
212      *
213      * @param configurationFilePath the configuration file path
214      */
215     public void setConfigurationFilePath(final String configurationFilePath) {
216         this.configurationFilePath = configurationFilePath;
217
218     }
219
220     /**
221      * Check set configuration file path.
222      *
223      * @return true, if check set configuration file path
224      */
225     public boolean checkSetConfigurationFilePath() {
226         return configurationFilePath != null && !configurationFilePath.isEmpty();
227     }
228
229     /**
230      * Gets the property file path.
231      *
232      * @return the property file path
233      */
234     public String getPropertyFilePath() {
235         return propertyFilePath;
236     }
237
238     /**
239      * Gets the full expanded property file path.
240      *
241      * @return the property file path
242      */
243     public String getFullPropertyFilePath() {
244         return ResourceUtils.getFilePath4Resource(getPropertyFilePath());
245     }
246
247     /**
248      * Sets the property file path.
249      *
250      * @param propertyFilePath the property file path
251      */
252     public void setPropertyFilePath(final String propertyFilePath) {
253         this.propertyFilePath = propertyFilePath;
254
255     }
256
257     /**
258      * Validate readable file.
259      *
260      * @param fileTag the file tag
261      * @param fileName the file name
262      * @throws PolicyXacmlPdpException on the file name passed as a parameter
263      */
264     private void validateReadableFile(final String fileTag, final String fileName) throws PolicyXacmlPdpException {
265         if (fileName == null || fileName.isEmpty()) {
266             throw new PolicyXacmlPdpException(fileTag + " file was not specified as an argument");
267         }
268
269         // The file name refers to a resource on the local file system
270         final var fileUrl = ResourceUtils.getUrl4Resource(fileName);
271         if (fileUrl == null) {
272             throw new PolicyXacmlPdpException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
273         }
274
275         final var theFile = new File(fileUrl.getPath());
276         if (!theFile.exists()) {
277             throw new PolicyXacmlPdpException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
278         }
279         if (!theFile.isFile()) {
280             throw new PolicyXacmlPdpException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file");
281         }
282         if (!theFile.canRead()) {
283             throw new PolicyXacmlPdpException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable");
284         }
285     }
286 }