Java Doc for ArgParser.java in  » Development » ArgParser » argparser » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Development » ArgParser » argparser 
Source Cross Reference  Class Diagram Java Document (Java Doc) 


java.lang.Object
   argparser.ArgParser

ArgParser
public class ArgParser (Code)
ArgParser is used to parse the command line arguments for a java application program. It provides a compact way to specify options and match them against command line arguments, with support for range checking, multiple option names (aliases), single word options, multiple values associated with an option, multiple option invocation, generating help information, custom argument parsing, and reading arguments from a file. The last feature is particularly useful and makes it easy to create ad-hoc configuration files for an application.

Basic Example

Here is a simple example in which an application has three command line options: -theta (followed by a floating point value), -file (followed by a string value), and -debug, which causes a boolean value to be set.

 static public void main (String[] args)
 {
 // create holder objects for storing results ...
 DoubleHolder theta = new DoubleHolder();
 StringHolder fileName = new StringHolder();
 BooleanHolder debug = new BooleanHolder();
 // create the parser and specify the allowed options ...
 ArgParser parser = new ArgParser("java argparser.SimpleExample");
 parser.addOption ("-theta %f #theta value (in degrees)", theta); 
 parser.addOption ("-file %s #name of the operating file", fileName);
 parser.addOption ("-debug %v #enables display of debugging info", debug);
 // match the arguments ...
 parser.matchAllArgs (args);
 // and print out the values
 System.out.println ("theta=" + theta.value);
 System.out.println ("fileName=" + fileName.value);
 System.out.println ("debug=" + debug.value);
 }
 

A command line specifying all three options might look like this:

 java argparser.SimpleExample -theta 7.8 -debug -file /ai/lloyd/bar 
 

The application creates an instance of ArgParser and then adds descriptions of the allowed options using ArgParser.addOption addOption . The method ArgParser.matchAllArgs(String[]) matchAllArgs is then used to match these options against the command line arguments. Values associated with each option are returned in the value field of special ``holder'' classes (e.g., argparser.DoubleHolder DoubleHolder , argparser.StringHolder StringHolder , etc.).

The first argument to ArgParser.addOption addOption is a string that specifies (1) the option's name, (2) a conversion code for its associated value (e.g., %f for floating point, %s for a string, %v for a boolean flag), and (3) an optional description (following the # character) which is used for generating help messages. The second argument is the holder object through which the value is returned. This may be either a type-specific object (such as argparser.DoubleHolder DoubleHolder or argparser.StringHolderStringHolder ), an array of the appropriate type, or an instance of java.util.Vector.

By default, arguments that don't match the specified options, are out of range, or are otherwise formatted incorrectly, will cause matchAllArgs to print a message and exit the program. Alternatively, an application can use ArgParser.matchAllArgs(String[],int,int) matchAllArgs(args,idx,exitFlags) to obtain an array of unmatched arguments which can then be processed separately

Range Specification

The values associated with options can also be given range specifications. A range specification appears in curly braces immediately following the conversion code. In the code fragment below, we show how to specify an option -name that expects to be provided with one of three string values (john, mary, or jane), an option -index that expects to be supplied with a integer value in the range 1 to 256, an option -size that expects to be supplied with integer values of either 1, 2, 4, 8, or 16, and an option -foo that expects to be supplied with floating point values in the ranges -99 < foo <= -50, or 50 <= foo < 99.
 StringHolder name = new StringHolder();
 IntHolder index = new IntHolder();
 IntHolder size = new IntHolder();
 DoubleHolder foo = new DoubleHolder();
 parser.addOption ("-name %s {john,mary,jane}", name);
 parser.addOption ("-index %d {[1,256]}", index);
 parser.addOption ("-size %d {1,2,4,8,16}", size);
 parser.addOption ("-foo %f {(-99,-50],[50,99)}", foo);
 
If an argument value does not lie within a specified range, an error is generated.

Multiple Option Names

An option may be given several names, or aliases, in the form of a comma seperated list:
 parser.addOption ("-v,--verbose %v #print lots of info");
 parser.addOption ("-of,-outfile,-outputFile %s #output file");
 

