Top Description Inners Fields Constructors Methods
org.kohsuke.args4j

public Class CmdLineParser

extends Object
Class Inheritance
Imports
java.io.BufferedReader, .File, .FileReader, .IOException, .OutputStream, .OutputStreamWriter, .PrintWriter, .Writer, java.util.ArrayList, .Arrays, .Collection, .Collections, .HashSet, .List, .ResourceBundle, .Set, org.kohsuke.args4j.spi.Getter, .OptionHandler, .Parameters, .Setter

Command line argument owner.

For typical usage, see this example.

Author
Kohsuke Kawaguchi ([email protected])

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
CmdLineParser.CmdLineImpl

Essentially a pointer over a String array.

Field Summary

Modifier and TypeField and Description
private final List<OptionHandler<T>>
arguments

Discovered OptionHandlers for arguments.

private OptionHandler<T>
private final List<OptionHandler<T>>
options

Discovered OptionHandlers for options.

private ParserProperties
parserProperties

settings for the parser

private boolean

Constructor Summary

AccessConstructor and Description
public
CmdLineParser(Object
instance of a class annotated by Option and Argument. this object will receive values. If this is null, the processing will be skipped, which is useful if you'd like to feed metadata from other sources.
bean
)

Creates a new command line owner that parses arguments/options and set them into the given object.

public
CmdLineParser(Object
instance of a class annotated by Option and Argument. this object will receive values. If this is null, the processing will be skipped, which is useful if you'd like to feed metadata from other sources.
bean
,
ParserProperties
various settings for this class
parserProperties
)

Creates a new command line owner that parses arguments/options and set them into the given object.

Method Summary

Modifier and TypeMethod and Description
public void
addArgument(Setter<T>
the setter for the type
setter
,
Argument
the Argument
a
)

Programmatically defines an argument (instead of reading it from annotations as normal).

public void
addOption(Setter<T>
the setter for the type
setter
,
Option
the Option
o
)

Programmatically defines an option (instead of reading it from annotations as normal).

private void
private void
private String
protected OptionHandler<T>
createOptionHandler(OptionDef o, Setter<T> setter)

Creates an OptionHandler that handles the given Option annotation and the Setter instance.

private String[]

Returns:

args with the @ sequences replaced by the text files referenced by the @ sequences, split around the line breaks.
expandAtFiles
(String[]
the command line arguments to be preprocessed.
args
)

Expands every entry prefixed with the AT sign by reading the file.

private OptionHandler<T>

Returns:

the OptionHandler or null
findOptionByName
(String
name
name
)

Finds a registered OptionHandler by its name or its alias.

private OptionHandler<T>
public List<OptionHandler<T>>
getArguments()

Lists up all the defined arguments in the order.

private String
public List<OptionHandler<T>>
getOptions()

Lists up all the defined options.

private int
public ParserProperties
private boolean

Returns:

true if all options forbid by option are not present, false otherwise
isHandlerAllowOtherOptions
(NamedOptionDef option, Set<OptionHandler<T>> present)

private boolean

Returns:

true if all options required by option are present, false otherwise
isHandlerHasHisOptions
(NamedOptionDef option, Set<OptionHandler<T>> present)

protected boolean
isOption(String arg)

Returns true if the given token is an option (as opposed to an argument).

private String
public void
public void
parseArgument(final String...
arguments to parse
args
)

Parses the command line arguments and set them to the option bean given in the constructor.

public String

Returns:

always non-null.
printExample
(OptionHandlerFilter
must not be null.
filter
)

Formats a command line example into a string.

public String
public String

Returns:

always non-null. If there's no option, this method returns just the empty string "". Otherwise, this method returns a string that contains a space at the beginning (but not at the end). This allows you to do something like: System.err.println("java -jar my.jar"+parser.printExample(REQUIRED)+" arg1 arg2");
printExample
(OptionHandlerFilter
Determines which options will be a part of the returned string. Must not be null.
mode
,
ResourceBundle
If non-null, meta variables (<dir> in the above example) is treated as a key to this resource bundle, and the associated value is printed. See Option#metaVar(). This is to support localization. Passing null would print Option#metaVar() directly.
rb
)

Formats a command line example into a string.

public String
protected void
printOption(PrintWriter
Writer to write into
out
,
OptionHandler<T>
handler where to receive the information
handler
,
int
Maximum length of metadata column
len
,
ResourceBundle
ResourceBundle for I18N
rb
,
OptionHandlerFilter filter)

Prints usage information for a given option.

private void
public void
printSingleLineUsage(OutputStream out)

Prints a single-line usage to the screen.

