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