org.apache.commons.cli.BasicParser Example
Basic Parser
is for Command Line Processing. Command Line Processing has three stages definition, parsing and interrogation. Options are defined for command line processing. Command Line interface uses the options class as a container for option instances. To create options, there are two ways. The constructors and factory methods defined in options are the two methods of creating optios.
Definition stage defines the options instance. The parsing stage parses the options and the result is command line instance. Interrogation stage is using the options for application data.
1. Source Code Example
The example below has the options created for the basic parser to parse and process them as application data.
BasicParserExample.java:
package com.architectcorner.cli.parsing; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; /** * @author Bhagvan Kommadi * Basic Parser example for parsing application data arguments */ public class BasicParserExample extends BasicParser{ /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BasicParserExample exampleParser = new BasicParserExample(); Options options = new Options() .addOption("a", "enable-a", false, "turn on or off") .addOption("b", "bfile", true, "set the value of [b]") .addOption("c", "copt", false, "turn on or off"); String[] parserArgs = new String[] { "-a", "-b", "toast", "foo", "bar" }; try { CommandLine commandLine = exampleParser.parse(options,parserArgs); System.out.println(commandLine.getOptionValue("b")); } catch(ParseException parseException) { System.out.println("Exception "+parseException.getMessage()); } } @Override /** * flatten the options and arguments string * @param arg0 options * @param arg1 argument string * @param arg2 boolean flag * @return string array of flattened arguments */ protected String[] flatten(Options arg0, String[] arg1, boolean arg2) { // TODO Auto-generated method stub return super.flatten(arg0,arg1,arg2); }
Basic parser
can be used to define application data options and can be parsed for application data processing.Conclusion
Basic Parser
is defined extending the Parser
class and can be used for command line interface processing.
You can download the source code of the example here: BasicParserExample.zip