Sunday, October 12, 2014

Apache Commons CLI - A Simple Example

As the saying goes " Out of Sight, Out of Mind", I was unable to remember how often I had used the Apache Commons CLI API in my Developer days. Now that I mostly work on Security engagements, when I was reminding one of our Consultants to use command line options, I couldn't remember the name of Commons CLI.

As soon as I got back home from the client site, I fired up my laptop, and there it was the code written almost several years back which used the Apache Commons CLI API.

The best way to get access to these code examples is to blog here, and you have it handy anywhere in the world, right?

The Commons CLI has great documentation on its website. Take a look:

Follow the steps below to get it up and running in a few mins:

1. Download Commons CLI from here:

2. Create a simple Main class:

3. As seen in the above screen shot, use the org.apache.commons.cli.Options to specify the command line options. For mandatory options, use the .isRequired().

4. Add descriptions to each command line option.

5. Next, parse command line input with set options as shown below:

6. Finally, get the individual command line options using the CommandLine object. For the ones which are optional, check if the argument is available using the .hasOption method.

7. Now run the jar file from the command line and you are all set. If an an option which is required is not set, it will print the help message as shown below:

8. If all the required options are specified, you see a message as such:

That's all it is for using the Apache Commons CLI. Happy Coding.