John Keyes Usage Scenario's

The following sections describe some example scenarios on how to use CLI in applications.

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 true, otherwise the value is false.

The DateApp utility prints the current date to standard output. If the -t option is present the current time is also printed.

An Options object must be created and the t Option must be added to it.

// create Options object Options options = new Options(); // add t option options.addOption('t', false, "display current time");

The addOption method has three parameters. The first parameter is a char that represents the option. The second paramter is a boolean that specifies whether the option requires an argument or not. In the case of a boolean option (sometimes referred to as a flag) an argument value is not present so it false is passed. The third parameter is the description of the option. This description will be used in the usage text of the application.

The parse methods of Options are used to parse the command line arguments.

CommandLine cmd = options.parse(args);

Now we need to check if the t option is present. To do this we will interrogate the CommandLine object. The hasOption method takes a char parameter and returns true if the option represented by the char is present, otherwise it returns false.

if(cmd.hasOption('t')) { // print the date and time } else { // print the date }

The InternationalDateApp utility extends the DateApp utility by providing the ability to print the date and time in any country in the world. To facilitate this a new command line option, c, has been introduced.

// add c option options.addOption('c', true, "country code");

The second parameter is true this time. This specifies that the c option requires an argument value. If the required option argument value is specified on the command line it is returned, otherwise null is returned.

The getOptionValue methods of Options are used to retrieve the argument values of options.

// get c option value String countryCode = options.getOptionValue('c'); if(countryCode == null) { // print default date } else { // print date for country specified by countryCode }