Catalog alignment
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / cli / CLITool.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.asdctool.cli;
22
23 import org.apache.commons.cli.CommandLine;
24 import org.apache.commons.cli.CommandLineParser;
25 import org.apache.commons.cli.DefaultParser;
26 import org.apache.commons.cli.HelpFormatter;
27 import org.apache.commons.cli.Options;
28 import org.apache.commons.cli.ParseException;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * abstract base class to extend when implementing a cli tool
34  */
35 public abstract class CLITool {
36
37     private static final Logger LOGGER = LoggerFactory.getLogger(CLITool.class);
38
39     public CLIToolData init(String[] args) {
40         CommandLine commandLine = initCmdLineOptions(args);
41         return new CLIToolData(commandLine);
42     }
43
44     private CommandLine initCmdLineOptions(String[] args) {
45         Options options = buildCmdLineOptions();
46         CommandLineParser parser = new DefaultParser();
47         try {
48             return parser.parse( options, args );
49         }
50         catch( ParseException exp ) {
51             LOGGER.error("Parsing failed.  Reason: " + exp.getMessage() );
52             usageAndExit(options);
53             return null;
54         }
55     }
56
57     private void usageAndExit(Options options) {
58         HelpFormatter formatter = new HelpFormatter();
59         formatter.printHelp(commandName(), options );
60         System.exit(1);
61     }
62
63     /**
64      *
65      * @return all command line options required by this command line tool
66      */
67     protected abstract Options buildCmdLineOptions();
68
69     /**
70      *
71      * @return the command name
72      */
73     protected abstract String commandName();
74
75
76 }