[JAVA] Analyze command line options with Apache's Commons CLI.

What is Apache Commons CLI?

An API that parses command line options.

For example, suppose you have three options when running hoge.jar. java -jar /usr/local/hoge.jar user age mail

And of these ・ User wants to take two options ・ I want to make age mandatory -If the option is incorrect, I want to return the specified option information (help).

The API that answers the request is Apache Commons CLI.

Try to introduce

I introduced it in the following environment. · Java 1.8 ・ Maven configuration

pom.xml


	<dependency>
	    <groupId>commons-cli</groupId>
	    <artifactId>commons-cli</artifactId>
	    <version>1.4</version>
	</dependency>

main.java



    	//Setting command line options
        Options options = new Options();

        //Setting method 1
        //Argument name(-t),Whether to get the argument,Description
        options.addOption("m", true, "mail address");

        //Setting method 2
        //Set options for each argument

        Options.addOption(Option.builder("u")     //Option name
        .argName("serviceid"))                    //Argument name
        .hasArg(2)                                //Takes two arguments.
        .desc("user")                          //Description
        .build());                                //Create an instance

        Options.addOption(Option.builder("a")
        .argName("age"))
        .required()                               //Mandatory
        .hasArg()
        .desc("age")
        .build());

        //Display optional help information.
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("[opts]", options);

        //Command line analysis
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        try {
			cmd = parser.parse(options, args);
		} catch (ParseException e) {
			log.error("cmd parser failed." , e);
		}

        //user
        cmd.hasOption("u");
		log.info("user["+String.join(",", cmd.getOptionValues("u"))+"]");

		//age
        cmd.hasOption("a");
		log.info("age["+String.join(",", cmd.getOptionValues("a"))+"]");

		//mail address
		cmd.hasOption("m");
		log.info("mail address["+String.join(",", cmd.getOptionValues("m"))+"]");

Try running it with the following arguments. -a 18 -u edy jeff -m [email protected]

console.log


usage: [opts]
 -a <age>age
 -m <arg>mail address
 -u <user>user
INFO App -user[edy,jeff](App.java:67)
INFO App -age[18](App.java:71)
INFO App -mail address[[email protected]](App.java:75)

Option information is also displayed, and you can see that the specified arguments have been acquired.

By the way, if you remove the age of the required items

console.log


usage: [opts]
 -a <age>age
 -m <arg>mail address
 -u <user>user
ERROR App - cmd parser failed. (App.java:62)
org.apache.commons.cli.MissingOptionException: Missing required option: a
	at org.apache.commons.cli.DefaultParser.checkRequiredOptions(DefaultParser.java:199)
	at org.apache.commons.cli.DefaultParser.parse(DefaultParser.java:130)
	at org.apache.commons.cli.DefaultParser.parse(DefaultParser.java:76)
	at org.apache.commons.cli.DefaultParser.parse(DefaultParser.java:60)
	at free_dom.test.App.main(App.java:60)
Exception in thread "main" java.lang.NullPointerException
	at free_dom.test.App.main(App.java:66)

It outputs that there is no "a" option.

I wanted an API like this when creating a batch, so I'll try using it next time. It's new, but (* ´Д `)

20190218 Addendum

Using OptionBuilder has been deprecated since Commons CLI 1.3. For this reason, the source part has also been modified.

OptionBuilder.withArgName("user").
              hasArgs(2).
              withDescription("user").
              create("u");

Use Option.builder instead.

Option.builder("u")
      .argName("user"))
      .hasArgs(2)
      .desc("user")
      .build()

Recommended Posts

Analyze command line options with Apache's Commons CLI.
Create command line app with maven