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