JAVA library to simplify development of command line utility

/
0 Comments



Recently I had to write a stand-alone command line utility using Java. While writing that utility, the most tedious task was to parse and validate command line argument. Imagine you have n number of argument to take via command line and imagine the code that one need to write for parsing and validating these arguments manually. But why to reinvent the wheel when you have some reliable open source library available to do it for you. In this post, I will cover Apache Commons CLI library.

Using the library:

You can pick the latest version of the library from here. For this tutorial, we will be using 1.3.1 version which is the latest version as per current date.

You can add dependency of commons CLI library depending upon your preferred build tool.

In this tutorial, we will create a command line utility of a basic calculator just for simplicity.

I am using Gradle as a build tool and my build.gradle file will look like this:



We will also add settings.gradle file to specify my jar name:



Moving on to actual code. The code is pretty straight-forward and self-explanatory: 



With these codes I will build my fat-jar using the following command:

gradle build

After a successful run of above command I can find my calculator utility jar ready in build\libs directory with name calculator-1.0.jar.

This utility expects three command line arguments as follows:

-o1 : first operand, must be number
-o2 : second operand, must be number
-op : operator, must be one of these: +,-,*,/

To see the usage instructions of this jar we can simply run the jar without any argument and it will show the usage:



>java -jar build\libs\calculator-1.0.jar
usage: calculator-<version>.jar
 -o1,--first-operand <arg>    First operand: Must be a number
 -o2,--second-operand <arg>   Second operand: Must be a number

 -op,--operator <arg>         operator: must be one of these -> +,-,*,/

Now since we know the usage let us try to run jar with proper input:

>java -jar build\libs\calculator-1.0.jar -o1 3.1 -o2 3.4 -op +
Result: 6.5

and we got the correct result.

Let's try with incorrect argument value. Notice that we are passing string 'abc' as first operand:



>java -jar build\libs\calculator-1.0.jar -o1 abc -o2 3.4 -op +
usage: calculator-<version>.jar
 -o1,--first-operand <arg>    First operand: Must be a number
 -o2,--second-operand <arg>   Second operand: Must be a number
 -op,--operator <arg>         operator: must be one of these -> +,-,*,/


and utility is showing usage info again since provided input is incorrect.

Similarly for other incorrect arguments also the utility will show usage information.

You can find complete code with build files here.





You may also like

Popular Posts