24c4b7d2f89ae0e2e0778a74b5c3a6411ead219b
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
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.clamp.controlloop.participant.simulator.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 import javax.ws.rs.core.Response;
29 import lombok.Getter;
30 import lombok.Setter;
31 import org.apache.commons.cli.CommandLine;
32 import org.apache.commons.cli.DefaultParser;
33 import org.apache.commons.cli.HelpFormatter;
34 import org.apache.commons.cli.Option;
35 import org.apache.commons.cli.Options;
36 import org.apache.commons.cli.ParseException;
37 import org.apache.commons.lang3.StringUtils;
38 import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException;
39 import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException;
40 import org.onap.policy.common.utils.resources.ResourceUtils;
41
42 /**
43  * This class reads and handles command line parameters for the participant simulator service.
44  *
45  */
46 public class ParticipantSimulatorCommandLineArguments {
47     private static final String FILE_MESSAGE_PREAMBLE = " file \"";
48     private static final int HELP_LINE_LENGTH = 120;
49
50     private final Options options;
51     @Getter()
52     @Setter()
53     private String configurationFilePath = null;
54
55     /**
56      * Construct the options for the participant component.
57      */
58     public ParticipantSimulatorCommandLineArguments() {
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 participant")
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 participant parameters")
77                 .hasArg()
78                 .argName("CONFIG_FILE")
79                 .required(false)
80                 .type(String.class)
81                 .build());
82         //@formatter:on
83     }
84
85     /**
86      * Construct the options for the participant component and parse in the given arguments.
87      *
88      * @param args The command line arguments
89      */
90     public ParticipantSimulatorCommandLineArguments(final String[] args) {
91         // Set up the options with the default constructor
92         this();
93
94         // Parse the arguments
95         try {
96             parse(args);
97         } catch (final ControlLoopException e) {
98             throw new ControlLoopRuntimeException(Response.Status.NOT_ACCEPTABLE,
99                     "parse error on participant parameters", e);
100         }
101     }
102
103     /**
104      * Parse the command line options.
105      *
106      * @param args The command line arguments
107      * @return a string with a message for help and version, or null if there is no message
108      * @throws ControlLoopException on command argument errors
109      */
110     public String parse(final String[] args) throws ControlLoopException {
111         // Clear all our arguments
112         setConfigurationFilePath(null);
113
114         CommandLine commandLine = null;
115         try {
116             commandLine = new DefaultParser().parse(options, args);
117         } catch (final ParseException e) {
118             throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE,
119                     "invalid command line arguments specified : " + e.getMessage());
120         }
121
122         // Arguments left over after Commons CLI does its stuff
123         final String[] remainingArgs = commandLine.getArgs();
124
125         if (remainingArgs.length > 0) {
126             throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE,
127                     "too many command line arguments specified : " + Arrays.toString(args));
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 ControlLoopException on command argument validation errors
149      */
150     public void validate() throws ControlLoopException {
151         validateReadableFile("participant configuration", configurationFilePath);
152     }
153
154     /**
155      * Print version information for participant.
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 participant.
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 full expanded configuration file path.
182      *
183      * @return the configuration file path
184      */
185     public String getFullConfigurationFilePath() {
186         return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
187     }
188
189     /**
190      * Check set configuration file path.
191      *
192      * @return true, if check set configuration file path
193      */
194     public boolean checkSetConfigurationFilePath() {
195         return !StringUtils.isEmpty(configurationFilePath);
196     }
197
198     /**
199      * Validate readable file.
200      *
201      * @param fileTag the file tag
202      * @param fileName the file name
203      * @throws ControlLoopException on the file name passed as a parameter
204      */
205     private void validateReadableFile(final String fileTag, final String fileName) throws ControlLoopException {
206         if (StringUtils.isEmpty(fileName)) {
207             throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE,
208                     fileTag + " file was not specified as an argument");
209         }
210
211         // The file name refers to a resource on the local file system
212         final URL fileUrl = ResourceUtils.getUrl4Resource(fileName);
213         if (fileUrl == null) {
214             throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE,
215                     fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
216         }
217
218         final File theFile = new File(fileUrl.getPath());
219         if (!theFile.exists()) {
220             throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE,
221                     fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
222         }
223         if (!theFile.isFile()) {
224             throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE,
225                     fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file");
226         }
227         if (!theFile.canRead()) {
228             throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE,
229                     fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable");
230         }
231     }
232 }