26fca0eab52073feac4b5385b8e3458829177968
[policy/api.git] / main / src / main / java / org / onap / policy / api / main / startstop / ApiCommandLineArguments.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Samsung Electronics Co., Ltd. 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.api.main.startstop;
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 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.api.main.exception.PolicyApiException;
35 import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
36 import org.onap.policy.common.utils.resources.ResourceUtils;
37
38 /**
39  * This class reads and handles command line parameters for the policy api main program.
40  */
41 public class ApiCommandLineArguments {
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
51     /**
52      * Construct the options for the CLI editor.
53      */
54     public ApiCommandLineArguments() {
55         //@formatter:off
56         options = new Options();
57         options.addOption(Option.builder("h")
58                 .longOpt("help")
59                 .desc("outputs the usage of this command")
60                 .required(false)
61                 .type(Boolean.class)
62                 .build());
63         options.addOption(Option.builder("v")
64                 .longOpt("version")
65                 .desc("outputs the version of policy api")
66                 .required(false)
67                 .type(Boolean.class)
68                 .build());
69         options.addOption(Option.builder("c")
70                 .longOpt("config-file")
71                 .desc("the full path to the configuration file to use, "
72                         + "the configuration file must be a Json file containing the policy api parameters")
73                 .hasArg()
74                 .argName("CONFIG_FILE")
75                 .required(false)
76                 .type(String.class)
77                 .build());
78         //@formatter:on
79     }
80
81     /**
82      * Construct the options for the CLI editor and parse in the given arguments.
83      *
84      * @param args The command line arguments
85      */
86     public ApiCommandLineArguments(final String[] args) {
87         // Set up the options with the default constructor
88         this();
89
90         // Parse the arguments
91         try {
92             parse(args);
93         } catch (final PolicyApiException e) {
94             throw new PolicyApiRuntimeException("parse error on policy api parameters", e);
95         }
96     }
97
98     /**
99      * Parse the command line options.
100      *
101      * @param args The command line arguments
102      * @return a string with a message for help and version, or null if there is no message
103      * @throws PolicyApiException on command argument errors
104      */
105     public String parse(final String[] args) throws PolicyApiException {
106         // Clear all our arguments
107         setConfigurationFilePath(null);
108
109         CommandLine commandLine = null;
110         try {
111             commandLine = new DefaultParser().parse(options, args);
112         } catch (final ParseException e) {
113             throw new PolicyApiException("invalid command line arguments specified : " + e.getMessage());
114         }
115
116         // Arguments left over after Commons CLI does its stuff
117         final String[] remainingArgs = commandLine.getArgs();
118
119         if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 0) {
120             throw new PolicyApiException(
121                     "too many command line arguments specified : " + Arrays.toString(args));
122         }
123
124         if (remainingArgs.length == 1) {
125             configurationFilePath = remainingArgs[0];
126         }
127
128         if (commandLine.hasOption('h')) {
129             return help(Main.class.getName());
130         }
131
132         if (commandLine.hasOption('v')) {
133             return version();
134         }
135
136         if (commandLine.hasOption('c')) {
137             setConfigurationFilePath(commandLine.getOptionValue('c'));
138         }
139
140         return null;
141     }
142
143     /**
144      * Validate the command line options.
145      *
146      * @throws PolicyApiException on command argument validation errors
147      */
148     public void validate() throws PolicyApiException {
149         validateReadableFile("policy api configuration", configurationFilePath);
150     }
151
152     /**
153      * Print version information for policy api.
154      *
155      * @return the version string
156      */
157     public String version() {
158         return ResourceUtils.getResourceAsString("version.txt");
159     }
160
161     /**
162      * Print help information for policy api.
163      *
164      * @param mainClassName the main class name
165      * @return the help string
166      */
167     public String help(final String mainClassName) {
168         final HelpFormatter helpFormatter = new HelpFormatter();
169         final StringWriter stringWriter = new StringWriter();
170         final PrintWriter printWriter = new PrintWriter(stringWriter);
171
172         helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0,
173                 0, "");
174
175         return stringWriter.toString();
176     }
177
178     /**
179      * Gets the configuration file path.
180      *
181      * @return the configuration file path
182      */
183     public String getConfigurationFilePath() {
184         return configurationFilePath;
185     }
186
187     /**
188      * Gets the full expanded configuration file path.
189      *
190      * @return the configuration file path
191      */
192     public String getFullConfigurationFilePath() {
193         return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
194     }
195
196     /**
197      * Sets the configuration file path.
198      *
199      * @param configurationFilePath the configuration file path
200      */
201     public void setConfigurationFilePath(final String configurationFilePath) {
202         this.configurationFilePath = configurationFilePath;
203
204     }
205
206     /**
207      * Check set configuration file path.
208      *
209      * @return true, if check set configuration file path
210      */
211     public boolean checkSetConfigurationFilePath() {
212         return configurationFilePath != null && configurationFilePath.length() > 0;
213     }
214
215     /**
216      * Validate readable file.
217      *
218      * @param fileTag the file tag
219      * @param fileName the file name
220      * @throws PolicyApiException on the file name passed as a parameter
221      */
222     private void validateReadableFile(final String fileTag, final String fileName) throws PolicyApiException {
223         if (fileName == null || fileName.length() == 0) {
224             throw new PolicyApiException(fileTag + " file was not specified as an argument");
225         }
226
227         // The file name refers to a resource on the local file system
228         final URL fileUrl = ResourceUtils.getUrl4Resource(fileName);
229         if (fileUrl == null) {
230             throw new PolicyApiException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
231         }
232
233         final File theFile = new File(fileUrl.getPath());
234         if (!theFile.exists()) {
235             throw new PolicyApiException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
236         }
237         if (!theFile.isFile()) {
238             throw new PolicyApiException(
239                     fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file");
240         }
241         if (!theFile.canRead()) {
242             throw new PolicyApiException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable");
243         }
244     }
245 }