bcds.tools
Class ArgsParser

java.lang.Object
  extended by bcds.tools.ArgsParser

public class ArgsParser
extends java.lang.Object

ArgsParser facilitates the processing of command-line arguments. The following code snipped illustrates the basic usage. opts is a simple array containing pairs of entries, the first one giving the name of the option, and the second a descrption. For example:

    String [] opts = {"-debug",  "enables debugging messages"
                      ,"outfile", "name of the output file"
                      ,"anotheropt", "some description here"
                     };
    try {
       ArgsParser pa = new ArgsParser(opts, argv);
       ...
       int deb = pa.getStr("debug", 0);
       ...
 
This can be run with:
   $ java MyProg --debug --outfile somefile.txt -anotheropt=123 infile.txt
 

Options start with "-" or "--" and can have arguments or "values". An argument is separated from its option by an equal sign or may appear as the next entry in argv.

If an option appears more than once in argv, an ArgsParserException is thrown with code NON_UNIQUE_OPTION. If an unregistered option is found in argv an ArgsParserException is thrown with code UNREGISTERED_OPTIONS. This behaviour can be changed by calling ignoreUnregisteredOptions(boolean).

Arguments can also be read from one or more files by giving @filename. Comments in the file start with #. Options may appear one-per-line or several-per-line separated by whitepsaces. Double quotes are removed.

Note also that "single letter combined options" are NOT supported, i.e., if -abc is given, that means "-abc", not -a -b -c.

The marker -- can be used to signal the end of the options. The remaining entries will be treated as non-option arguments.

The non-option arguments, either appearing at the end of the options or in the middle of the sequence, can be obtained with getExtraArgs().

The various getXXX() methods require an id as their first argument. This id MUST not include the leading "-", that is, use getBool("debug", ...) not getBool("-debug", ...).

A complete functional example: TestArgsParser.java

   import java.util.Set;
   
   import bcds.tools.ArgsParser;
   import bcds.tools.ArgsParserException;
   
   /**
    * A complete (but ficticious) example that uses ArgsParser.
    */
   public class TestArgsParser
   {
      enum Options
      {
         SHOW_GUI,
         ENABLE_3D_EFFECTS,
         QUIT_ON_CLOSE
      }

      void parseArgs(String [] args) 
      {
         String [] opts =
            {"-h",     "help",
             "-debug", "Show debugging messages",
             "extra",    "Options. Default: none. One or more of:\n\t"
                       + ArgsParser.enumValues(Options.class),
             "rep",    "Number of repetitions. Default=40",
             "tunit",  "Time unit to use. Default=seconds. Choose one of:\n\t"
                       + ArgsParser.enumValues(TimeUnit.class)
            };

         String usage = null;

         try {
            ArgsParser pa = new ArgsParser(opts, args);
            usage = "Usage:\nTestArgsParser [options] file..."
                  +"\nwhere options:\n" + pa.usage("  ");

            if ( pa.getBool("h", false) == true ) {
               System.out.println("\n\n" + usage);
               System.exit(0);
            }

            // Enable this to test the generation of a runtime exception 
            // (internal error because option does not exist):
            // boolean wrong = pa.getBool("xyz", false);

            opt_enable_debug = pa.getBool("debug", false);
            opt_num_rep = pa.getInt("rep", 40);

            opt_extra = pa.getEnumSet("extra", Options.class, null);

            opt_time_unit = pa.getEnum("tunit", TimeUnit.class, TimeUnit.SECONDS);
            opt_files = pa.getExtraArgs();

            // Check presence of non-option parameters.
            if ( opt_files == null )
               pa.raiseBadUsage("At least one filename is required.");

         } catch (ArgsParserException ex) {
            System.err.printf("\nERROR: %s\n", ex.getMessage());
            if ( ex.isBadUsage() )
               System.err.println(usage);

            System.exit(1);
         }
      }


      // These hold the options received from the command line
      // and are populated in parseArgs().

      boolean opt_enable_debug;
      int opt_num_rep;
      TimeUnit opt_time_unit;
      Set<Options> opt_extra;
      String [] opt_files;


      public static void main(String [] args)
      {
         TestArgsParser t = new TestArgsParser();

         t.parseArgs(args);

         System.out.println("\nNon-option parameters: " 
               +java.util.Arrays.asList(t.opt_files));

         System.out.println("\ndebug=" + t.opt_enable_debug
            +"\nrep=" + t.opt_num_rep
            +"\nextra=" + t.opt_extra
            +"\ntunit=" + t.opt_time_unit);

         if ( t.opt_extra.contains(Options.SHOW_GUI) )
            System.out.print("\nGUI is requested");

         System.out.println();
      }
   }
 

Author:
Juan Segovia S.

Constructor Summary
ArgsParser(java.lang.String[] opts, java.lang.String[] args)
          Creates a new instance.
 
Method Summary
static
<T extends java.lang.Enum>
java.lang.String
enumValues(java.lang.Class<T> enum_class)
          A convenience function that returns the elements of an enumeration class as a string.
 boolean getBool(java.lang.String id, boolean defval)
          Returns an option's boolean value represented as an integer (if present) or the value given in defval otherwise.
 double getDouble(java.lang.String id, double defval)
          Returns an option's argument as a double (if present) or the value given in defval otherwise.
<T extends java.lang.Enum<? super T>>
T
getEnum(java.lang.String id, java.lang.Class<T> enum_class, T defval)
          Returns the enumeration corresponding an option's argument.
<T extends java.lang.Enum>
java.util.Set<T>
getEnumSet(java.lang.String id, java.lang.Class<T> enum_class)
          Collects the items of an option's argument into a set.
<T extends java.lang.Enum>
java.util.Set<T>
getEnumSet(java.lang.String id, java.lang.Class<T> enum_class, T defval)
          Returns the set of values found, or a set with defval as its only value if no value exists for id.
 java.lang.String[] getExtraArgs()
          Returns the non-option parameters, or null if no non-option parameter exists in argv.
 int getInt(java.lang.String id, int defval)
          Returns an option's argument as an integer, if present, or the value given in defval otherwise.
 java.lang.String getStr(java.lang.String id, java.lang.String defval)
          Returns an option's argument as a string, if present, or the value given in defval otherwise.
 void ignoreUnregisteredOptions(boolean ignore)
          Establishes whether unregistered options found should raise an exception.
static void raise(ArgsParserException.ErrorCode err, java.lang.String msg)
          Throws an exception with the given error code and message.
static void raise(ArgsParserException.ErrorCode err, java.lang.String fmt, java.lang.Object... msg)
          Throws an exception with the given error code and message.
static void raise(java.lang.String fmt, java.lang.Object... msg)
          Throws an exception with error code GENERIC.
static void raiseBadUsage(java.lang.String fmt, java.lang.Object... msg)
          Throws and exception with error code BAD_USAGE and and the given message.
 java.util.List<java.lang.String> readArgsFromFile(java.lang.String fname)
          Reads command-line like arguments from the file fname.
static java.lang.String[] toArgsArray(java.lang.String z, java.lang.String prepend)
          Converts a comma-separated list of key=value pairs into an "args" style array.
 java.lang.String usage(java.lang.String indent)
          Builds a string that can be used to display a "usage" message.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ArgsParser

public ArgsParser(java.lang.String[] opts,
                  java.lang.String[] args)
           throws ArgsParserException
Creates a new instance. The list of the "option specifiers" (opts) and the actual arguments (argv) are cheched and copied for internal use.

Parameters:
opts - the list of acceptable options. If an option begins with an minus sign (-), it is assumed to be boolean. Its value/presence must be obtained with getBool(String, boolean).
args - The actual list of arguments supplied by the user. Generally, it will be main()'s argv.
Throws:
ArgsParserException - with error code GENERIC if: a) an option specifier is empty ("") or is just "-" or "--"; b) opts is null or opts.length is not even; c) an option appears more than once in opts.
Method Detail