Single Word Options

Normally, options are assumed to be "multi-word", meaning that any associated value must follow the option as a separate argument string. For example,
 parser.addOption ("-file %s #file name");
 
will cause the parser to look for two strings in the argument list of the form
 -file someFileName
 
However, if there is no white space separting the option's name from it's conversion code, then values associated with that option will be assumed to be part of the same argument string as the option itself. For example,
 parser.addOption ("-file=%s #file name");
 
will cause the parser to look for a single string in the argument list of the form
 -file=someFileName
 
Such an option is called a "single word" option.

In cases where an option has multiple names, then this single word behavior is invoked if there is no white space between the last indicated name and the conversion code. However, previous names in the list will still be given multi-word behavior if there is white space between the name and the following comma. For example,

 parser.addOption ("-nb=,-number ,-n%d #number of blocks");
 
will cause the parser to look for one, two, and one word constructions of the forms
 -nb=N
 -number N
 -nN
 

Multiple Option Values

If may be useful for an option to be followed by several values. For instance, we might have an option -velocity which should be followed by three numbers denoting the x, y, and z components of a velocity vector. We can require multiple values for an option by placing a multiplier specification, of the form XN, where N is an integer, after the conversion code (or range specification, if present). For example,
 double[] pos = new double[3];
 addOption ("-position %fX3 #position of the object", pos);
 
will cause the parser to look for
 -position xx yy zz
 
in the argument list, where xx, yy, and zz are numbers. The values are stored in the array pos. Options requiring multiple values must use arrays to return their values, and cannot be used in single word format.

Multiple Option Invocation

Normally, if an option appears twice in the command list, the value associated with the second instance simply overwrites the value associated with the first instance. However, the application can instead arrange for the storage of all values associated with multiple option invocation, by supplying a instance of java.util.Vector to serve as the value holder. Then every time the option appears in the argument list, the parser will create a value holder of appropriate type, set it to the current value, and store the holder in the vector. For example, the construction
 Vector vec = new Vector(10);
 parser.addOption ("-foo %f", vec);
 parser.matchAllArgs(args);
 
when supplied with an argument list that contains
 -foo 1.2 -foo 1000 -foo -78
 
will create three instances of argparser.DoubleHolder DoubleHolder , initialized to 1.2, 1000, and -78, and store them in vec.

Generating help information

ArgParser automatically generates help information for the options, and this information may be printed in response to a help option, or may be queried by the application using ArgParser.getHelpMessage getHelpMessage . The information for each option consists of the option's name(s), it's required value(s), and an application-supplied description. Value information is generated automaticlly from the conversion code, range, and multiplier specifications (although this can be overriden, as described below). The application-supplied description is whatever appears in the specification string after the optional # character. The string returned by ArgParser.getHelpMessage getHelpMessage for the first example above would be
 Usage: java argparser.SimpleExample
 Options include:
 -help,-?                displays help information
 -theta <float>          theta value (in degrees)
 -file <string>          name of the operating file
 -debug                  enables display of debugging info
 
The options -help and -? are including in the parser by default as help options, and they automatically cause the help message to be printed. To exclude these options, one should use the constructor ArgParser.ArgParser(String,boolean)ArgParser(synopsis,false) . Help options can also be specified by the application using ArgParser.addOption addOption and the conversion code %h. Help options can be disabled using ArgParser.setHelpOptionsEnabledsetHelpOptionsEnabled(false) .

A description of the required values for an option can be specified explicitly by placing a second # character in the specification string. Everything between the first and second # characters then becomes the value description, and everything after the second # character becomes the option description. For example, if the -theta option above was specified with

 parser.addOption ("-theta %f #NUMBER#theta value (in degrees)",theta);
 
instead of
 parser.addOption ("-theta %f #theta value (in degrees)", theta);
 
then the corresponding entry in the help message would look like
 -theta NUMBER          theta value (in degrees)
 

Custom Argument Parsing

An application may find it necessary to handle arguments that don't fit into the framework of this class. There are a couple of ways to do this.

