Package com.portal.common
Class CommandLineParser
java.lang.Object
com.portal.common.CommandLineParser
- Direct Known Subclasses:
Options
This class is a utility for parsing and accessing command line arguments
and supports the following:
A standard parsing method with hooks that can be overriden
to impose a syntax.
Methods to access 0 to many values for an option.
Methods to access the leading tokens.
Methods to access the trailing tokens.
Nomenclature:
token | 1 or more characters delimited by white space characeters. The 1st character cannot be a "-" |
option | a token preceded by a "-" (i.e. -verbose); options are case insensitive |
value | one or more tokens following an option |
Syntax assumed by this class followed by some examples:
[token] ... [option] [value] ... [token]
max.txt -threads 5 -debug -mode color intense table.txt
-threads 5 -debug -verbose max.txt jon.txt
The last example would decompose as follows:
Type | Option | Values/Tokens |
leading_tokens | N/A | none |
option | -threads | 5 |
option | -debug | none |
option | -verbose | max.txt jon.txt |
trailing_tokens | N/A | max.txt jon.txt |
From the decompositon you can see the values for the option -verbose are the same as the tokens for the trailing_tokens. This is an ambiguous case which is beyond the scope of what this class is intended to solve. The consumer of this class needs to resolve the ambiguity or a dervied class can be created that will resolve the ambiguity.
- Author:
- Max Spivak and Jon Sorensen
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionclass
Signals that an exception occurred while the command line arguments were being parsed.class
Signals that an exception occurred while looking up an option.class
Signals that an exception occurred when trying to convert an option value from one data type to another or the value(s) associated with the option are invalid.class
Signals that an exception occurred while doing an operation that involved an option (lookup of the option, data retrieval, etc.)class
Signals that an exception occurred when trying to retrieve one or more values for an option. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final int
Constant used to specify an indefinite number of values. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
CommandLineParser
(String[] args) You must call this constructor when deriving from this class and the constructor of your derived class you must call theparse
method after your constructor has finished all initialization. -
Method Summary
Modifier and TypeMethodDescriptionprotected final String
constructErrMsg
(String errFormatKey, Object[] msgArgs) Helper method used to construct an error message using the specified key.protected final String
constructErrMsg
(ResourceBundle bundle, String errFormatKey, Object[] msgArgs) Helper method used to construct an error message using the specified key.boolean
containsOption
(String option) Tests if a option (i.e.static CommandLineParser
createParser
(String[] args) Factory method used to create a CommandLineParser.String[]
getArgs()
Get the command line argumets that were passed to the constructor of the CommandLineParser.getHelp()
Get the help string that describes the syntax required by your options class and a desciption of each option used by your class.getLeadingToken
(int index) Get the ith leading token using the specified index.String[]
Get the leading tokens.int
Get the number of leading tokens.int
Get the number of options that appeared on the command line.int
Get the number of trailing tokens.int
getNumValues
(String option) Get the number values that follow an option.protected final String
getStrFromBundle
(String key) Helper method used to return a string using the specified key.protected final String
getStrFromBundle
(ResourceBundle bundle, String key) Helper method used to return a string using the specified key.getTrailingToken
(int index) Get the ith trailing token using the specified index.String[]
Get the trailing tokens.Gets the first value following specified option.String[]
Get all of the values following the specified option.String[]
Get the specified number of values following the specified option.boolean
isHelp()
Return true if the help option was contained in the command line or the command line is empty.protected final void
parse()
Internal method that parses the argument array.protected void
Override this method to do any post parsing.protected boolean
Override this method if you want to change the default behavior that when a command line only contains tokens (no options) then the tokens will be considered leading tokens and there will be no trailing tokens.static String
strArrayToString
(String[] sa) Simple minded helper method to output the contents of a string array to a string.toString()
Convert this class to a string that will contain the following: The arguments passed to the constructor The leading tokens For each option, the values associated with that option The trailing tokensprotected void
validateLeadingTokens
(ArrayList tokens) Override this method if validation of the leading tokens is required when parsing the command line arguments.protected void
validateOption
(String option, ArrayList values, boolean lastOption) Override this method if validation for a particular option is required.protected void
Ensure that all required options were present on the command line.protected void
validateTrailingTokens
(ArrayList tokens, int numLastOptionArgs) Override this method if validation of the trailing tokens is required when parsing the command line arguments.
-
Field Details
-
ALL
public static final int ALLConstant used to specify an indefinite number of values. Used in methods likegetValues()
to retrieve all of the values associated with the option.- See Also:
-
-
Constructor Details
-
CommandLineParser
You must call this constructor when deriving from this class and the constructor of your derived class you must call theparse
method after your constructor has finished all initialization. This is because theparse
method calls methods that can be overriden in your derived class, so your dervied class must be completely instantiated for theparse
method to operate correctly and predictably.- Parameters:
args
- The array of command line arguments passed to the program.dummy
- A dummy parameter used to create a unique method signature. Just pass null.- Throws:
CommandLineParser.InvalidOptionsException
- An error was encountered when parsing the command line arguments. This gets thrown by the parse() method that the constructor in your derived class will call.
-
-
Method Details
-
createParser
public static CommandLineParser createParser(String[] args) throws CommandLineParser.InvalidOptionsException Factory method used to create a CommandLineParser. Call this method to construct a ComandLineParser.- Parameters:
args
- The array of command line arguments passed to the program.- Returns:
- An instance of a CommandLineParser.
- Throws:
CommandLineParser.InvalidOptionsException
- An error was encountered when parsing the command line arguments. The only error this class will generate is when a duplicate option is encountered.
-
getArgs
Get the command line argumets that were passed to the constructor of the CommandLineParser.- Returns:
- the command line argumets that were passed to the constructor of the CommandLineParser.
-
containsOption
Tests if a option (i.e. -debug) is present in the command line arguments.- Parameters:
option
- The option to check for presence in the command line.- Returns:
- true if option exists on command line, false otherwise.
-
getNumValues
Get the number values that follow an option.- Parameters:
option
- The option (i.e. -accounts) to return the number of values for.- Returns:
- The number values that follow an option. A value of zero will be returned if there are no values following the specified option.
- Throws:
CommandLineParser.NoSuchOptionException
- The option is not on the command line.
-
getValues
Get all of the values following the specified option. If no values follow the option an empty array will be returned.- Parameters:
option
- The option (i.e. -accounts) to return the values for.- Returns:
- Array of values associated with the option. The array will be empty if there are no values.
- Throws:
CommandLineParser.NoSuchOptionException
- The option is not on the command line.
-
getValues
public String[] getValues(String option, int numValues) throws CommandLineParser.NoSuchOptionException, CommandLineParser.ValueOutOfBoundsException Get the specified number of values following the specified option. Use the constantCommandLineParser.ALL
to return all the values following the option. If no values follow the option an empty array will be returned.- Parameters:
option
- The option (i.e. -accounts) to return the values for.numValues
- The number of values to return. Use the constantCommandLineParser.ALL
to return all the values following the option.- Returns:
- Array of values associated with the option. The array will be empty if there are no values.
- Throws:
CommandLineParser.NoSuchOptionException
- The option is not on the command line.CommandLineParser.ValueOutOfBoundsException
- The number of values requested exceeds the number of values associated with the option.
-
getValue
public String getValue(String option) throws CommandLineParser.NoSuchOptionException, CommandLineParser.ValueOutOfBoundsException Gets the first value following specified option. If no values follow the option an exception will be thrown.- Parameters:
option
- The option (i.e. -threads) to return the first value for.- Returns:
- The first value associated with the option.
- Throws:
CommandLineParser.NoSuchOptionException
- The option is not on the command line.CommandLineParser.ValueOutOfBoundsException
- There are no values associated with the option.
-
getNumLeadingTokens
public int getNumLeadingTokens()Get the number of leading tokens. These are the arguments that precede the first option on the command line.- Returns:
- The number of leading tokens on the command line. If there no leading tokens a value of zero will be returned.
-
getLeadingTokens
Get the leading tokens. These are the arguments that precede the first option on the command line.- Returns:
- The string array of leading tokens. If there no leading tokens an empty array will be returned.
-
getLeadingToken
Get the ith leading token using the specified index.- Parameters:
index
- The zero relative index of token to return.- Returns:
- The ith leading token.
- Throws:
CommandLineParser.ValueOutOfBoundsException
- The ith leading token does not exist.
-
getNumTrailingTokens
public int getNumTrailingTokens()Get the number of trailing tokens. These are the arguments that follow the last option on the command line.- Returns:
- The number of trailing tokens on the command line. If there no trailing tokens a value of zero will be returned.
-
getNumOptions
public int getNumOptions()Get the number of options that appeared on the command line.- Returns:
- The number of options that appeared on the command line. A value of zero implies no options were present.
-
getTrailingTokens
Get the trailing tokens. These are the arguments that follow the last option on the command line.- Returns:
- The string array of trailing tokens. If there no trailing tokens an empty array will be returned.
-
getTrailingToken
Get the ith trailing token using the specified index.- Parameters:
index
- The zero relative index of token to return.- Returns:
- The ith trailing token.
- Throws:
CommandLineParser.ValueOutOfBoundsException
- The ith trailing token does not exist.
-
toString
Convert this class to a string that will contain the following:- The arguments passed to the constructor
- The leading tokens
- For each option, the values associated with that option
- The trailing tokens
-
isHelp
public boolean isHelp()Return true if the help option was contained in the command line or the command line is empty.- Returns:
- Since this class knows nothing about specific options it will always return false.
-
getHelp
Get the help string that describes the syntax required by your options class and a desciption of each option used by your class.- Returns:
- Since this class knows nothing about specific options it will always return an empty string.
-
strArrayToString
Simple minded helper method to output the contents of a string array to a string. Each element in the string array will be enclosed in single quotes and separated by a comma (i.e. 'arg1', 'arg2').- Returns:
- the contents of a string array as a string.
-
validateLeadingTokens
protected void validateLeadingTokens(ArrayList tokens) throws CommandLineParser.InvalidOptionsException Override this method if validation of the leading tokens is required when parsing the command line arguments. The default implementation of this method does no validation.- Parameters:
tokens
- The list of "tokens" that appear at the beginning of the command line. The list will be empty if there are no tokens.- Throws:
CommandLineParser.InvalidOptionsException
- There is an error with the number of "leading tokens" or the value of a "leading token" is invalid.
-
validateOption
protected void validateOption(String option, ArrayList values, boolean lastOption) throws CommandLineParser.InvalidOptionsException Override this method if validation for a particular option is required. To resolve the ambiguity associated with the values for the last option and the trailing tokens could also be resolved by overriding this method. The default implementation of this method does no validation.- Parameters:
option
- The name of the option to validate. This name will include the leading "-" (i.e. "-verbose").values
- The list of values associated with the option. The list will be empty if there are no values.lastOption
- This flag will be true if this is the last option contained in the command line.- Throws:
CommandLineParser.InvalidOptionsException
- There is an error with the number of values for the option or a particular value is invalid.
-
validateTrailingTokens
protected void validateTrailingTokens(ArrayList tokens, int numLastOptionArgs) throws CommandLineParser.InvalidOptionsException Override this method if validation of the trailing tokens is required when parsing the command line arguments. The default implementation of this method does no validation.- Parameters:
tokens
- The list of "tokens" that appear at the end of the command line. The list will be empty if there are no tokens.numLastOptionArgs
- The number of arguments used by the last option.- Throws:
CommandLineParser.InvalidOptionsException
- There is an error with the number of trailing tokens or the value of a trailing token> is invalid.
-
validateRequiredParameters
Ensure that all required options were present on the command line. The default implementation does no validation.- Throws:
CommandLineParser.InvalidOptionsException
- A required option was not present on the command line.
-
storeAllTokensAsLeadingTokens
protected boolean storeAllTokensAsLeadingTokens()Override this method if you want to change the default behavior that when a command line only contains tokens (no options) then the tokens will be considered leading tokens and there will be no trailing tokens.- Returns:
- Always return true.
-
postParse
Override this method to do any post parsing. Typically, this is the place where you can extract option values into local member variables. The default implementation does nothing.- Throws:
CommandLineParser.InvalidOptionsException
- An error was detected when extracting option values into local member variables.
-
parse
Internal method that parses the argument array. You must call theparse
method after your constructor has finished all initialization. This is because theparse
method calls methods that can be overriden in your derived class, so your dervied class must be completely instantiated for this method to function correctly and predictably.- Throws:
CommandLineParser.InvalidOptionsException
- An error was encountered when parsing the command line arguments.
-
getStrFromBundle
Helper method used to return a string using the specified key. from the JavaCommon resource bundle. A generic message will be returned if the string can not be found.- Parameters:
key
- The key to use to retrieve the string from the resource bundle.- Returns:
- the string retrieved from the JavaCommon resource bundle. A generic message will be returned if the string can not be found.
-
getStrFromBundle
Helper method used to return a string using the specified key. from the JavaCommon resource bundle. A generic message will be returned if the string can not be found.- Parameters:
bundle
- The resource bundle to retrieve the string from.key
- The key to use to retrieve the string from the resource bundle.- Returns:
- the string cannot be retrieved from the sprecified resource bundle. A generic message will be returned if the string can not be found.
-
constructErrMsg
Helper method used to construct an error message using the specified key. The error message will be retrieved from the JavaCommon resource bundle and will have the specified list of "arguments substitued into it. A generic message will be returned if the error message can not be found.- Parameters:
errFormatKey
- The resource key to use to retrieve the error message (i.e. "clp.format_msg.option_not_found").msgArgs
- The array of arguments to substitute into the error message.- Returns:
- the error message with specified arguments substitued into it. A generic message will be returned if the error message can not be found.
-
constructErrMsg
protected final String constructErrMsg(ResourceBundle bundle, String errFormatKey, Object[] msgArgs) Helper method used to construct an error message using the specified key. The error message will be retrieved from the specified resource bundle and will have the specified list of "arguments substitued into it. A generic message will be returned if the error message can not be found.- Parameters:
bundle
- The resource bundle to retrieve the error message from.errFormatKey
- The resource key to use to retrieve the error message (i.e. "clp.format_msg.option_not_found").msgArgs
- The array of arguments to substitute into the error message.- Returns:
- the error message with specified arguments substitued into it. A generic message will be returned if the error message can not be found.
-