---
title: >-
  Command Line Argument Parsing for Groovy | Jarrod Roberson: Programming Missives
updated: 2019-02-26 12:14:26Z
created: 2019-02-26 12:05:41Z
tags:
  - IT
  - Development/Groovy
---



Groovy has some wrappers around the apache.commons.cli via their CLIBuilder class. This is a pretty old and crusty library that has some significant limitations. I prefer to use the Java Simple Argument Parser (JSAP) library. Especially since they have added the ability to declare argument definitions in a declarative XML file. This reduces the code footprint in your Groovy or Java program significantly. Normally I am adverse to XML configuration programming but in this case the syntax is very succinct and an appropriate use.

Here is a partial example of argument declarations for an example program that scans for open ports on a server.
```xml
<jsap>
    <parameters>
        <switch>
            <id>help</id>
		    <shortFlag>h</shortFlag>
		    <longFlag>help</longFlag>
		    <help>Display this help</help>
	    </switch>
		<flaggedOption>
			<id>host</id>
			<stringParser>
				<classname>StringStringParser</classname>
			</stringParser>
			<required>true</required>
			<shortFlag>h</shortFlag>
			<longFlag>host</longFlag>
			<help>Server to use to scan for open ports</help>
		</flaggedOption>
		<unflaggedOption>
			<id>ports</id>
			<stringParser>
				<classname>IntegerStringParser</classname>
			</stringParser>
			<greedy>true</greedy>
			<list>true</list>
			<listSeparator>,</listSeparator>
			<help>List of ports to scan on the server</help>
		</unflaggedOption>
	</parameters>
</jsap>
```
[jsap.xml](https://gist.github.com/jarrodhroberson/8995420#file-jsap-xml) hosted with ❤ by GitHub

 

Then you can use the following boilerplate code to initialize the parser and use it. Assuming the code is saved in file named “main.groovy” and the configuration file is named “main.jsap” and both are built into a .jar file called main.jar
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 	
```groovy
JSAP jsap = new JSAP(main.getResource("main.jsap"));
JSAPResult config = jsap.parse(args)
if (config.getBoolean("help") || !config.success())
{
println "Usage: java -jar main.jar " + jsap.usage
println ""
println jsap.help
if (!config.success())
{
for (e in config.getErrorMessageIterator())
{
println e
}
}
System.exit(0)
}
```
[main.groovy](https://gist.github.com/jarrodhroberson/8995431#file-main-groovy) hosted with ❤ by GitHub

That is basically all the code you need to easily and powerfully parse command line arguments in Groovy.
