public final class ParameterParser
extends java.lang.Object
This class provides a command line parameter and option parser, suitable
for use in command line utilities, as well as other contexts where a command
line option-style syntax is desired. The CommandLineUtility
class
implicitly uses this class to parse its parameters, but there's no reason
an application cannot use a ParameterParser object directly.
ParameterParser supports both short single-character options (e.g., -h) and GNU-style long options (e.g., --help). A single option can have both a short and a long variant. Similarly, it's possible to have only a short or a long variant for an option. In addition, this class will parse non-option parameters that follow any options.
Note that this class does not parse options the way GNU getopt() (or even traditional getopt()) does. In particular, it does not permit combining multiple single-character options into one command-line parameter. The parsing logic may be extended to support that capability in the future; however, it doesn't do that yet.
Using this class is straightforward:
UsageInfo
object that describes the options and
parameters. This object is also used when generating a usage summary
message. (See the getUsageMessage()
method.)
ParameterHandler
interface. An instance of this class will
be passed to the parser, to be invoked as the parser encounters options
and parameters.
parse()
method, passing it three arguments:
UsageInfo
object that describes the expected
options and parameters.
ParameterHandler
interface.
Example:
This example handles the following options and parameters, for a fictitious copy utility.
Option/Parameter | Meaning |
---|---|
--help or -h | Get detailed help |
--force or -f | Perform the copy even if the destination file already exists. |
--time yyyymmddHHMMSS or -t yymmddHHMMSS |
After the copy, set the timestamp of the destination file to the specified datetime. |
srcFile | Path to file to be copied. |
destFile | Path to destinationn file. |
Here's some sample code that will parse those options. In practice, of
course, you'd usually use the CommandLineUtility
infrastructure,
which provides these capabilities and more; however, for the purposes of
illustration, we'll stick to ParameterParser here. This example
omits constructors, a main() method, and other methods necessary
build a truly runnable utility.
public class ExampleParser implements ParameterHandler
{
private Date timestamp= null;
private boolean forceCopy = false;
private boolean showHelpOnly = false;
public void parse(String[] args) throws CommandLineUtilityException
{
UsageInfo usageInfo = new UsageInfo();
usageInfo.addOption('h', "help", "Get detailed help");
usageInfo.addOption('f', "force",
"Perform copy even if destination file exists.");
usageInfo.addOption('t', "time", "yymmddHHMMSS",
"Set timestamp of destination file to specified " +
"datetime");
usageInfo.addParameter("srcFile", "Path to file to be copied", true);
usageInfo.addParameter("destFile", "Path to destination file", true);
ParameterParser paramParser = new ParameterParser();
try
{
paramParser.parse(args, this);
}
catch (Exception ex)
{
System.err.println(paramParser.getUsageMessage(null, 80));
}
}
public void parseOption(char shortOption, String longOption, Iterator<String> it)
throws CommandLineUsageException,
NoSuchElementException
{
switch (shortOption)
{
case 'h':
doHelp();
this.showHelpOnly = true;
break;
case 'f':
forceCopy = true;
break;
case 't':
parseTimestamp(it.next());
break;
default:
if (longOption == null)
throw new CommandLineUsageException("Unknown option: " +
UsageInfo.SHORT_OPTION_PREFIX +
shortOption);
else
throw new CommandLineUsageException("Unknown option: " +
UsageInfo.LONG_OPTION_PREFIX +
longOption);
break;
}
}
public void parsePostOptionParameters(Iterator<String> it)
throws CommandLineUsageException,
NoSuchElementException
{
this.sourceFile = new File(it.next());
this.targetFile = new File(it.next());
}
}
ParameterHandler
,
CommandLineUtility
Constructor and Description |
---|
ParameterParser(UsageInfo usageInfo)
Construct a new ParameterParser that parses a specific set
of options.
|
Modifier and Type | Method and Description |
---|---|
java.lang.String |
getUsageMessage(java.lang.String prefixMsg)
Generate a usage message.
|
java.lang.String |
getUsageMessage(java.lang.String prefixMsg,
int maxLineLength)
Generate a usage message.
|
void |
parse(java.lang.String[] params,
ParameterHandler paramHandler)
Parse a set of command-line parameters.
|
public void parse(java.lang.String[] params, ParameterHandler paramHandler) throws CommandLineUsageException
UsageInfo
object dictates the arguments to be parsed. The ParameterHandler
object handles the encountered parameters.params
- parameters to parseparamHandler
- handles the argumentsCommandLineUsageException
- on errorpublic java.lang.String getUsageMessage(java.lang.String prefixMsg)
prefixMsg
- prefix (e.g., error) message to use, or nullpublic java.lang.String getUsageMessage(java.lang.String prefixMsg, int maxLineLength)
prefixMsg
- prefix (e.g., error) message to use, or nullmaxLineLength
- maximum output line length, or 0 to disable line
wrapping