ignoreUnregisteredOptions

public void ignoreUnregisteredOptions(boolean ignore)
Establishes whether unregistered options found should raise an exception. By default, an exception is raised as soon as one such case is found during the first getXXX.

Note that when ignoreUnregisteredOptions(true) and option "abc" was not registered, getXXX("abc") throws ArgsParserException with error code BAD_OPTION_ID.


getStr

public java.lang.String getStr(java.lang.String id,
                               java.lang.String defval)
                        throws ArgsParserException
Returns an option's argument as a string, if present, or the value given in defval otherwise.

Parameters:
id - the option identifier as given to the constructor.
defval - the value to be returned if id is not present.
Returns:
The option's argument, trimmed.
Throws:
ArgsParserException - with error code BAD_OPTION_ID if the option requested was not given at instantiation time.

getInt

public int getInt(java.lang.String id,
                  int defval)
           throws ArgsParserException
Returns an option's argument as an integer, if present, or the value given in defval otherwise.

Parameters:
id - the option identifier as given to the constructor.
defval - the value to be returned if id is not present in args (2nd parameter to ArgsParser(String[], String[])).
Returns:
The argument or defval.
Throws:
ArgsParserdException - with error code BAD_OPTION if the option requested was not given at instantiation time.
ArgsParserException - with error code BAD_VALUE if the option's argument cannot be converted to integer by Integer.ParseInt().

getDouble

public double getDouble(java.lang.String id,
                        double defval)
                 throws ArgsParserException
Returns an option's argument as a double (if present) or the value given in defval otherwise.

Throws:
ArgsParserException
See Also:
getInt(String, int)

getBool