public void
printSingleLineUsage(Writer w, ResourceBundle
if this is non-null, Option#usage() is treated as a key to obtain the actual message from this resource bundle.
rb
)

Prints a single-line usage to the screen.

public void
printUsage(OutputStream out)

Prints the list of options and their usages to the screen.

public void
printUsage(Writer out, ResourceBundle rb)

Prints the list of all the non-hidden options and their usages to the screen.

public void
printUsage(Writer out, ResourceBundle
If non-null, Option#usage() is treated as a key to obtain the actual message from this resource bundle.
rb
,
OptionHandlerFilter
Controls which options to be printed.
filter
)

Prints the list of all the non-hidden options and their usages to the screen.

private static List<String>
readAllLines(File f)

Reads all lines of a file with the platform encoding.

public static void
registerHandler(Class<T>
The specified handler is used when the field/method annotated by Option is of this type.
valueType
,
Class<? extends OptionHandler<T>>
This class must have the constructor that has the same signature as OptionHandler#OptionHandler(CmdLineParser, OptionDef, Setter)
handlerClass
)

Registers a user-defined OptionHandler class with args4j.

public void
setUsageWidth(int
the width of the usage output in columns.
usageWidth
)
Deprecated Use ParserProperties#withUsageWidth(int) instead.

Sets the width of the usage output.

public void
stopOptionParsing()

Signals the parser that parsing the options has finished.

private List<String>

Returns:

list of all wrapped parts
wrapLines
(String
Line to wrap
line
,
final int
maximum length for the resulting parts
maxLength
)

Wraps a line so that the resulting parts are not longer than a given maximum length.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

argumentsback to summary
private final List<OptionHandler<T>> arguments

Discovered OptionHandlers for arguments.

currentOptionHandlerback to summary
private OptionHandler<T> currentOptionHandler
optionsback to summary
private final List<OptionHandler<T>> options

Discovered OptionHandlers for options.

parserPropertiesback to summary
private ParserProperties parserProperties

settings for the parser

parsingOptionsback to summary
private boolean parsingOptions

Constructor Detail

CmdLineParserback to summary
public CmdLineParser(Object bean)

Creates a new command line owner that parses arguments/options and set them into the given object.

Parameters
bean:Object

instance of a class annotated by Option and Argument. this object will receive values. If this is null, the processing will be skipped, which is useful if you'd like to feed metadata from other sources.

Exceptions
IllegalAnnotationError:
if the option bean class is using args4j annotations incorrectly.
CmdLineParserback to summary
public CmdLineParser(Object bean, ParserProperties parserProperties)

Creates a new command line owner that parses arguments/options and set them into the given object.

Parameters
bean:Object

instance of a class annotated by Option and Argument. this object will receive values. If this is null, the processing will be skipped, which is useful if you'd like to feed metadata from other sources.

parserProperties:ParserProperties

various settings for this class

Exceptions
IllegalAnnotationError:
if the option bean class is using args4j annotations incorrectly.

Method Detail

addArgumentback to summary
public void addArgument(Setter<T> setter, Argument a)

Programmatically defines an argument (instead of reading it from annotations as normal).

Parameters
setter:Setter<T>

the setter for the type

a:Argument

the Argument

Exceptions
NullPointerException:
if setter or a is null.
addOptionback to summary
public void addOption(Setter<T> setter, Option o)

Programmatically defines an option (instead of reading it from annotations as normal).

Parameters
setter:Setter<T>

the setter for the type

o:Option

the Option

Exceptions
NullPointerException:
if setter or o is null.
IllegalAnnotationError:
if the option name or one of the aliases is already taken.
checkOptionNotInMapback to summary
private void checkOptionNotInMap(String name) throws IllegalAnnotationError
checkRequiredOptionsAndArgumentsback to summary
private void checkRequiredOptionsAndArguments(Set<OptionHandler<T>> present) throws CmdLineException
createDefaultValuePartback to summary
private String createDefaultValuePart(OptionHandler<T> handler)
createOptionHandlerback to summary
protected OptionHandler<T> createOptionHandler(OptionDef o, Setter<T> setter)

Creates an OptionHandler that handles the given Option annotation and the Setter instance.

expandAtFilesback to summary
private String[] expandAtFiles(String[] args) throws CmdLineException

Expands every entry prefixed with the AT sign by reading the file. The AT sign is used to reference another file that contains command line options separated by line breaks.

Parameters
args:String[]

the command line arguments to be preprocessed.

Returns:String[]

args with the @ sequences replaced by the text files referenced by the @ sequences, split around the line breaks.

