Changes for Checkstyle 8.32
[policy/models.git] / models-sim / policy-models-sim-pdp / src / main / java / org / onap / policy / models / sim / pdp / PdpSimulatorCommandLineArguments.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2019, 2020 AT&T Intellectual Property. All rights reserved.
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.models.sim.pdp;
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 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.models.sim.pdp.exception.PdpSimulatorException;
37 import org.onap.policy.models.sim.pdp.exception.PdpSimulatorRunTimeException;
38
39 /**
40  * This class reads and handles command line parameters for the pdp simulator.
41  *
42  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
43  */
44 public class PdpSimulatorCommandLineArguments {
45
46     private static final String FILE_MESSAGE_PREAMBLE = " file \"";
47     private static final int HELP_LINE_LENGTH = 120;
48
49     private final Options options;
50     private String configurationFilePath = null;
51     private String propertyFilePath = null;
52
53     /**
54      * Construct the options for the CLI editor.
55      */
56     public PdpSimulatorCommandLineArguments() {
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 pdp simulator")
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 pdp simulator parameters")
75                 .hasArg()
76                 .argName("CONFIG_FILE")
77                 .required(false)
78                 .type(String.class)
79                 .build());
80         options.addOption(Option.builder("p")
81                 .longOpt("property-file")
82                 .desc("the full path to the topic property file to use, "
83                         + "the property file contains the pdp simulator topic properties")
84                 .hasArg()
85                 .argName("PROP_FILE")
86                 .required(false)
87                 .type(String.class)
88                 .build());
89         //@formatter:on
90     }
91
92     /**
93      * Construct the options for the CLI editor and parse in the given arguments.
94      *
95      * @param args The command line arguments
96      */
97     public PdpSimulatorCommandLineArguments(final String[] args) {
98         // Set up the options with the default constructor
99         this();
100
101         // Parse the arguments
102         try {
103             parse(args);
104         } catch (final PdpSimulatorException e) {
105             throw new PdpSimulatorRunTimeException("parse error on pdp simulator parameters", e);
106         }
107     }
108
109     /**
110      * Parse the command line options.
111      *
112      * @param args The command line arguments
113      * @return a string with a message for help and version, or null if there is no message
114      * @throws PdpSimulatorException on command argument errors
115      */
116     public String parse(final String[] args) throws PdpSimulatorException {
117         // Clear all our arguments
118         setConfigurationFilePath(null);
119         setPropertyFilePath(null);
120
121         CommandLine commandLine = null;
122         try {
123             commandLine = new DefaultParser().parse(options, args);
124         } catch (final ParseException e) {
125             throw new PdpSimulatorException("invalid command line arguments specified : " + e.getMessage());
126         }
127
128         // Arguments left over after Commons CLI does its stuff
129         final String[] remainingArgs = commandLine.getArgs();
130
131         if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 0) {
132             throw new PdpSimulatorException("too many command line arguments specified : " + Arrays.toString(args));
133         }
134
135         if (remainingArgs.length == 1) {
136             configurationFilePath = remainingArgs[0];
137         }
138
139         if (commandLine.hasOption('h')) {
140             return help(PdpSimulatorMain.class.getName());
141         }
142
143         if (commandLine.hasOption('v')) {
144             return version();
145         }
146
147         if (commandLine.hasOption('c')) {
148             setConfigurationFilePath(commandLine.getOptionValue('c'));
149         }
150
151         if (commandLine.hasOption('p')) {
152             setPropertyFilePath(commandLine.getOptionValue('p'));
153         }
154
155         return null;
156     }
157
158     /**
159      * Validate the command line options.
160      *
161      * @throws PdpSimulatorException on command argument validation errors
162      */
163     public void validate() throws PdpSimulatorException {
164         validateReadableFile("pdp simulator configuration", configurationFilePath);
165     }
166
167     /**
168      * Print version information for pdp simulator.
169      *
170      * @return the version string
171      */
172     public String version() {
173         return ResourceUtils.getResourceAsString("src/main/resources/version.txt");
174     }
175
176     /**
177      * Print help information for pdp simulator.
178      *
179      * @param mainClassName the main class name
180      * @return the help string
181      */
182     public String help(final String mainClassName) {
183         final HelpFormatter helpFormatter = new HelpFormatter();
184         final StringWriter stringWriter = new StringWriter();
185         final PrintWriter printWriter = new PrintWriter(stringWriter);
186
187         helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0,
188                 0, "");
189
190         return stringWriter.toString();
191     }
192
193     /**
194      * Gets the configuration file path.
195      *
196      * @return the configuration file path
197      */
198     public String getConfigurationFilePath() {
199         return configurationFilePath;
200     }
201
202     /**
203      * Gets the full expanded configuration file path.
204      *
205      * @return the configuration file path
206      */
207     public String getFullConfigurationFilePath() {
208         return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
209     }
210
211     /**
212      * Sets the configuration file path.
213      *
214      * @param configurationFilePath the configuration file path
215      */
216     public void setConfigurationFilePath(final String configurationFilePath) {
217         this.configurationFilePath = configurationFilePath;
218
219     }
220
221     /**
222      * Check set configuration file path.
223      *
224      * @return true, if check set configuration file path
225      */
226     public boolean checkSetConfigurationFilePath() {
227         return configurationFilePath != null && configurationFilePath.length() > 0;
228     }
229
230     /**
231      * Gets the property file path.
232      *
233      * @return the property file path
234      */
235     public String getPropertyFilePath() {
236         return propertyFilePath;
237     }
238
239     /**
240      * Gets the full expanded property file path.
241      *
242      * @return the property file path
243      */
244     public String getFullPropertyFilePath() {
245         return ResourceUtils.getFilePath4Resource(getPropertyFilePath());
246     }
247
248     /**
249      * Sets the property file path.
250      *
251      * @param propertyFilePath the property file path
252      */
253     public void setPropertyFilePath(final String propertyFilePath) {
254         this.propertyFilePath = propertyFilePath;
255
256     }
257
258     /**
259      * Check set property file path.
260      *
261      * @return true, if check set property file path
262      */
263     public boolean checkSetPropertyFilePath() {
264         return propertyFilePath != null && propertyFilePath.length() > 0;
265     }
266
267     /**
268      * Validate readable file.
269      *
270      * @param fileTag the file tag
271      * @param fileName the file name
272      * @throws PdpSimulatorException on the file name passed as a parameter
273      */
274     private void validateReadableFile(final String fileTag, final String fileName) throws PdpSimulatorException {
275         if (fileName == null || fileName.length() == 0) {
276             throw new PdpSimulatorException(fileTag + " file was not specified as an argument");
277         }
278
279         // The file name refers to a resource on the local file system
280         final URL fileUrl = ResourceUtils.getUrl4Resource(fileName);
281         if (fileUrl == null) {
282             throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
283         }
284
285         final File theFile = new File(fileUrl.getPath());
286         if (!theFile.exists()) {
287             throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
288         }
289         if (!theFile.isFile()) {
290             throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file");
291         }
292         if (!theFile.canRead()) {
293             throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable");
294         }
295     }
296
297 }