First, the method ArgParser.matchAllArgs(String[],int,int)matchAllArgs(args,idx,exitFlags) returns an array of all unmatched arguments, which can then be handled specially:

 String[] unmatched =
 parser.matchAllArgs (args, 0, parser.EXIT_ON_ERROR);
 for (int i = 0; i < unmatched.length; i++)
 { ... handle unmatched arguments ...
 }
 
For instance, this would be useful for an applicatoon that accepts an arbitrary number of input file names. The options can be parsed using matchAllArgs, and the remaining unmatched arguments give the file names.

If we need more control over the parsing, we can parse arguments one at a time using ArgParser.matchArg matchArg :

 int idx = 0;
 while (idx < args.length)
 { try
 { idx = parser.matchArg (args, idx);
 if (parser.getUnmatchedArgument() != null)
 {
 ... handle this unmatched argument ourselves ...
 }
 }
 catch (ArgParserException e) 
 { // malformed or erroneous argument
 parser.printErrorAndExit (e.getMessage());
 }
 }
 
ArgParser.matchArg matchArg(args,idx) matches one option at location idx in the argument list, and then returns the location value that should be used for the next match. If an argument does not match any option, ArgParser.getUnmatchedArgument getUnmatchedArgument will return a copy of the unmatched argument.

Reading Arguments From a File

The method ArgParser.prependArgs prependArgs can be used to automatically read in a set of arguments from a file and prepend them onto an existing argument list. Argument words correspond to white-space-delimited strings, and the file may contain the comment character # (which comments out everything to the end of the current line). A typical usage looks like this:
 ... create parser and add options ...
 args = parser.prependArgs (new File(".configFile"), args);
 parser.matchAllArgs (args);
 
This makes it easy to generate simple configuration files for an application.
author:
   John E. Lloyd, Fall 2004

Inner Class :static class NameDesc
Inner Class :static class RangePnt
Inner Class :class RangeAtom
Inner Class :class Record

Field Summary
public static  intEXIT_ON_ERROR
     Indicates that the program should exit with an appropriate message in the event of an erroneous or malformed argument.
public static  intEXIT_ON_UNMATCHED
     Indicates that the program should exit with an appropriate message in the event of an unmatched argument.
 RecorddefaultHelpOption
    
 StringerrMsg
    
 RecordfirstHelpOption
    
 inthelpIndent
    
 booleanhelpOptionsEnabled
    
 VectormatchList
    
 PrintStreamprintStream
    
 StringsynopsisString
    
 StringunmatchedArg
    
static  StringvalidConversionCodes
    

Constructor Summary
public  ArgParser(String synopsisString)
     Creates an ArgParser with a synopsis string, and the default help options -help and -?.
public  ArgParser(String synopsisString, boolean defaultHelp)
     Creates an ArgParser with a synopsis string.

Method Summary
public  voidaddOption(String spec, Object resHolder)
     Adds a new option description to the parser.
public  PrintStreamgetDefaultPrintStream()
     Returns the default print stream used for outputting help and error information.
public  StringgetErrorMessage()
     Returns the parser's error message.
public  intgetHelpIndentation()
     Gets the indentation used by ArgParser.getHelpMessagegetHelpMessage .
public  StringgetHelpMessage()
     Returns a string describing the allowed options in detail.
public  booleangetHelpOptionsEnabled()
     Indicates whether or not help options are enabled.
 StringgetOptionName(String arg)
    
 StringgetOptionRangeDesc(String arg)
    
 StringgetOptionTypeName(String arg)
    
 ObjectgetResultHolder(String arg)
    
public  StringgetSynopsisString()
     Returns the synopsis string used by the parser.
public  StringgetUnmatchedArgument()
     Returns the value of an unmatched argument discovered ArgParser.matchArg matchArg or ArgParser.matchAllArgs(String[],int,int)matchAllArgs .
public static  StringgetValidConversionCodes()
     Returns a string containing the valid conversion codes.
 RecordlastMatchRecord()
    
public  voidmatchAllArgs(String[] args)
     Matches arguments within an argument list.

In the event of an erroneous or unmatched argument, the method prints a message and exits the program with code 1.