findOptionByNameback to summary
private OptionHandler<T> findOptionByName(String name)

Finds a registered OptionHandler by its name or its alias.

Parameters
name:String

name

Returns:OptionHandler<T>

the OptionHandler or null

findOptionHandlerback to summary
private OptionHandler<T> findOptionHandler(String name)
getArgumentsback to summary
public List<OptionHandler<T>> getArguments()

Lists up all the defined arguments in the order.

getOptionNameback to summary
private String getOptionName()
getOptionsback to summary
public List<OptionHandler<T>> getOptions()

Lists up all the defined options.

getPrefixLenback to summary
private int getPrefixLen(OptionHandler<T> h, ResourceBundle rb)
getPropertiesback to summary
public ParserProperties getProperties()
isHandlerAllowOtherOptionsback to summary
private boolean isHandlerAllowOtherOptions(NamedOptionDef option, Set<OptionHandler<T>> present)
Returns:boolean

true if all options forbid by option are not present, false otherwise

isHandlerHasHisOptionsback to summary
private boolean isHandlerHasHisOptions(NamedOptionDef option, Set<OptionHandler<T>> present)
Returns:boolean

true if all options required by option are present, false otherwise

isOptionback to summary
protected boolean isOption(String arg)

Returns true if the given token is an option (as opposed to an argument).

Exceptions
NullPointerException:
if arg is null.
localizeback to summary
private String localize(String s, ResourceBundle rb)
parseArgumentback to summary
public void parseArgument(Collection<String> args) throws CmdLineException

Same as parseArgument(String[])

parseArgumentback to summary
public void parseArgument(final String... args) throws CmdLineException

Parses the command line arguments and set them to the option bean given in the constructor.

Parameters
args:String[]

arguments to parse

Exceptions
CmdLineException:
if there's any error parsing arguments, or if required option was not given.
NullPointerException:
if args is null.
printExampleback to summary
public String printExample(OptionHandlerFilter filter)

Formats a command line example into a string. See printExample(OptionHandlerFilter, ResourceBundle) for more details.

Parameters
filter:OptionHandlerFilter

must not be null.

Returns:String

always non-null.

printExampleback to summary
public String printExample(ExampleMode mode)
printExampleback to summary
public String printExample(OptionHandlerFilter mode, ResourceBundle rb)

Formats a command line example into a string.

This method produces a string like -d <dir> -v -b. This is useful for printing a command line example (perhaps as a part of the usage screen).

Parameters
mode:OptionHandlerFilter

Determines which options will be a part of the returned string. Must not be null.

rb:ResourceBundle

If non-null, meta variables (<dir> in the above example) is treated as a key to this resource bundle, and the associated value is printed. See Option#metaVar(). This is to support localization. Passing null would print Option#metaVar() directly.

Returns:String

always non-null. If there's no option, this method returns just the empty string "". Otherwise, this method returns a string that contains a space at the beginning (but not at the end). This allows you to do something like: System.err.println("java -jar my.jar"+parser.printExample(REQUIRED)+" arg1 arg2");

Exceptions
NullPointerException:
if mode is null.
printExampleback to summary
public String printExample(ExampleMode mode, ResourceBundle rb)
printOptionback to summary
protected void printOption(PrintWriter out, OptionHandler<T> handler, int len, ResourceBundle rb, OptionHandlerFilter filter)

Prints usage information for a given option.

Subtypes may override this method and determine which options get printed (or other things), based on OptionHandler (perhaps by using handler.setter.asAnnotatedElement()).

Parameters
out:PrintWriter

Writer to write into

handler:OptionHandler<T>

handler where to receive the information

len:int

Maximum length of metadata column

rb:ResourceBundle

ResourceBundle for I18N

See Also
Setter#asAnnotatedElement()
printSingleLineOptionback to summary
private void printSingleLineOption(PrintWriter pw, OptionHandler<T> h, ResourceBundle rb)
printSingleLineUsageback to summary
public void printSingleLineUsage(OutputStream out)

Prints a single-line usage to the screen.

This is a convenience method for calling printUsage(new OutputStreamWriter(out),null) so that you can do printUsage(System.err).

Exceptions
NullPointerException:
if out is null.
printSingleLineUsageback to summary
public void printSingleLineUsage(Writer w, ResourceBundle rb)

Prints a single-line usage to the screen.

Parameters
rb:ResourceBundle

if this is non-null, Option#usage() is treated as a key to obtain the actual message from this resource bundle.

Exceptions
NullPointerException:
if w is null.
printUsageback to summary
public void printUsage(OutputStream out)