public boolean getBool(java.lang.String id,
                       boolean defval)
                throws ArgsParserException
Returns an option's boolean value represented as an integer (if present) or the value given in defval otherwise. The value given in argv can be one of: "true", "false", "yes", "no", "1", "0".

Throws:
ArgsParserException - with error code GENERIC if id was not identified as boolean ("-option"). For other exceptions, see getInt(String, int).
See Also:
getInt(String, int)

getEnum

public <T extends java.lang.Enum<? super T>> T getEnum(java.lang.String id,
                                                       java.lang.Class<T> enum_class,
                                                       T defval)
                                            throws ArgsParserException
Returns the enumeration corresponding an option's argument. The comparison of the given argument(s) with the members of the enumeration is performed in lowercase, so the user can give arguments in any "case". NOTE: Comparing values in lowercase means that enumeration members SHOULD be unique in "case". This function will return the first member that matches.

Parameters:
id - the option identifier as given to the constructor.
enum_class - the Class identifying the the enumeration.
defval - the default value to return if id is not present.
Returns:
A reference to the enumeration value, or null if the option is not present in argv.
Throws:
ArgsParserException - with error code BAD_OPTION_ID if the option requested was not given at instantiation time.
ArgsParserException - with error code BAD_ENUM if the value given is not present in enum_class.
ArgsParserException - with error code GENERIC if enum_class does not reference an Enum class.

getEnumSet

public <T extends java.lang.Enum> java.util.Set<T> getEnumSet(java.lang.String id,
                                                              java.lang.Class<T> enum_class)
                                                   throws ArgsParserException
Collects the items of an option's argument into a set. This is a generalization of getEnum(java.lang.String, java.lang.Class, T). The multiple values must be separated by comma. Example:
   java MyProg --debug=this,that,andthat
 

Returns:
An new instance of java.util.HashSet, or null if the option is not present in argv.
Throws:
ArgsParserException
See Also:
getEnum(java.lang.String, java.lang.Class, T)

getEnumSet

public <T extends java.lang.Enum> java.util.Set<T> getEnumSet(java.lang.String id,
                                                              java.lang.Class<T> enum_class,
                                                              T defval)
                                                   throws ArgsParserException
Returns the set of values found, or a set with defval as its only value if no value exists for id. If defval is null, an empty set is return. So, it never returns null.

Throws:
ArgsParserException

getExtraArgs

public java.lang.String[] getExtraArgs()
Returns the non-option parameters, or null if no non-option parameter exists in argv.


usage

public java.lang.String usage(java.lang.String indent)
Builds a string that can be used to display a "usage" message. The order of appearance of the options given to ArgsParser(String [], String[]). is preserved. The "boolean indicator" (the - sign in -opt) is removed.

Parameters:
indent - a string to preprend to every option, generally used to "indent" the output.

enumValues

public static <T extends java.lang.Enum> java.lang.String enumValues(java.lang.Class<T> enum_class)
A convenience function that returns the elements of an enumeration class as a string.


toArgsArray

public static java.lang.String[] toArgsArray(java.lang.String z,
                                             java.lang.String prepend)
Converts a comma-separated list of key=value pairs into an "args" style array. The =value part is optional.

Parameters:
z - The string containing the values to split. Example: "name="Hello World",age=20,isStudent".
prepend - A string to prepend to each key so that for example "name" becomes "--name".

raise

public static void raise(ArgsParserException.ErrorCode err,
                         java.lang.String fmt,
                         java.lang.Object... msg)
                  throws ArgsParserException
Throws an exception with the given error code and message.

Throws:
ArgsParserException

raise

public static void raise(ArgsParserException.ErrorCode err,
                         java.lang.String msg)
                  throws ArgsParserException
Throws an exception with the given error code and message.

Throws:
ArgsParserException

raiseBadUsage

public static void raiseBadUsage(java.lang.String fmt,
                                 java.lang.Object... msg)
                          throws ArgsParserException
Throws and exception with error code BAD_USAGE and and the given message.

Throws:
ArgsParserException

raise

public static void raise(java.lang.String fmt,
                         java.lang.Object... msg)
                  throws ArgsParserException
Throws an exception with error code GENERIC. This is explicitly chosen so that isBadUsage() == false, which the caller may use to opt for not displaying usage message.

Throws:
ArgsParserException

readArgsFromFile

public java.util.List<java.lang.String> readArgsFromFile(java.lang.String fname)
                                                  throws ArgsParserException
Reads command-line like arguments from the file fname. The file is read through DataFileReader.

A ficticious example of a file containing command-line arguments is:

   # Enable debugging messages
   -debug
   # Other options
   -a -y -someotheroption="ABC"
   # Note that @file is not processed recursively. So this will
   # be treated as a non-option argument.
   @abc
 

Throws:
ArgsParserException - with error code FILE_IO if an IOException is thrown during the interaction with the file.