If help options are enabled and one of the arguments matches a help option, then the result of ArgParser.getHelpMessagegetHelpMessage is printed to the default print stream and the program exits with code 0.

public  String[]matchAllArgs(String[] args, int idx, int exitFlags)
     Matches arguments within an argument list and returns those which were not matched.
public  intmatchArg(String[] args, int idx)
     Matches one option starting at a specified location in an argument list.
public static  String[]prependArgs(Reader reader, String[] args)
     Reads in a set of strings from a reader and prepends them to an argument list.
public static  String[]prependArgs(File file, String[] args)
     Reads in a set of strings from a file and prepends them to an argument list.
public  voidprintErrorAndExit(String msg)
     Prints an error message, along with a pointer to help options, if available, and causes the program to exit with code 1.
public  voidsetDefaultPrintStream(PrintStream stream)
     Sets the default print stream used for outputting help and error information.
protected  voidsetError(String msg)
     Sets the parser's error message.
public  voidsetHelpIndentation(int indent)
     Sets the indentation used by ArgParser.getHelpMessagegetHelpMessage .
public  voidsetHelpOptionsEnabled(boolean enable)
     Enables or disables help options.
public  voidsetSynopsisString(String s)
     Sets the synopsis string used by the parser.
static  voidstringToArgs(Vector vec, String s, boolean allowQuotedStrings)
    

Field Detail
EXIT_ON_ERROR
public static int EXIT_ON_ERROR(Code)
Indicates that the program should exit with an appropriate message in the event of an erroneous or malformed argument.



EXIT_ON_UNMATCHED
public static int EXIT_ON_UNMATCHED(Code)
Indicates that the program should exit with an appropriate message in the event of an unmatched argument.



defaultHelpOption
Record defaultHelpOption(Code)



errMsg
String errMsg(Code)



firstHelpOption
Record firstHelpOption(Code)



helpIndent
int helpIndent(Code)



helpOptionsEnabled
boolean helpOptionsEnabled(Code)



matchList
Vector matchList(Code)



printStream
PrintStream printStream(Code)



synopsisString
String synopsisString(Code)



unmatchedArg
String unmatchedArg(Code)



validConversionCodes
static String validConversionCodes(Code)




Constructor Detail
ArgParser
public ArgParser(String synopsisString)(Code)
Creates an ArgParser with a synopsis string, and the default help options -help and -?.
Parameters:
  synopsisString - string that briefly describes program usage,for use by ArgParser.getHelpMessage getHelpMessage.
See Also:   ArgParser.getSynopsisString
See Also:   ArgParser.getHelpMessage



ArgParser
public ArgParser(String synopsisString, boolean defaultHelp)(Code)
Creates an ArgParser with a synopsis string. The help options -help and -? are added if defaultHelp is true.
Parameters:
  synopsisString - string that briefly describes program usage,for use by ArgParser.getHelpMessage getHelpMessage.
Parameters:
  defaultHelp - if true, adds the default help options
See Also:   ArgParser.getSynopsisString
See Also:   ArgParser.getHelpMessage




Method Detail
addOption
public void addOption(String spec, Object resHolder) throws IllegalArgumentException(Code)
Adds a new option description to the parser. The method takes two arguments: a specification string, and a result holder in which to store the associated value.

The specification string has the general form

