org.clapper.util.cmdline
Class ParameterParser

java.lang.Object
  extended by org.clapper.util.cmdline.ParameterParser

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:

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());
     }
 }
 

Version:
$Revision: 6767 $
Author:
Copyright © 2004-2007 Brian M. Clapper
See Also:
ParameterHandler, CommandLineUtility

Constructor Summary
ParameterParser(UsageInfo usageInfo)
          Construct a new ParameterParser that parses a specific set of options.
 
Method Summary
 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.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ParameterParser

public ParameterParser(UsageInfo usageInfo)
Construct a new ParameterParser that parses a specific set of options.

Parameters:
usageInfo - the UsageInfo object that describes the parameters to be parsed
Method Detail

parse

public void parse(java.lang.String[] params,
                  ParameterHandler paramHandler)
           throws CommandLineUsageException
Parse a set of command-line parameters. The UsageInfo object dictates the arguments to be parsed. The ParameterHandler object handles the encountered parameters.

Parameters:
params - parameters to parse
paramHandler - handles the arguments
Throws:
CommandLineUsageException - on error

getUsageMessage

public java.lang.String getUsageMessage(java.lang.String prefixMsg)
Generate a usage message.

Parameters:
prefixMsg - prefix (e.g., error) message to use, or null
Returns:
the usage string, with embedded newlines

getUsageMessage

public java.lang.String getUsageMessage(java.lang.String prefixMsg,
                                        int maxLineLength)
Generate a usage message.

Parameters:
prefixMsg - prefix (e.g., error) message to use, or null
maxLineLength - maximum output line length, or 0 to disable line wrapping
Returns:
the usage string, with embedded newlines


Copyright © 2004-2007 Brian M. Clapper. All Rights Reserved.