Apache Commons CLI Development Command-line tool example

Source: Internet
Author: User

Concept Description
Apache Commons CLI Introduction

Despite the rapid development of various human-computer interaction technologies, the most traditional command-line pattern is still widely used in various fields: from compiling code to system administration, the command line is favored by its simplicity and efficiency. Various tools and systems provide a detailed user manual, and some provide examples of how to develop it two times. However, there are few articles on how to develop an easy-to-use, robust command-line tool. This article combines the Apache Commons CLI with a complete example showing how to prepare, develop, and test a command-line tool. I hope this article will be helpful to readers with relevant needs.
Apache Commons CLI.

Apache Commons CLI is a toolkit for parsing command line input below Apache, which also provides the ability to automatically generate output help documents.

The Apache Commons CLI supports a variety of input parameter formats, with the following main supported formats:

The form of a parameter in POSIX (portable Operating System Interface of Unix), such as TAR-ZXVF foo.tar.gz

Long parameter forms in GNU, such as Du--human-readable--max-depth=1

The form of a parameter in a Java command, such as Java-djava.net.usesystemproxies=true Foo

Short bar Parameter form with parameter value, for example Gcc-o2 foo.c

The Long bar parameter does not take the form of a parameter value, such as Ant–projecthelp

CLI Command Code implementation
Typically, command-line processing has three steps: Define, parse, and interrogate phases. This chapter will explain these three steps in turn, and will combine examples to discuss how to implement them through the Apache Commons CLI.
The command-line process is relatively straightforward, and the main process is to use the input data for logical processing, such as setting command line parameters, parsing input parameters

CLI definition Phase

Each command line must define a set of parameters that are used to define the interface of the application. The Apache Commons CLI uses the Options class to define and set parameters, which are containers for all Option instances. In the CLI, there are currently two ways to create options, one through constructors, which is the most common and most familiar way, and the other is achieved through the factory approach defined in the options.

The goal result of the CLI definition phase is to create an Options instance.

Create an Options object
Options options = new options ();

Add-H parameter
Options.addoption ("H", false, "Lists short");

Add-t parameter
Options.addoption ("T", true, "sets the HTTP communication protocol for CIM Connection");

where the AddOption () method has three parameters, the first parameter sets the option's single-character name, the second parameter indicates whether the option needs to enter a value, and the third argument is a brief description of the option. In this code snippet, the first parameter simply lists the help file, does not require the user to enter any values, and the second parameter is the communication protocol that requires the user to enter HTTP, so the second parameter of the two option is false and true

CLI parsing phase

In the parsing phase, the text of the application is passed through the command line for processing. The process will be based on the rules defined during the parser implementation. The parse method defined in the Commandlineparser class will use the Options instance and a set of strings produced in the CLI definition phase as input and return the CommandLine generated after parsing.

The goal result of the CLI parsing phase is to create the CommandLine instance.

Commandlineparser parser = new Posixparser ();
CommandLine cmd = parser.parse (options, args);

if (Cmd.hasoption ("H")) {
A brief help message is displayed here
}

CLI Inquiry Phase

During the Ask phase, the application determines which branch of the program needs to be executed by querying the CommandLine and through the Boolean parameters and the parameter values provided to the application. This phase is implemented in the user's code, and the access method in CommandLine provides the CLI with the ability to interrogate the user code.

The goal result of the CLI inquiry phase is to pass all the text information that is obtained through the command line and processing parameters to the user's code.

CommandLine = Parser.parse (options, args);
if (commandline.hasoption (' h ')) {
Print Use Help
Hf.printhelp ("Test", options, true);
}

code example

ImportOrg.apache.commons.cli.CommandLine;ImportOrg.apache.commons.cli.CommandLineParser;ImportOrg.apache.commons.cli.HelpFormatter;Importorg.apache.commons.cli.Option;Importorg.apache.commons.cli.Options;Importorg.apache.commons.cli.ParseException;ImportOrg.apache.commons.cli.DefaultParser;/*** datetime:2016 Year May 1 afternoon 5:07:31 **/ Public classTest { Public Static voidMain (string[] args) {string[] arg= {"-H", "-C", "Config!" };    Testoptions (ARG); }     Public Static voidtestoptions (string[] args) {Options options=NewOptions (); Option opt=NewOption ("H", "Help",false, "Print Help"); Opt.setrequired (false);        Options.addoption (opt); Opt=NewOption ("C", "ConfigFile",true, "Name Server Config Properties file"); Opt.setrequired (false);        Options.addoption (opt); Opt=NewOption ("P", "Printconfigitem",false, "Print all config item"); Opt.setrequired (false);        Options.addoption (opt); Helpformatter HF=NewHelpformatter (); Hf.setwidth (110); CommandLine CommandLine=NULL; Commandlineparser Parser=NewDefaultparser (); Try{commandLine=parser.parse (options, args); if(Commandline.hasoption (' H ')) {                //Print Use HelpHf.printhelp ("Test", Options,true); }            //print the name and value of the OPTsSystem.out.println ("--------------------------------------"); Option[] OPTs=commandline.getoptions (); if(OPTs! =NULL) {                 for(Option opt1:opts) {String name=opt1.getlongopt (); String value=Commandline.getoptionvalue (name); SYSTEM.OUT.PRINTLN (Name+ "= +" +value); }            }        }        Catch(ParseException e) {hf.printhelp ("Test", Options,true); }    }}
View Code

Apache Commons CLI Development Command-line tool example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.