Using Apache Commons CLIThe following sections describe some example scenarios on how to use CLI in applications. Using a boolean option
A boolean option is represented on a command line by the presence
of the option, i.e. if the option is found then the option value
is
The Creating the Options
An
Options object must be created and the // create Options object Options options = new Options(); // add t option options.addOption("t", false, "display current time");
The Parsing the command line arguments
The CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args);
Now we need to check if the if(cmd.hasOption("t")) { // print the date and time } else { // print the date }
final Options options = new Options(); options.addOption(new Option("d", "debug", false, "Turn on debug.")); options.addOption(new Option("e", "extract", false, "Turn on extract.")); options.addOption(new Option("o", "option", true, "Turn on option with argument.")); -de only matching the
"debug" option. We can consequently, now, turn this off and have
-de match both the debug option as well as the
extract option.
International Time
The // add c option options.addOption("c", true, "country code");
The second parameter is Retrieving the argument value
The // get c option value String countryCode = cmd.getOptionValue("c"); if(countryCode == null) { // print default date } else { // print date for country specified by countryCode } Using Ant as an Example
Ant will be used
here to illustrate how to create the ant [options] [target [target2 [target3] ...]] Options: -help print this message -projecthelp print project help information -version print the version information and exit -quiet be extra quiet -verbose be extra verbose -debug print debugging information -emacs produce logging information without adornments -logfile <file> use given file for log -logger <classname> the class which is to perform logging -listener <classname> add an instance of class as a project listener -buildfile <file> use given buildfile -D<property>=<value> use value for given property -find <file> search for buildfile towards the root of the filesystem and use it Defining Boolean Options
Lets create the boolean options for the application as they
are the easiest to create. For clarity the constructors for
Option help = new Option("help", "print this message"); Option projecthelp = new Option("projecthelp", "print project help information"); Option version = new Option("version", "print the version information and exit"); Option quiet = new Option("quiet", "be extra quiet"); Option verbose = new Option("verbose", "be extra verbose"); Option debug = new Option("debug", "print debugging information"); Option emacs = new Option("emacs", "produce logging information without adornments"); Defining Argument Options
The argument options are created using the Option logFile = Option.builder("logfile") .argName("file") .hasArg() .desc("use given file for log") .build(); Option logger = Option.builder("logger") .argName("classname") .hasArg() .desc("the class which it to perform logging") .build(); Option listener = Option.builder("listener") .argName("classname") .hasArg() .desc("add an instance of class as " + "a project listener") .build(); Option buildFile = Option.builder("buildfile") .argName("file") .hasArg() .desc("use given buildfile") .build(); Option find = Option.builder("find") .argName("file") .hasArg() .desc("search for buildfile towards the " + "root of the filesystem and use it") .build(); Defining Java Property OptionThe last option to create is the Java property, and it is also created using the Option class' Builder. Option property = Option property = Option.builder("D") .hasArgs() .valueSeparator('=') .build(); getOptionProperties("D") on the CommandLine .
Creating the Options
Now that we have created each
Option we need
to create the
Options
instance. This is achieved using the
addOption
method of Options options = new Options(); options.addOption(help); options.addOption(projecthelp); options.addOption(version); options.addOption(quiet); options.addOption(verbose); options.addOption(debug); options.addOption(emacs); options.addOption(logfile); options.addOption(logger); options.addOption(listener); options.addOption(buildfile); options.addOption(find); options.addOption(property); All the preparation is now complete, and we are now ready to parse the command line arguments. Creating the Parser
We now need to create a public static void main(String[] args) { // create the parser CommandLineParser parser = new DefaultParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } } Querying the commandline
To see if an option has been passed the // has the buildfile argument been passed? if (line.hasOption("buildfile")) { // initialise the member variable this.buildfile = line.getOptionValue("buildfile"); } Displaying Usage and HelpCLI also provides the means to automatically generate usage and help information. This is achieved with the HelpFormatter class. // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ant", options); When executed the following output is produced: usage: ant -D <property=value> use value for given property -buildfile <file> use given buildfile -debug print debugging information -emacs produce logging information without adornments -file <file> search for buildfile towards the root of the filesystem and use it -help print this message -listener <classname> add an instance of class as a project listener -logger <classname> the class which it to perform logging -projecthelp print project help information -quiet be extra quiet -verbose be extra verbose -version print the version information and exit
If you also require to have a usage statement printed
then calling Creating an ls Example
One of the most widely used command line applications in the *nix world
is Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuSUX nor --sort. -a, --all do not hide entries starting with . -A, --almost-all do not list implied . and .. -b, --escape print octal escapes for non-graphic characters --block-size=SIZE use SIZE-byte blocks -B, --ignore-backups do not list implied entries ending with ~ -c with -lt: sort by, and show, ctime (time of last modification of file status information) with -l: show ctime and sort by name otherwise: sort by ctime -C list entries by columns The following is the code that is used to create the Options for this example. // create the command line parser CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption("a", "all", false, "do not hide entries starting with ."); options.addOption("A", "almost-all", false, "do not list implied . and .."); options.addOption("b", "escape", false, "print octal escapes for non-graphic " + "characters"); options.addOption(Option.builder("SIZE").longOpt("block-size") .desc("use SIZE-byte blocks") .hasArg() .build()); options.addOption("B", "ignore-backups", false, "do not list implied entries " + "ending with ~"); options.addOption("c", false, "with -lt: sort by, and show, ctime (time of last " + "modification of file status information) with " + "-l:show ctime and sort by name otherwise: sort " + "by ctime"); options.addOption("C", false, "list entries by columns"); String[] args = new String[]{ "--block-size=10" }; try { // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption("block-size")) { // print the value of block-size System.out.println(line.getOptionValue("block-size")); } } catch (ParseException exp) { System.out.println("Unexpected exception:" + exp.getMessage()); } Converting (Parsing) Option Values
By in most cases the values on the command line are retrieved as Strings via the
public static void main(String[] args) { Option count = Option.builder("count") .hasArg() .desc("the number of things") .type(Integer.class) .build(); Options options = new Options().addOption(count); // create the parser CommandLineParser parser = new DefaultParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } try { Integer value = line.getParsedOptionValue(count); System.out.format("The value is %s%n", value ); } catch (ParseException e) { e.printStackTrace(); } } The value types natively supported by commons-cli are:
TypeHandler.register(Class<T> clazz, Converter<T> converter) .
The Class<T> can be any defined class. The converter is a function that takes a String argument and returns an instance of
the class. Any exception thrown by the constructor will be caught and reported as a ParseException
Conversions can be specified without using the Option fooOpt = Option.builder("foo") .hasArg() .desc("the foo arg") .converter(Foo::new) .build(); commandLine.getParsedOptionValue(fooOpt) is called.
Conversions that are added to the TypeHandler or that are specified directly will not deserialize if the option is serialized unless the type is registered with the TypeHandler before deserialization begins. Deprecating Options
Options may be marked as deprecated using ghe
The examples below will implement public static void main(String[] args) { Option n = Option.builder("n") .deprecated(DeprecatedAttributes.builder() .setDescription("Use '-count' instead") .setForRemoval(true) .setSince("now").get()) .hasArg() .desc("the number of things") .type(Integer.class) .build(); Option count = Option.builder("count") .hasArg() .desc("the number of things") .type(Integer.class) .build(); Options options = new Options().addOption(n).addOption(count); doSomething(options); } Changing Usage Announcement
The usage announcement may be changed by providing a
for example if void doSomething(Options options) { CommandLineParser parser = new DefaultParser(); CommandLine line; try { // parse the command line arguments line = parser.parse(options, new String[] {"-n", "5"}); System.out.println("n=" + line.getParsedOptionValue("n")); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } } The output of the run would be. Option 'n': Deprecated for removal since now: Use '-count' instead n=5
for example if void doSomething(Options options) { Consumer<Option> deprecatedUsageAnnouncement = o -> { final StringBuilder buf = new StringBuilder() .append("'") .append(o.getOpt()) .append("'"); if (o.getLongOpt() != null) { buf.append("'").append(o.getLongOpt()).append("'"); } System.err.printf("ERROR: Option %s: %s%n", buf, o.getDeprecated()); }; DefaultParser parser = DefaultParser.builder().setDeprecatedHandler(deprecatedUsageAnnouncement).build(); CommandLine line; try { // parse the command line arguments line = parser.parse(options, new String[] {"-n", "5"}); System.out.println("n=" + line.getParsedOptionValue("n")); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } } The output of the run would be. ERROR: Option 'n': Deprecated for removal since now: Use '-count' instead n=5 However, the first line would be printed on system err instead of system out. Changing help formatBy default the help formater prints "[Deprecated]" in front of the description for the option. This can be changed to display any values desired.
If void doSomething(Options options) { HelpFormatter formatter = HelpFormatter.builder().get(); formatter.printHelp("Command line syntax:", options); } usage: Command line syntax: -count <arg> the number of things -n <arg> [Deprecated] the number of things
The display of deprecated options may be changed through the use of the
doSomething to
void doSomething(Options options) { Function<Option, String> disp = option -> String.format("%s. %s", HelpFormatter.getDescription(option), option.getDeprecated().toString()); HelpFormatter formatter = HelpFormatter.builder().setShowDeprecated(disp).get(); formatter.printHelp("Command line syntax:", options); } usage: Command line syntax: -count <arg> the number of things -n <arg> the number of things. Deprecated for removal since now: Use '-count' instead |