optionNames %conversionCode [{rangeSpec}] [Xmultiplier] [#valueDescription] [#optionDescription]

where

  • optionNames is a comma-separated list of names for the option (such as -f, --file).

  • conversionCode is a single letter, following a % character, specifying information about what value the option requires:
    %fa floating point number
    %ian integer, in either decimal, hex (if preceeded by 0x), or octal (if preceeded by 0)
    %da decimal integer
    %oan octal integer
    %ha hex integer (without the preceeding 0x)
    %ca single character, including escape sequences (such as \n or \007), and optionally enclosed in single quotes
    %ba boolean value (true or false)
    %sa string. This will be the argument string itself (or its remainder, in the case of a single word option)
    %vno explicit value is expected, but a boolean value of true (by default) will be stored into the associated result holder if this option is matched. If one wishes to have a value of false stored instead, then the %v should be followed by a "range spec" containing false, as in %v{false}.

  • rangeSpec is an optional range specification, placed inside curly braces, consisting of a comma-separated list of range items each specifying permissible values for the option. A range item may be an individual value, or it may itself be a subrange, consisting of two individual values, separated by a comma, and enclosed in square or round brackets. Square and round brackets denote closed and open endpoints of a subrange, indicating that the associated endpoint value is included or excluded from the subrange. The values specified in the range spec need to be consistent with the type of value expected by the option.

    Examples:

    A range spec of {2,4,8,16} for an integer value will allow the integers 2, 4, 8, or 16.

    A range spec of {[-1.0,1.0]} for a floating point value will allow any floating point number in the range -1.0 to 1.0.

    A range spec of {(-88,100],1000} for an integer value will allow values > -88 and <= 100, as well as 1000.

    A range spec of {"foo", "bar", ["aaa","zzz")} for a string value will allow strings equal to "foo" or "bar", plus any string lexically greater than or equal to "aaa" but less then "zzz".

  • multiplier is an optional integer, following a X character, indicating the number of values which the option expects. If the multiplier is not specified, it is assumed to be 1. If the multiplier value is greater than 1, then the result holder should be either an array (of appropriate type) with a length greater than or equal to the multiplier value, or a java.util.Vector as discussed below.

  • valueDescription is an optional description of the option's value requirements, and consists of all characters between two # characters. The final # character initiates the option description, which may be empty. The value description is used in generating help messages.

  • optionDescription is an optional description of the option itself, consisting of all characters between a # character and the end of the specification string. The option description is used in generating help messages.

The result holder must be an object capable of holding a value compatible with the conversion code, or it must be a java.util.Vector. When the option is matched, its associated value is placed in the result holder. If the same option is matched repeatedly, the result holder value will be overwritten, unless the result holder is a java.util.Vector, in which case new holder objects for each match will be allocated and added to the vector. Thus if multiple instances of an option are desired by the program, the result holder should be a java.util.Vector.

If the result holder is not a Vector, then it must correspond as follows to the conversion code:
%i, %d, %x, %o argparser.IntHolder IntHolder , argparser.LongHolder LongHolder , int[], or long[]
%f argparser.FloatHolder FloatHolder , argparser.DoubleHolder DoubleHolder , float[], or double[]
%b, %v argparser.BooleanHolder BooleanHolder or boolean[]
%s argparser.StringHolder StringHolder or String[]
%c argparser.CharHolder CharHolder or char[]

In addition, if the multiplier is greater than 1, then only the array type indicated above may be used, and the array must be at least as long as the multiplier.

If the result holder is a Vector, then the system will create an appropriate result holder object and add it to the vector. Multiple occurances of the option will cause multiple results to be added to the vector.

The object allocated by the system to store the result will correspond to the conversion code as follows:
%i, %d, %x, %o argparser.LongHolder LongHolder , or long[] if the multiplier value exceeds 1
%f argparser.DoubleHolder DoubleHolder , or double[] if the multiplier value exceeds 1
%b, %v argparser.BooleanHolder BooleanHolder , or boolean[] if the multiplier value exceeds 1
%s argparser.StringHolder StringHolder , or String[] if the multiplier value exceeds 1
%c argparser.CharHolder CharHolder , or char[] if the multiplier value exceeds 1

Parameters:
  spec - the specification string
Parameters:
  resHolder - object in which to store the associatedvalue
throws:
  
IllegalArgumentException - if there is an error inthe specification or if the result holder is of an invalidtype.




getDefaultPrintStream
public PrintStream getDefaultPrintStream()(Code)
Returns the default print stream used for outputting help and error information. default print stream
See Also:   ArgParser.setDefaultPrintStream



getErrorMessage
public String getErrorMessage()(Code)
Returns the parser's error message. This is automatically set whenever an error is encountered in matchArg or matchAllArgs, and is automatically set to null at the beginning of these methods. error message



getHelpIndentation
public int getHelpIndentation()(Code)
Gets the indentation used by ArgParser.getHelpMessagegetHelpMessage . number of indentation columns
See Also:   ArgParser.setHelpIndentation
See Also:   ArgParser.getHelpMessage



getHelpMessage
public String getHelpMessage()(Code)
Returns a string describing the allowed options in detail. help information string.



getHelpOptionsEnabled
public boolean getHelpOptionsEnabled()(Code)
Indicates whether or not help options are enabled. true if help options are enabled
See Also:   ArgParser.setHelpOptionsEnabled
See Also:   
See Also:   ArgParser.addOption



getOptionName
String getOptionName(String arg)(Code)



getOptionRangeDesc
String getOptionRangeDesc(String arg)(Code)



getOptionTypeName
String getOptionTypeName(String arg)(Code)



getResultHolder
Object getResultHolder(String arg)(Code)



getSynopsisString
public String getSynopsisString()(Code)
Returns the synopsis string used by the parser. The synopsis string is a short description of how to invoke the program, and usually looks something like

"java somepackage.SomeClass [options] files ..."

It is used in help and error messages. synopsis string
See Also:   ArgParser.setSynopsisString
See Also:   ArgParser.getHelpMessage




getUnmatchedArgument
public String getUnmatchedArgument()(Code)
Returns the value of an unmatched argument discovered ArgParser.matchArg matchArg or ArgParser.matchAllArgs(String[],int,int)matchAllArgs . If there was no unmatched argument, null is returned. unmatched argument



getValidConversionCodes
public static String getValidConversionCodes()(Code)
Returns a string containing the valid conversion codes. These are the characters which may follow the % character in the specification string of ArgParser.addOption addOption . Valid conversion codes
See Also:   ArgParser.addOption



lastMatchRecord
Record lastMatchRecord()(Code)



matchAllArgs
public void matchAllArgs(String[] args)(Code)
Matches arguments within an argument list.

In the event of an erroneous or unmatched argument, the method prints a message and exits the program with code 1.

If help options are enabled and one of the arguments matches a help option, then the result of ArgParser.getHelpMessagegetHelpMessage is printed to the default print stream and the program exits with code 0. If help options are not enabled, they are ignored.
Parameters:
  args - argument list
See Also:   ArgParser.getDefaultPrintStream




matchAllArgs
public String[] matchAllArgs(String[] args, int idx, int exitFlags)(Code)
Matches arguments within an argument list and returns those which were not matched. The matching starts at a location in args specified by idx, and unmatched arguments are returned in a String array.

In the event of an erroneous argument, the method either prints a message and exits the program (if ArgParser.EXIT_ON_ERROR is set in exitFlags) or terminates the matching and creates a error message that can be retrieved by ArgParser.getErrorMessage .

In the event of an umatched argument, the method will print a message and exit if ArgParser.EXIT_ON_UNMATCHED is set in errorFlags. Otherwise, the unmatched argument will be appended to the returned array of unmatched values, and the matching will continue at the next location.

If help options are enabled and one of the arguments matches a help option, then the result of ArgParser.getHelpMessagegetHelpMessage is printed to the the default print stream and the program exits with code 0. If help options are not enabled, then they will not be matched.
Parameters:
  args - argument list
Parameters:
  idx - starting location in list
Parameters:
  exitFlags - conditions causing the program to exit. Should bean or-ed combintion of ArgParser.EXIT_ON_ERROR or ArgParser.EXIT_ON_UNMATCHED. array of arguments that were not matched, ornull if all arguments were successfully matched
See Also:   ArgParser.getErrorMessage
See Also:   ArgParser.getDefaultPrintStream




matchArg
public int matchArg(String[] args, int idx) throws ArgParseException(Code)
Matches one option starting at a specified location in an argument list. The method returns the location in the list where the next match should begin.

In the event of an erroneous argument, the method throws an argparser.ArgParseException ArgParseException with an appropriate error message. This error message can also be retrieved using ArgParser.getErrorMessage getErrorMessage .

In the event of an umatched argument, the method will return idx + 1, and ArgParser.getUnmatchedArgument getUnmatchedArgument will return a copy of the unmatched argument. If an argument is matched, ArgParser.getUnmatchedArgument getUnmatchedArgument will return null.

If help options are enabled and the argument matches a help option, then the result of ArgParser.getHelpMessage getHelpMessage is printed to the the default print stream and the program exits with code 0. If help options are not enabled, then they are ignored.
Parameters:
  args - argument list
Parameters:
  idx - location in list where match should start location in list where next match should start
throws:
  ArgParseException - if there was an error performingthe match (such as improper or insufficient values).
See Also:   ArgParser.setDefaultPrintStream
See Also:   ArgParser.getHelpOptionsEnabled
See Also:   ArgParser.getErrorMessage
See Also:   ArgParser.getUnmatchedArgument




prependArgs
public static String[] prependArgs(Reader reader, String[] args) throws IOException(Code)
Reads in a set of strings from a reader and prepends them to an argument list. Strings are delimited by either whitespace or double quotes ". The character # acts as a comment character, causing input to the end of the current line to be ignored.
Parameters:
  reader - Reader from which to read the strings
Parameters:
  args - Initial set of argument values. Can bespecified as null.
throws:
  IOException - if an error occured while reading.



prependArgs
public static String[] prependArgs(File file, String[] args) throws IOException(Code)
Reads in a set of strings from a file and prepends them to an argument list. Strings are delimited by either whitespace or double quotes ". The character # acts as a comment character, causing input to the end of the current line to be ignored.
Parameters:
  file - File to be read
Parameters:
  args - Initial set of argument values. Can bespecified as null.
throws:
  IOException - if an error occured while reading the file.



printErrorAndExit
public void printErrorAndExit(String msg)(Code)
Prints an error message, along with a pointer to help options, if available, and causes the program to exit with code 1.



setDefaultPrintStream
public void setDefaultPrintStream(PrintStream stream)(Code)
Sets the default print stream used for outputting help and error information.
Parameters:
  stream - new default print stream
See Also:   ArgParser.getDefaultPrintStream



setError
protected void setError(String msg)(Code)
Sets the parser's error message.
Parameters:
  s - Error message



setHelpIndentation
public void setHelpIndentation(int indent)(Code)
Sets the indentation used by ArgParser.getHelpMessagegetHelpMessage . This is the number of columns that an option's help information is indented. If the option's name and value information can fit within this number of columns, then all information about the option is placed on one line. Otherwise, the indented help information is placed on a separate line.
Parameters:
  indent - number of indentation columns
See Also:   ArgParser.getHelpIndentation
See Also:   ArgParser.getHelpMessage



setHelpOptionsEnabled
public void setHelpOptionsEnabled(boolean enable)(Code)
Enables or disables help options. Help options are those associated with a conversion code of %h. If help options are enabled, and a help option is matched, then the string produced by ArgParser.getHelpMessage getHelpMessage is printed to the default print stream and the program exits with code 0. Otherwise, arguments which match help options are ignored.
Parameters:
  enable - enables help options if true.
See Also:   ArgParser.getHelpOptionsEnabled
See Also:   
See Also:   ArgParser.addOption
See Also:   ArgParser.setDefaultPrintStream
See Also:   



setSynopsisString
public void setSynopsisString(String s)(Code)
Sets the synopsis string used by the parser.
Parameters:
  s - new synopsis string
See Also:   ArgParser.getSynopsisString
See Also:   ArgParser.getHelpMessage



stringToArgs
static void stringToArgs(Vector vec, String s, boolean allowQuotedStrings) throws StringScanException(Code)



Methods inherited from java.lang.Object
native protected Object clone() throws CloneNotSupportedException(Code)(Java Doc)
public boolean equals(Object obj)(Code)(Java Doc)
protected void finalize() throws Throwable(Code)(Java Doc)
final native public Class getClass()(Code)(Java Doc)
native public int hashCode()(Code)(Java Doc)
final native public void notify()(Code)(Java Doc)
final native public void notifyAll()(Code)(Java Doc)
public String toString()(Code)(Java Doc)
final native public void wait(long timeout) throws InterruptedException(Code)(Java Doc)
final public void wait(long timeout, int nanos) throws InterruptedException(Code)(Java Doc)
final public void wait() throws InterruptedException(Code)(Java Doc)

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.