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