Prints the list of options and their usages to the screen.

This is a convenience method for calling printUsage(new OutputStreamWriter(out),null) so that you can do printUsage(System.err).

printUsageback to summary
public void printUsage(Writer out, ResourceBundle rb)

Prints the list of all the non-hidden options and their usages to the screen.

Short for printUsage(out,rb,OptionHandlerFilter.PUBLIC)

printUsageback to summary
public void printUsage(Writer out, ResourceBundle rb, OptionHandlerFilter filter)

Prints the list of all the non-hidden options and their usages to the screen.

Parameters
rb:ResourceBundle

If non-null, Option#usage() is treated as a key to obtain the actual message from this resource bundle.

filter:OptionHandlerFilter

Controls which options to be printed.

readAllLinesback to summary
private static List<String> readAllLines(File f) throws IOException

Reads all lines of a file with the platform encoding.

registerHandlerback to summary
public static void registerHandler(Class<T> valueType, Class<? extends OptionHandler<T>> handlerClass)

Registers a user-defined OptionHandler class with args4j.

This method allows users to extend the behavior of args4j by writing their own OptionHandler implementation.

Parameters
valueType:Class<T>

The specified handler is used when the field/method annotated by Option is of this type.

handlerClass:Class<? extends OptionHandler<T>>

This class must have the constructor that has the same signature as OptionHandler#OptionHandler(CmdLineParser, OptionDef, Setter)

Exceptions
NullPointerException:
if valueType or handlerClass is null.
IllegalArgumentException:
if handlerClass is not a subtype of OptionHandler.
setUsageWidthback to summary
public void setUsageWidth(int usageWidth)

Deprecated

Use ParserProperties#withUsageWidth(int) instead.

Sets the width of the usage output.

Parameters
usageWidth:int

the width of the usage output in columns.

Exceptions
IllegalArgumentException:
if usageWidth is negative
stopOptionParsingback to summary
public void stopOptionParsing()

Signals the parser that parsing the options has finished.

Everything seen after this call is treated as an argument as opposed to an option.

wrapLinesback to summary
private List<String> wrapLines(String line, final int maxLength)

Wraps a line so that the resulting parts are not longer than a given maximum length.

Parameters
line:String

Line to wrap

maxLength:int

maximum length for the resulting parts

Returns:List<String>

list of all wrapped parts

org.kohsuke.args4j back to summary

private Class CmdLineParser.CmdLineImpl

extends Object
implements Parameters
Class Inheritance
All Implemented Interfaces
org.kohsuke.args4j.spi.Parameters

Essentially a pointer over a String array. Can move forward; can look ahead.

Field Summary

Modifier and TypeField and Description
private final String[]
private int

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
protected String
public String
getParameter(int
specifying 0 will retrieve the token next to the option. For example, if the command line looks like -o abc -d x, then getParameter(0) for -o returns abc and getParameter(1) will return -d.
idx
)

Implements org.kohsuke.args4j.spi.Parameters.getParameter.

Gets the additional parameter to this option.

protected boolean
private void
proceed(int n)

public int
size()

Implements org.kohsuke.args4j.spi.Parameters.size.

Number of remaining tokens.

pack-priv void
splitToken()

Used when the current token is of the form "-option=value", to replace the current token by "value", as if this was given as two tokens "-option value"

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

argsback to summary
private final String[] args
posback to summary
private int pos

Constructor Detail

CmdLineImplback to summary
pack-priv CmdLineImpl(String[] args)

Method Detail

getCurrentTokenback to summary
protected String getCurrentToken()
getParameterback to summary
public String getParameter(int idx) throws CmdLineException

Implements org.kohsuke.args4j.spi.Parameters.getParameter.

Doc from org.kohsuke.args4j.spi.Parameters.getParameter.

Gets the additional parameter to this option.

Parameters
idx:int

specifying 0 will retrieve the token next to the option. For example, if the command line looks like -o abc -d x, then getParameter(0) for -o returns abc and getParameter(1) will return -d.

Returns:String

Always return non-null valid String. If an attempt is made to access a non-existent index, this method throws appropriate org.kohsuke.args4j.CmdLineException.

hasMoreback to summary
protected boolean hasMore()
proceedback to summary
private void proceed(int n)
sizeback to summary
public int size()

Implements org.kohsuke.args4j.spi.Parameters.size.

Doc from org.kohsuke.args4j.spi.Parameters.size.

Number of remaining tokens.

splitTokenback to summary
pack-priv void splitToken()

Used when the current token is of the form "-option=value", to replace the current token by "value", as if this was given as two tokens "-option value"