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