CmdLineParser.java
上传用户:zhengdagz
上传日期:2014-03-06
资源大小:1956k
文件大小:11k
源码类别:

xml/soap/webservice

开发平台:

Java

  1. package org.jdesktop.demo;
  2. import java.text.NumberFormat;
  3. import java.text.ParseException;
  4. import java.util.Hashtable;
  5. import java.util.Vector;
  6. import java.util.Enumeration;
  7. import java.util.Locale;
  8. /**
  9.  * Largely GNU-compatible command-line options parser. Has short (-v) and
  10.  * long-form (--verbose) option support, and also allows options with
  11.  * associated values (-d 2, --debug 2, --debug=2). Option processing
  12.  * can be explicitly terminated by the argument '--'.
  13.  * <p/>
  14.  * <b>Note from Richard Bair:</b> This file was taken from the jargs project
  15.  * which can be found at http://sourceforge.net/projects/jargs. The project is
  16.  * BSD licensed, so I'm ok in doing this.
  17.  *
  18.  * @author Steve Purcell
  19.  * @version $Revision: 1.1 $
  20.  */
  21. public class CmdLineParser {
  22.     /**
  23.      * Base class for exceptions that may be thrown when options are parsed
  24.      */
  25.     public static abstract class OptionException extends Exception {
  26.         OptionException(String msg) { super(msg); }
  27.     }
  28.     /**
  29.      * Thrown when the parsed command-line contains an option that is not
  30.      * recognised. <code>getMessage()</code> returns
  31.      * an error string suitable for reporting the error to the user (in
  32.      * English).
  33.      */
  34.     public static class UnknownOptionException extends OptionException {
  35.         UnknownOptionException( String optionName ) {
  36.             super("unknown option '" + optionName + "'");
  37.             this.optionName = optionName;
  38.         }
  39.         /**
  40.          * @return the name of the option that was unknown (e.g. "-u")
  41.          */
  42.         public String getOptionName() { return this.optionName; }
  43.         private String optionName = null;
  44.     }
  45.     /**
  46.      * Thrown when an illegal or missing value is given by the user for
  47.      * an option that takes a value. <code>getMessage()</code> returns
  48.      * an error string suitable for reporting the error to the user (in
  49.      * English).
  50.      */
  51.     public static class IllegalOptionValueException extends OptionException {
  52.         public IllegalOptionValueException( Option opt, String value ) {
  53.             super("illegal value '" + value + "' for option -" +
  54.                   opt.shortForm() + "/--" + opt.longForm());
  55.             this.option = opt;
  56.             this.value = value;
  57.         }
  58.         /**
  59.          * @return the name of the option whose value was illegal (e.g. "-u")
  60.          */
  61.         public Option getOption() { return this.option; }
  62.         /**
  63.          * @return the illegal value
  64.          */
  65.         public String getValue() { return this.value; }
  66.         private Option option;
  67.         private String value;
  68.     }
  69.     /**
  70.      * Representation of a command-line option
  71.      */
  72.     public static abstract class Option {
  73.         protected Option( char shortForm, String longForm,
  74.                           boolean wantsValue ) {
  75.             if ( longForm == null )
  76.                 throw new IllegalArgumentException("null arg forms not allowed");
  77.             this.shortForm = new String(new char[]{shortForm});
  78.             this.longForm = longForm;
  79.             this.wantsValue = wantsValue;
  80.         }
  81.         public String shortForm() { return this.shortForm; }
  82.         public String longForm() { return this.longForm; }
  83.         /**
  84.          * Tells whether or not this option wants a value
  85.          */
  86.         public boolean wantsValue() { return this.wantsValue; }
  87.         public final Object getValue( String arg, Locale locale )
  88.             throws IllegalOptionValueException {
  89.             if ( this.wantsValue ) {
  90.                 if ( arg == null ) {
  91.                     throw new IllegalOptionValueException(this, "");
  92.                 }
  93.                 return this.parseValue(arg, locale);
  94.             }
  95.             else {
  96.                 return Boolean.TRUE;
  97.             }
  98.         }
  99.         /**
  100.          * Override to extract and convert an option value passed on the
  101.          * command-line
  102.          */
  103.         protected Object parseValue( String arg, Locale locale )
  104.             throws IllegalOptionValueException {
  105.             return null;
  106.         }
  107.         private String shortForm = null;
  108.         private String longForm = null;
  109.         private boolean wantsValue = false;
  110.         public static class BooleanOption extends Option {
  111.             public BooleanOption( char shortForm, String longForm ) {
  112.                 super(shortForm, longForm, false);
  113.             }
  114.         }
  115.         /**
  116.          * An option that expects an integer value
  117.          */
  118.         public static class IntegerOption extends Option {
  119.             public IntegerOption( char shortForm, String longForm ) {
  120.                 super(shortForm, longForm, true);
  121.             }
  122.             protected Object parseValue( String arg, Locale locale )
  123.                 throws IllegalOptionValueException {
  124.                 try {
  125.                     return new Integer(arg);
  126.                 }
  127.                 catch (NumberFormatException e) {
  128.                     throw new IllegalOptionValueException(this, arg);
  129.                 }
  130.             }
  131.         }
  132.         /**
  133.          * An option that expects a floating-point value
  134.          */
  135.         public static class DoubleOption extends Option {
  136.             public DoubleOption( char shortForm, String longForm ) {
  137.                 super(shortForm, longForm, true);
  138.             }
  139.             protected Object parseValue( String arg, Locale locale )
  140.                 throws IllegalOptionValueException {
  141.                 try {
  142.                     NumberFormat format = NumberFormat.getNumberInstance(locale);
  143.                     Number num = (Number)format.parse(arg);
  144.                     return new Double(num.doubleValue());
  145.                 }
  146.                 catch (ParseException e) {
  147.                     throw new IllegalOptionValueException(this, arg);
  148.                 }
  149.             }
  150.         }
  151.         /**
  152.          * An option that expects a string value
  153.          */
  154.         public static class StringOption extends Option {
  155.             public StringOption( char shortForm, String longForm ) {
  156.                 super(shortForm, longForm, true);
  157.             }
  158.             protected Object parseValue( String arg, Locale locale ) {
  159.                 return arg;
  160.             }
  161.         }
  162.     }
  163.     /**
  164.      * Add the specified Option to the list of accepted options
  165.      */
  166.     public final Option addOption( Option opt ) {
  167.         this.options.put("-" + opt.shortForm(), opt);
  168.         this.options.put("--" + opt.longForm(), opt);
  169.         return opt;
  170.     }
  171.     /**
  172.      * Convenience method for adding a string option.
  173.      * @return the new Option
  174.      */
  175.     public final Option addStringOption( char shortForm, String longForm ) {
  176.         Option opt = new Option.StringOption(shortForm, longForm);
  177.         addOption(opt);
  178.         return opt;
  179.     }
  180.     /**
  181.      * Convenience method for adding an integer option.
  182.      * @return the new Option
  183.      */
  184.     public final Option addIntegerOption( char shortForm, String longForm ) {
  185.         Option opt = new Option.IntegerOption(shortForm, longForm);
  186.         addOption(opt);
  187.         return opt;
  188.     }
  189.     /**
  190.      * Convenience method for adding a double option.
  191.      * @return the new Option
  192.      */
  193.     public final Option addDoubleOption( char shortForm, String longForm ) {
  194.         Option opt = new Option.DoubleOption(shortForm, longForm);
  195.         addOption(opt);
  196.         return opt;
  197.     }
  198.     /**
  199.      * Convenience method for adding a boolean option.
  200.      * @return the new Option
  201.      */
  202.     public final Option addBooleanOption( char shortForm, String longForm ) {
  203.         Option opt = new Option.BooleanOption(shortForm, longForm);
  204.         addOption(opt);
  205.         return opt;
  206.     }
  207.     /**
  208.      * @return the parsed value of the given Option, or null if the
  209.      * option was not set
  210.      */
  211.     public final Object getOptionValue( Option o ) {
  212.         return values.get(o.longForm());
  213.     }
  214.     /**
  215.      * @return the parsed value of the given Option, or null if the
  216.      * option was not set
  217.      */
  218.     public final Object getOptionValue( Option o, Object defaultValue ) {
  219.      Object val = values.get(o.longForm());
  220.      return val == null ? defaultValue : val;
  221.     }
  222.     /**
  223.      * @return the non-option arguments
  224.      */
  225.     public final String[] getRemainingArgs() {
  226.         return this.remainingArgs;
  227.     }
  228.     /**
  229.      * Extract the options and non-option arguments from the given
  230.      * list of command-line arguments. The default locale is used for
  231.      * parsing options whose values might be locale-specific.
  232.      */
  233.     public final void parse( String[] argv )
  234.         throws IllegalOptionValueException, UnknownOptionException {
  235.         parse(argv, Locale.getDefault());
  236.     }
  237.     /**
  238.      * Extract the options and non-option arguments from the given
  239.      * list of command-line arguments. The specified locale is used for
  240.      * parsing options whose values might be locale-specific.
  241.      */
  242.     public final void parse( String[] argv, Locale locale )
  243.         throws IllegalOptionValueException, UnknownOptionException {
  244.         Vector otherArgs = new Vector();
  245.         int position = 0;
  246.         this.values = new Hashtable(10);
  247.         while ( position < argv.length ) {
  248.             String curArg = argv[position];
  249.             if ( curArg.startsWith("-") ) {
  250.                 if ( curArg.equals("--") ) { // end of options
  251.                     position += 1;
  252.                     break;
  253.                 }
  254.                 String valueArg = null;
  255.                 if ( curArg.startsWith("--") ) { // handle --arg=value
  256.                     int equalsPos = curArg.indexOf("=");
  257.                     if ( equalsPos != -1 ) {
  258.                         valueArg = curArg.substring(equalsPos+1);
  259.                         curArg = curArg.substring(0,equalsPos);
  260.                     }
  261.                 }
  262.                 Option opt = (Option)this.options.get(curArg);
  263.                 if ( opt == null ) {
  264.                     throw new UnknownOptionException(curArg);
  265.                 }
  266.                 Object value = null;
  267.                 if ( opt.wantsValue() ) {
  268.                     if ( valueArg == null ) {
  269.                         position += 1;
  270.                         valueArg = null;
  271.                         if ( position < argv.length ) {
  272.                             valueArg = argv[position];
  273.                         }
  274.                     }
  275.                     value = opt.getValue(valueArg, locale);
  276.                 }
  277.                 else {
  278.                     value = opt.getValue(null, locale);
  279.                 }
  280.                 this.values.put(opt.longForm(), value);
  281.                 position += 1;
  282.             }
  283.             else {
  284.                 break;
  285.             }
  286.         }
  287.         for ( ; position < argv.length; ++position ) {
  288.             otherArgs.addElement(argv[position]);
  289.         }
  290.         this.remainingArgs = new String[otherArgs.size()];
  291.         int i = 0;
  292.         for (Enumeration e = otherArgs.elements(); e.hasMoreElements(); ++i) {
  293.             this.remainingArgs[i] = (String)e.nextElement();
  294.         }
  295.     }
  296.     private String[] remainingArgs = null;
  297.     private Hashtable options = new Hashtable(10);
  298.     private Hashtable values = new Hashtable(10);
  299. }