Documentation of 'org.clapper.util.cmdline.ParameterParser' Java class
ParameterParser
org.clapper.util.cmdline

Class 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:

    • Create a UsageInfo object that describes the options and parameters. This object is also used when generating a usage summary message. (See the getUsageMessage() method.)
    • Create a class (often, a local or anonymous one will do) that implements the ParameterHandler interface. An instance of this class will be passed to the parser, to be invoked as the parser encounters options and parameters.
    • Instantiate a ParameterParser object and call its parse() method, passing it three arguments:
      1. The array of parameters to be parsed. Options are assumed to precede non-option parameters.
      2. The UsageInfo object that describes the expected options and parameters.
      3. An instance of the class that implements the 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());
         }
     }
     
    See Also:
    ParameterHandler, CommandLineUtility
    • Constructor Summary

      Constructors 
      Constructor and Description
      ParameterParser(UsageInfo usageInfo)
      Construct a new ParameterParser that parses a specific set of options.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      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.
      • Methods inherited from class java.lang.Object

        equals, 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

      • 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

DMelt 3.0 © DataMelt by jWork.ORG

You see the box below because you did not login.