Apache Commons CLI Tutorial
Apache Commons CLI Tutorial
The Apache Commons CLI are the components of the Apache Commons which are derived from Java
API and provides an API to parse command line arguments/options which are passed to the
programs. This API also enables to print the help related to options available. This tutorial covers
most of the topics required for a basic understanding of Apache Commons CLI and to get a feel of
how it works.
Audience
This tutorial has been prepared for the beginners to help them understand the basic to
advanced concepts related to the Apache Commons CLI.
Prerequisites
Before you start practicing various types of examples given in this reference, we assume that
you are already aware about computer programs and computer programming languages.
Command line processing comprises of three stages. These stages are explained below −
Definition Stage
Parsing Stage
Interrogation Stage
Definition Stage
In definition stage, we define the options that an application can take and act accordingly.
Commons CLI provides Options class, which is a container for Option objects.
// add a option
options.addOption("a", false, "add two numbers");
Here we have added an option flag a, while false as second parameter, signifies that option is
not mandatory and third parameter states the description of option.
Parsing Stage
In parsing stage, we parse the options passed using command line arguments after creating a
parser instance.
//Create a parser
CommandLineParser parser = new DefaultParser();
In Interrogation stage, we check if a particular option is present or not and then, process the
command accordingly.
If you are still willing to set up your environment for Java programming language, then this
chapter will guide you on how to download and set up Java on your machine. Please follow
the steps mentioned below to set up the environment.
Follow the instructions to download Java and run the .exe to install Java on your machine.
Once you have installed Java on your machine, you would need to set environment variables
to point to correct installation directories.
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=
%PATH%;C:\Program Files\java\jdk\bin'.
Environment variable PATH should be set to point, where the Java binaries have been
installed. Refer to your shell documentation, if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of
your '.bashrc: export PATH=/path/to/java:$PATH'
To write your Java programs, you need a text editor. There are many sophisticated IDEs
available in the market. But for now, you can consider one of the following −
Notepad − On Windows machine you can use any simple text editor like Notepad
(Recommended for this tutorial), TextPad.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded
from www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the eclipse open-source community and
can be downloaded from www.eclipse.org.
Download the latest version of Apache Common CLI jar file from commons-cli-1.4-bin.zip.
At the time of writing this tutorial, we have downloaded commons-cli-1.4-bin.zip and copied
it into C:\>Apache folder.
OS Archive name
Windows commons-cli-1.4-bin.zip
Linux commons-cli-1.4-bin.tar.gz
Mac commons-cli-1.4-bin.tar.gz
Set the APACHE_HOME environment variable to point to the base directory location
where, Apache jar is stored on your machine. Assume that we have extracted
commonscollections4-4.1-bin.zip in Apache folder on various Operating Systems as follows
−
OS Output
CLASSPATH Variable
Set the CLASSPATH environment variable to point to the Common CLI jar location.
Assume that you have stored commons-cli-1.4.jar in Apache folder on various Operating
Systems as follows −
OS Output
APACHE_HOME/commons-cli-1.4.jar:.
export CLASSPATH =
Mac
CLASSPATH:
APACHE_HOME/commons-cli-1.4.jar:.
Example
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
//***Definition Stage***
// create Options object
Options options = new Options();
//***Parsing Stage***
//Create a parser
CommandLineParser parser = new DefaultParser();
//***Interrogation Stage***
//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
System.out.println("Sum of the numbers: " + getSum(args));
} else if(cmd.hasOption("m")) {
System.out.println("Multiplication of the numbers: " +
getMultiplication(args));
}
}
public static int getSum(String[] args) {
int sum = 0;
for(int i = 1; i < args.length ; i++) {
sum += Integer.parseInt(args[i]);
}
return sum;
}
public static int getMultiplication(String[] args) {
int multiplication = 1;
for(int i = 1; i < args.length ; i++) {
multiplication *= Integer.parseInt(args[i]);
}
return multiplication;
}
}
Output
Run the file, while passing -a as option and numbers to get the sum of the numbers as result.
java CLITester -a 1 2 3 4 5
Sum of the numbers: 15
Run the file, while passing -m as option and numbers to get the multiplication of the numbers
as result.
java CLITester -m 1 2 3 4 5
Multiplication of the numbers: 120
CLITester.java
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
Run the file without passing any option and see the result.
java CLITester
12/11/2017
Run the file, while passing -t as option and see the result.
java CLITester
12/11/2017 4:13:10
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
options.addOption(logfile);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
Run the file, while passing --logFile as option, name of the file as value of the option and see
the result.
Example
CLITester.java
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
options.addOption(propertyOption);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("D")) {
Properties properties = cmd.getOptionProperties("D");
System.out.println("Class: " + properties.getProperty("class"));
System.out.println("Roll No: " +
properties.getProperty("rollNo"));
System.out.println("Name: " + properties.getProperty("name"));
}
}
}
Output
Run the file, while passing options as key value pairs and see the result.
Example
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
public class CLITester {
public static void main(String[] args) throws ParseException {
if( cmd.hasOption("D") ) {
System.out.println("D option was used.");
}
if( cmd.hasOption("A") ) {
System.out.println("A option was used.");
}
}
}
Output
Run the file while passing -D -A as options and see the result.
java CLITester -D -A
D option was used.
A option was used.
Run the file while passing --D as option and see the result.
Example
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
if( cmd.hasOption("p") ) {
System.out.println("p option was used.");
}
if( cmd.hasOption("g") ) {
System.out.println("g option was used.");
}
if( cmd.hasOption("n") ) {
System.out.println("Value passed: " + cmd.getOptionValue("n"));
}
}
}
Output
Run the file while passing -p -g -n 10 as option and see the result.
java CLITester -p -g -n 10
p option was used.
g option was used.
Value passed: 10
Example
CLITester.java
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
java CLITester
usage: CLITester
-g,--gui Show GUI Application
-n <arg> No. of copies to print
-p,--print Send print request to printer.
Example
CLITester.java
import java.io.PrintWriter;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
java CLITester
usage: CLITester [-g] [-n <arg>] [-p]