|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectbcds.tools.ArgsParser
public class ArgsParser
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(); } }
Constructor Summary | |
---|---|
ArgsParser(java.lang.String[] opts,
java.lang.String[] args)
Creates a new instance. |
Method Summary | ||
---|---|---|
static
|
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. |
|
|
getEnum(java.lang.String id,
java.lang.Class<T> enum_class,
T defval)
Returns the enumeration corresponding an option's argument. |
|
|
getEnumSet(java.lang.String id,
java.lang.Class<T> enum_class)
Collects the items of an option's argument into a set. |
|
|
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 |
---|
public ArgsParser(java.lang.String[] opts, java.lang.String[] args) throws ArgsParserException
opts
)
and the actual arguments (argv
) are cheched and copied
for internal use.
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.
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 |
---|
public void ignoreUnregisteredOptions(boolean ignore)
Note that when ignoreUnregisteredOptions(true) and option "abc" was not registered, getXXX("abc") throws ArgsParserException with error code BAD_OPTION_ID.
public java.lang.String getStr(java.lang.String id, java.lang.String defval) throws ArgsParserException
defval
otherwise.
id
- the option identifier as given to the constructor.defval
- the value to be returned if id is not present.
ArgsParserException
- with error code BAD_OPTION_ID
if the option requested
was not given at instantiation time.public int getInt(java.lang.String id, int defval) throws ArgsParserException
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[])
).
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().public double getDouble(java.lang.String id, double defval) throws ArgsParserException
ArgsParserException
getInt(String, int)
public boolean getBool(java.lang.String id, boolean defval) throws ArgsParserException
ArgsParserException
- with error code GENERIC if
id
was not identified
as boolean ("-option").
For other exceptions, see getInt(String, int)
.getInt(String, int)
public <T extends java.lang.Enum<? super T>> T getEnum(java.lang.String id, java.lang.Class<T> enum_class, T defval) throws ArgsParserException
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.
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.public <T extends java.lang.Enum> java.util.Set<T> getEnumSet(java.lang.String id, java.lang.Class<T> enum_class) throws ArgsParserException
getEnum(java.lang.String, java.lang.Class, T)
.
The multiple values must be separated by comma. Example:
java MyProg --debug=this,that,andthat
ArgsParserException
getEnum(java.lang.String, java.lang.Class, T)
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
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.
ArgsParserException
public java.lang.String[] getExtraArgs()
public java.lang.String usage(java.lang.String indent)
ArgsParser(String [], String[])
.
is preserved. The "boolean indicator" (the - sign in -opt) is
removed.
indent
- a string to preprend to every option, generally
used to "indent" the output.public static <T extends java.lang.Enum> java.lang.String enumValues(java.lang.Class<T> enum_class)
public static java.lang.String[] toArgsArray(java.lang.String z, java.lang.String prepend)
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".public static void raise(ArgsParserException.ErrorCode err, java.lang.String fmt, java.lang.Object... msg) throws ArgsParserException
ArgsParserException
public static void raise(ArgsParserException.ErrorCode err, java.lang.String msg) throws ArgsParserException
ArgsParserException
public static void raiseBadUsage(java.lang.String fmt, java.lang.Object... msg) throws ArgsParserException
ArgsParserException
public static void raise(java.lang.String fmt, java.lang.Object... msg) throws ArgsParserException
ArgsParserException
public java.util.List<java.lang.String> readArgsFromFile(java.lang.String fname) throws ArgsParserException
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
ArgsParserException
- with error code FILE_IO
if an IOException is
thrown during the interaction with the file.
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |