DefaultParser.java

  1. /*
  2.   Licensed to the Apache Software Foundation (ASF) under one or more
  3.   contributor license agreements.  See the NOTICE file distributed with
  4.   this work for additional information regarding copyright ownership.
  5.   The ASF licenses this file to You under the Apache License, Version 2.0
  6.   (the "License"); you may not use this file except in compliance with
  7.   the License.  You may obtain a copy of the License at

  8.       http://www.apache.org/licenses/LICENSE-2.0

  9.   Unless required by applicable law or agreed to in writing, software
  10.   distributed under the License is distributed on an "AS IS" BASIS,
  11.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12.   See the License for the specific language governing permissions and
  13.   limitations under the License.
  14.  */

  15. package org.apache.commons.cli;

  16. import java.util.ArrayList;
  17. import java.util.Enumeration;
  18. import java.util.List;
  19. import java.util.Properties;
  20. import java.util.function.Consumer;

  21. /**
  22.  * Default parser.
  23.  *
  24.  * @since 1.3
  25.  */
  26. public class DefaultParser implements CommandLineParser {

  27.     /**
  28.      * A nested builder class to create {@code DefaultParser} instances
  29.      * using descriptive methods.
  30.      *
  31.      * Example usage:
  32.      * <pre>
  33.      * DefaultParser parser = Option.builder()
  34.      *     .setAllowPartialMatching(false)
  35.      *     .setStripLeadingAndTrailingQuotes(false)
  36.      *     .build();
  37.      * </pre>
  38.      *
  39.      * @since 1.5.0
  40.      */
  41.     public static final class Builder {

  42.         /** Flag indicating if partial matching of long options is supported. */
  43.         private boolean allowPartialMatching = true;

  44.         /**
  45.          * The deprecated option handler.
  46.          * <p>
  47.          * If you want to serialize this field, use a serialization proxy.
  48.          * </p>
  49.          */
  50.         private Consumer<Option> deprecatedHandler = CommandLine.Builder.DEPRECATED_HANDLER;

  51.         /** Flag indicating if balanced leading and trailing double quotes should be stripped from option arguments. */
  52.         private Boolean stripLeadingAndTrailingQuotes;

  53.         /**
  54.          * Constructs a new {@code Builder} for a {@code DefaultParser} instance.
  55.          *
  56.          * Both allowPartialMatching and stripLeadingAndTrailingQuotes are true by default,
  57.          * mimicking the argument-less constructor.
  58.          */
  59.         private Builder() {
  60.         }

  61.         /**
  62.          * Builds an DefaultParser with the values declared by this {@link Builder}.
  63.          *
  64.          * @return the new {@link DefaultParser}
  65.          * @since 1.5.0
  66.          */
  67.         public DefaultParser build() {
  68.             return new DefaultParser(allowPartialMatching, stripLeadingAndTrailingQuotes, deprecatedHandler);
  69.         }

  70.         /**
  71.          * Sets if partial matching of long options is supported.
  72.          *
  73.          * By "partial matching" we mean that given the following code:
  74.          *
  75.          * <pre>
  76.          * {
  77.          *     &#64;code
  78.          *     final Options options = new Options();
  79.          *     options.addOption(new Option("d", "debug", false, "Turn on debug."));
  80.          *     options.addOption(new Option("e", "extract", false, "Turn on extract."));
  81.          *     options.addOption(new Option("o", "option", true, "Turn on option with argument."));
  82.          * }
  83.          * </pre>
  84.          *
  85.          * If "partial matching" is turned on, {@code -de} only matches the {@code "debug"} option. However, with
  86.          * "partial matching" disabled, {@code -de} would enable both {@code debug} as well as {@code extract}
  87.          *
  88.          * @param allowPartialMatching whether to allow partial matching of long options
  89.          * @return this builder, to allow method chaining
  90.          * @since 1.5.0
  91.          */
  92.         public Builder setAllowPartialMatching(final boolean allowPartialMatching) {
  93.             this.allowPartialMatching = allowPartialMatching;
  94.             return this;
  95.         }

  96.         /**
  97.          * Sets the deprecated option handler.
  98.          *
  99.          * @param deprecatedHandler the deprecated option handler.
  100.          * @return {@code this} instance.
  101.          * @since 1.7.0
  102.          */
  103.         public Builder setDeprecatedHandler(final Consumer<Option> deprecatedHandler) {
  104.             this.deprecatedHandler = deprecatedHandler;
  105.             return this;
  106.         }

  107.         /**
  108.          * Sets if balanced leading and trailing double quotes should be stripped from option arguments.
  109.          *
  110.          * If "stripping of balanced leading and trailing double quotes from option arguments" is true,
  111.          * the outermost balanced double quotes of option arguments values will be removed.
  112.          * For example, {@code -o '"x"'} getValue() will return {@code x}, instead of {@code "x"}
  113.          *
  114.          * If "stripping of balanced leading and trailing double quotes from option arguments" is null,
  115.          * then quotes will be stripped from option values separated by space from the option, but
  116.          * kept in other cases, which is the historic behavior.
  117.          *
  118.          * @param stripLeadingAndTrailingQuotes whether balanced leading and trailing double quotes should be stripped from option arguments.
  119.          * @return this builder, to allow method chaining
  120.          * @since 1.5.0
  121.          */
  122.         public Builder setStripLeadingAndTrailingQuotes(final Boolean stripLeadingAndTrailingQuotes) {
  123.             this.stripLeadingAndTrailingQuotes = stripLeadingAndTrailingQuotes;
  124.             return this;
  125.         }
  126.     }

  127.     /**
  128.      * Creates a new {@link Builder} to create an {@link DefaultParser} using descriptive
  129.      * methods.
  130.      *
  131.      * @return a new {@link Builder} instance
  132.      * @since 1.5.0
  133.      */
  134.     public static Builder builder() {
  135.         return new Builder();
  136.     }

  137.     static int indexOfEqual(final String token) {
  138.         return token.indexOf(Char.EQUAL);
  139.     }

  140.     /** The command-line instance. */
  141.     protected CommandLine cmd;

  142.     /** The current options. */
  143.     protected Options options;

  144.     /**
  145.      * Flag indicating how unrecognized tokens are handled. {@code true} to stop the parsing and add the remaining
  146.      * tokens to the args list. {@code false} to throw an exception.
  147.      */
  148.     protected boolean stopAtNonOption;

  149.     /** The token currently processed. */
  150.     protected String currentToken;

  151.     /** The last option parsed. */
  152.     protected Option currentOption;

  153.     /** Flag indicating if tokens should no longer be analyzed and simply added as arguments of the command line. */
  154.     protected boolean skipParsing;

  155.     /** The required options and groups expected to be found when parsing the command line. */
  156.     protected List expectedOpts;

  157.     /** Flag indicating if partial matching of long options is supported. */
  158.     private final boolean allowPartialMatching;

  159.     /** Flag indicating if balanced leading and trailing double quotes should be stripped from option arguments.
  160.      * null represents the historic arbitrary behavior */
  161.     private final Boolean stripLeadingAndTrailingQuotes;

  162.     /**
  163.      * The deprecated option handler.
  164.      * <p>
  165.      * If you want to serialize this field, use a serialization proxy.
  166.      * </p>
  167.      */
  168.     private final Consumer<Option> deprecatedHandler;

  169.     /**
  170.      * Creates a new DefaultParser instance with partial matching enabled.
  171.      *
  172.      * By "partial matching" we mean that given the following code:
  173.      *
  174.      * <pre>
  175.      * {
  176.      *     &#64;code
  177.      *     final Options options = new Options();
  178.      *     options.addOption(new Option("d", "debug", false, "Turn on debug."));
  179.      *     options.addOption(new Option("e", "extract", false, "Turn on extract."));
  180.      *     options.addOption(new Option("o", "option", true, "Turn on option with argument."));
  181.      * }
  182.      * </pre>
  183.      *
  184.      * with "partial matching" turned on, {@code -de} only matches the {@code "debug"} option. However, with
  185.      * "partial matching" disabled, {@code -de} would enable both {@code debug} as well as {@code extract}
  186.      * options.
  187.      */
  188.     public DefaultParser() {
  189.         this.allowPartialMatching = true;
  190.         this.stripLeadingAndTrailingQuotes = null;
  191.         this.deprecatedHandler = CommandLine.Builder.DEPRECATED_HANDLER;
  192.     }

  193.     /**
  194.      * Create a new DefaultParser instance with the specified partial matching policy.
  195.      *
  196.      * By "partial matching" we mean that given the following code:
  197.      *
  198.      * <pre>
  199.      * {
  200.      *     &#64;code
  201.      *     final Options options = new Options();
  202.      *     options.addOption(new Option("d", "debug", false, "Turn on debug."));
  203.      *     options.addOption(new Option("e", "extract", false, "Turn on extract."));
  204.      *     options.addOption(new Option("o", "option", true, "Turn on option with argument."));
  205.      * }
  206.      * </pre>
  207.      *
  208.      * with "partial matching" turned on, {@code -de} only matches the {@code "debug"} option. However, with
  209.      * "partial matching" disabled, {@code -de} would enable both {@code debug} as well as {@code extract}
  210.      * options.
  211.      *
  212.      * @param allowPartialMatching if partial matching of long options shall be enabled
  213.      */
  214.     public DefaultParser(final boolean allowPartialMatching) {
  215.         this.allowPartialMatching = allowPartialMatching;
  216.         this.stripLeadingAndTrailingQuotes = null;
  217.         this.deprecatedHandler = CommandLine.Builder.DEPRECATED_HANDLER;
  218.     }

  219.     /**
  220.      * Creates a new DefaultParser instance with the specified partial matching and quote
  221.      * stripping policy.
  222.      *
  223.      * @param allowPartialMatching if partial matching of long options shall be enabled
  224.      * @param stripLeadingAndTrailingQuotes if balanced outer double quoutes should be stripped
  225.      */
  226.     private DefaultParser(final boolean allowPartialMatching, final Boolean stripLeadingAndTrailingQuotes, final Consumer<Option> deprecatedHandler) {
  227.         this.allowPartialMatching = allowPartialMatching;
  228.         this.stripLeadingAndTrailingQuotes = stripLeadingAndTrailingQuotes;
  229.         this.deprecatedHandler = deprecatedHandler;
  230.     }

  231.     /**
  232.      * Throws a {@link MissingArgumentException} if the current option didn't receive the number of arguments expected.
  233.      */
  234.     private void checkRequiredArgs() throws ParseException {
  235.         if (currentOption != null && currentOption.requiresArg()) {
  236.             if (isJavaProperty(currentOption.getKey()) && currentOption.getValuesList().size() == 1) {
  237.                 return;
  238.             }
  239.             throw new MissingArgumentException(currentOption);
  240.         }
  241.     }

  242.     /**
  243.      * Throws a {@link MissingOptionException} if all of the required options are not present.
  244.      *
  245.      * @throws MissingOptionException if any of the required Options are not present.
  246.      */
  247.     protected void checkRequiredOptions() throws MissingOptionException {
  248.         // if there are required options that have not been processed
  249.         if (!expectedOpts.isEmpty()) {
  250.             throw new MissingOptionException(expectedOpts);
  251.         }
  252.     }

  253.     /**
  254.      * Searches for a prefix that is the long name of an option (-Xmx512m)
  255.      *
  256.      * @param token
  257.      */
  258.     private String getLongPrefix(final String token) {
  259.         final String t = Util.stripLeadingHyphens(token);
  260.         int i;
  261.         String opt = null;
  262.         for (i = t.length() - 2; i > 1; i--) {
  263.             final String prefix = t.substring(0, i);
  264.             if (options.hasLongOption(prefix)) {
  265.                 opt = prefix;
  266.                 break;
  267.             }
  268.         }
  269.         return opt;
  270.     }

  271.     /**
  272.      * Gets a list of matching option strings for the given token, depending on the selected partial matching policy.
  273.      *
  274.      * @param token the token (may contain leading dashes)
  275.      * @return the list of matching option strings or an empty list if no matching option could be found
  276.      */
  277.     private List<String> getMatchingLongOptions(final String token) {
  278.         if (allowPartialMatching) {
  279.             return options.getMatchingOptions(token);
  280.         }
  281.         final List<String> matches = new ArrayList<>(1);
  282.         if (options.hasLongOption(token)) {
  283.             matches.add(options.getOption(token).getLongOpt());
  284.         }
  285.         return matches;
  286.     }

  287.     /**
  288.      * Breaks {@code token} into its constituent parts using the following algorithm.
  289.      *
  290.      * <ul>
  291.      * <li>ignore the first character ("<b>-</b>")</li>
  292.      * <li>for each remaining character check if an {@link Option} exists with that id.</li>
  293.      * <li>if an {@link Option} does exist then add that character prepended with "<b>-</b>" to the list of processed
  294.      * tokens.</li>
  295.      * <li>if the {@link Option} can have an argument value and there are remaining characters in the token then add the
  296.      * remaining characters as a token to the list of processed tokens.</li>
  297.      * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> {@code stopAtNonOption} <b>IS</b> set then add the
  298.      * special token "<b>--</b>" followed by the remaining characters and also the remaining tokens directly to the
  299.      * processed tokens list.</li>
  300.      * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> {@code stopAtNonOption} <b>IS NOT</b> set then add
  301.      * that character prepended with "<b>-</b>".</li>
  302.      * </ul>
  303.      *
  304.      * @param token The current token to be <b>burst</b> at the first non-Option encountered.
  305.      * @throws ParseException if there are any problems encountered while parsing the command line token.
  306.      */
  307.     protected void handleConcatenatedOptions(final String token) throws ParseException {
  308.         for (int i = 1; i < token.length(); i++) {
  309.             final String ch = String.valueOf(token.charAt(i));
  310.             if (!options.hasOption(ch)) {
  311.                 handleUnknownToken(stopAtNonOption && i > 1 ? token.substring(i) : token);
  312.                 break;
  313.             }
  314.             handleOption(options.getOption(ch));
  315.             if (currentOption != null && token.length() != i + 1) {
  316.                 // add the trail as an argument of the option
  317.                 currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(token.substring(i + 1)));
  318.                 break;
  319.             }
  320.         }
  321.     }

  322.     /**
  323.      * Handles the following tokens:
  324.      *
  325.      * --L --L=V --L V --l
  326.      *
  327.      * @param token the command line token to handle
  328.      */
  329.     private void handleLongOption(final String token) throws ParseException {
  330.         if (indexOfEqual(token) == -1) {
  331.             handleLongOptionWithoutEqual(token);
  332.         } else {
  333.             handleLongOptionWithEqual(token);
  334.         }
  335.     }

  336.     /**
  337.      * Handles the following tokens:
  338.      *
  339.      * --L=V -L=V --l=V -l=V
  340.      *
  341.      * @param token the command line token to handle
  342.      */
  343.     private void handleLongOptionWithEqual(final String token) throws ParseException {
  344.         final int pos = indexOfEqual(token);
  345.         final String value = token.substring(pos + 1);
  346.         final String opt = token.substring(0, pos);
  347.         final List<String> matchingOpts = getMatchingLongOptions(opt);
  348.         if (matchingOpts.isEmpty()) {
  349.             handleUnknownToken(currentToken);
  350.         } else if (matchingOpts.size() > 1 && !options.hasLongOption(opt)) {
  351.             throw new AmbiguousOptionException(opt, matchingOpts);
  352.         } else {
  353.             final String key = options.hasLongOption(opt) ? opt : matchingOpts.get(0);
  354.             final Option option = options.getOption(key);
  355.             if (option.acceptsArg()) {
  356.                 handleOption(option);
  357.                 currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(value));
  358.                 currentOption = null;
  359.             } else {
  360.                 handleUnknownToken(currentToken);
  361.             }
  362.         }
  363.     }

  364.     /**
  365.      * Handles the following tokens:
  366.      *
  367.      * --L -L --l -l
  368.      *
  369.      * @param token the command line token to handle
  370.      */
  371.     private void handleLongOptionWithoutEqual(final String token) throws ParseException {
  372.         final List<String> matchingOpts = getMatchingLongOptions(token);
  373.         if (matchingOpts.isEmpty()) {
  374.             handleUnknownToken(currentToken);
  375.         } else if (matchingOpts.size() > 1 && !options.hasLongOption(token)) {
  376.             throw new AmbiguousOptionException(token, matchingOpts);
  377.         } else {
  378.             final String key = options.hasLongOption(token) ? token : matchingOpts.get(0);
  379.             handleOption(options.getOption(key));
  380.         }
  381.     }

  382.     private void handleOption(final Option option) throws ParseException {
  383.         // check the previous option before handling the next one
  384.         checkRequiredArgs();
  385.         final Option copy = (Option) option.clone();
  386.         updateRequiredOptions(copy);
  387.         cmd.addOption(copy);
  388.         currentOption = copy.hasArg() ? copy : null;
  389.     }

  390.     /**
  391.      * Sets the values of Options using the values in {@code properties}.
  392.      *
  393.      * @param properties The value properties to be processed.
  394.      */
  395.     private void handleProperties(final Properties properties) throws ParseException {
  396.         if (properties == null) {
  397.             return;
  398.         }
  399.         for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
  400.             final String option = e.nextElement().toString();
  401.             final Option opt = options.getOption(option);
  402.             if (opt == null) {
  403.                 throw new UnrecognizedOptionException("Default option wasn't defined", option);
  404.             }
  405.             // if the option is part of a group, check if another option of the group has been selected
  406.             final OptionGroup group = options.getOptionGroup(opt);
  407.             final boolean selected = group != null && group.isSelected();
  408.             if (!cmd.hasOption(option) && !selected) {
  409.                 // get the value from the properties
  410.                 final String value = properties.getProperty(option);

  411.                 if (opt.hasArg()) {
  412.                     if (Util.isEmpty(opt.getValues())) {
  413.                         opt.processValue(stripLeadingAndTrailingQuotesDefaultOff(value));
  414.                     }
  415.                 } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) {
  416.                     // if the value is not yes, true or 1 then don't add the option to the CommandLine
  417.                     continue;
  418.                 }
  419.                 handleOption(opt);
  420.                 currentOption = null;
  421.             }
  422.         }
  423.     }

  424.     /**
  425.      * Handles the following tokens:
  426.      *
  427.      * -S -SV -S V -S=V -S1S2 -S1S2 V -SV1=V2
  428.      *
  429.      * -L -LV -L V -L=V -l
  430.      *
  431.      * @param hyphenToken the command line token to handle
  432.      */
  433.     private void handleShortAndLongOption(final String hyphenToken) throws ParseException {
  434.         final String token = Util.stripLeadingHyphens(hyphenToken);
  435.         final int pos = indexOfEqual(token);
  436.         if (token.length() == 1) {
  437.             // -S
  438.             if (options.hasShortOption(token)) {
  439.                 handleOption(options.getOption(token));
  440.             } else {
  441.                 handleUnknownToken(hyphenToken);
  442.             }
  443.         } else if (pos == -1) {
  444.             // no equal sign found (-xxx)
  445.             if (options.hasShortOption(token)) {
  446.                 handleOption(options.getOption(token));
  447.             } else if (!getMatchingLongOptions(token).isEmpty()) {
  448.                 // -L or -l
  449.                 handleLongOptionWithoutEqual(hyphenToken);
  450.             } else {
  451.                 // look for a long prefix (-Xmx512m)
  452.                 final String opt = getLongPrefix(token);

  453.                 if (opt != null && options.getOption(opt).acceptsArg()) {
  454.                     handleOption(options.getOption(opt));
  455.                     currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(token.substring(opt.length())));
  456.                     currentOption = null;
  457.                 } else if (isJavaProperty(token)) {
  458.                     // -SV1 (-Dflag)
  459.                     handleOption(options.getOption(token.substring(0, 1)));
  460.                     currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(token.substring(1)));
  461.                     currentOption = null;
  462.                 } else {
  463.                     // -S1S2S3 or -S1S2V
  464.                     handleConcatenatedOptions(hyphenToken);
  465.                 }
  466.             }
  467.         } else {
  468.             // equal sign found (-xxx=yyy)
  469.             final String opt = token.substring(0, pos);
  470.             final String value = token.substring(pos + 1);

  471.             if (opt.length() == 1) {
  472.                 // -S=V
  473.                 final Option option = options.getOption(opt);
  474.                 if (option != null && option.acceptsArg()) {
  475.                     handleOption(option);
  476.                     currentOption.processValue(value);
  477.                     currentOption = null;
  478.                 } else {
  479.                     handleUnknownToken(hyphenToken);
  480.                 }
  481.             } else if (isJavaProperty(opt)) {
  482.                 // -SV1=V2 (-Dkey=value)
  483.                 handleOption(options.getOption(opt.substring(0, 1)));
  484.                 currentOption.processValue(opt.substring(1));
  485.                 currentOption.processValue(value);
  486.                 currentOption = null;
  487.             } else {
  488.                 // -L=V or -l=V
  489.                 handleLongOptionWithEqual(hyphenToken);
  490.             }
  491.         }
  492.     }

  493.     /**
  494.      * Handles any command line token.
  495.      *
  496.      * @param token the command line token to handle
  497.      * @throws ParseException
  498.      */
  499.     private void handleToken(final String token) throws ParseException {
  500.         if (token != null) {
  501.             currentToken = token;
  502.             if (skipParsing) {
  503.                 cmd.addArg(token);
  504.             } else if ("--".equals(token)) {
  505.                 skipParsing = true;
  506.             } else if (currentOption != null && currentOption.acceptsArg() && isArgument(token)) {
  507.                 currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOn(token));
  508.             } else if (token.startsWith("--")) {
  509.                 handleLongOption(token);
  510.             } else if (token.startsWith("-") && !"-".equals(token)) {
  511.                 handleShortAndLongOption(token);
  512.             } else {
  513.                 handleUnknownToken(token);
  514.             }
  515.             if (currentOption != null && !currentOption.acceptsArg()) {
  516.                 currentOption = null;
  517.             }
  518.         }
  519.     }

  520.     /**
  521.      * Handles an unknown token. If the token starts with a dash an UnrecognizedOptionException is thrown. Otherwise the
  522.      * token is added to the arguments of the command line. If the stopAtNonOption flag is set, this stops the parsing and
  523.      * the remaining tokens are added as-is in the arguments of the command line.
  524.      *
  525.      * @param token the command line token to handle
  526.      */
  527.     private void handleUnknownToken(final String token) throws ParseException {
  528.         if (token.startsWith("-") && token.length() > 1 && !stopAtNonOption) {
  529.             throw new UnrecognizedOptionException("Unrecognized option: " + token, token);
  530.         }
  531.         cmd.addArg(token);
  532.         if (stopAtNonOption) {
  533.             skipParsing = true;
  534.         }
  535.     }

  536.     /**
  537.      * Tests if the token is a valid argument.
  538.      *
  539.      * @param token
  540.      */
  541.     private boolean isArgument(final String token) {
  542.         return !isOption(token) || isNegativeNumber(token);
  543.     }

  544.     /**
  545.      * Tests if the specified token is a Java-like property (-Dkey=value).
  546.      */
  547.     private boolean isJavaProperty(final String token) {
  548.         final String opt = token.isEmpty() ? null : token.substring(0, 1);
  549.         final Option option = options.getOption(opt);
  550.         return option != null && (option.getArgs() >= 2 || option.getArgs() == Option.UNLIMITED_VALUES);
  551.     }

  552.     /**
  553.      * Tests if the token looks like a long option.
  554.      *
  555.      * @param token
  556.      */
  557.     private boolean isLongOption(final String token) {
  558.         if (token == null || !token.startsWith("-") || token.length() == 1) {
  559.             return false;
  560.         }
  561.         final int pos = indexOfEqual(token);
  562.         final String t = pos == -1 ? token : token.substring(0, pos);
  563.         if (!getMatchingLongOptions(t).isEmpty()) {
  564.             // long or partial long options (--L, -L, --L=V, -L=V, --l, --l=V)
  565.             return true;
  566.         }
  567.         if (getLongPrefix(token) != null && !token.startsWith("--")) {
  568.             // -LV
  569.             return true;
  570.         }
  571.         return false;
  572.     }

  573.     /**
  574.      * Tests if the token is a negative number.
  575.      *
  576.      * @param token
  577.      */
  578.     private boolean isNegativeNumber(final String token) {
  579.         try {
  580.             Double.parseDouble(token);
  581.             return true;
  582.         } catch (final NumberFormatException e) {
  583.             return false;
  584.         }
  585.     }

  586.     /**
  587.      * Tests if the token looks like an option.
  588.      *
  589.      * @param token
  590.      */
  591.     private boolean isOption(final String token) {
  592.         return isLongOption(token) || isShortOption(token);
  593.     }

  594.     /**
  595.      * Tests if the token looks like a short option.
  596.      *
  597.      * @param token
  598.      */
  599.     private boolean isShortOption(final String token) {
  600.         // short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
  601.         if (token == null || !token.startsWith("-") || token.length() == 1) {
  602.             return false;
  603.         }
  604.         // remove leading "-" and "=value"
  605.         final int pos = indexOfEqual(token);
  606.         final String optName = pos == -1 ? token.substring(1) : token.substring(1, pos);
  607.         if (options.hasShortOption(optName)) {
  608.             return true;
  609.         }
  610.         // check for several concatenated short options
  611.         return !optName.isEmpty() && options.hasShortOption(String.valueOf(optName.charAt(0)));
  612.     }

  613.     @Override
  614.     public CommandLine parse(final Options options, final String[] arguments) throws ParseException {
  615.         return parse(options, arguments, null);
  616.     }

  617.     @Override
  618.     public CommandLine parse(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException {
  619.         return parse(options, arguments, null, stopAtNonOption);
  620.     }

  621.     /**
  622.      * Parses the arguments according to the specified options and properties.
  623.      *
  624.      * @param options the specified Options
  625.      * @param arguments the command line arguments
  626.      * @param properties command line option name-value pairs
  627.      * @return the list of atomic option and value tokens
  628.      *
  629.      * @throws ParseException if there are any problems encountered while parsing the command line tokens.
  630.      */
  631.     public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException {
  632.         return parse(options, arguments, properties, false);
  633.     }

  634.     /**
  635.      * Parses the arguments according to the specified options and properties.
  636.      *
  637.      * @param options the specified Options
  638.      * @param arguments the command line arguments
  639.      * @param properties command line option name-value pairs
  640.      * @param stopAtNonOption if {@code true} an unrecognized argument stops the parsing and the remaining arguments
  641.      *        are added to the {@link CommandLine}s args list. If {@code false} an unrecognized argument triggers a
  642.      *        ParseException.
  643.      *
  644.      * @return the list of atomic option and value tokens
  645.      * @throws ParseException if there are any problems encountered while parsing the command line tokens.
  646.      */
  647.     public CommandLine parse(final Options options, final String[] arguments, final Properties properties, final boolean stopAtNonOption)
  648.         throws ParseException {
  649.         this.options = options;
  650.         this.stopAtNonOption = stopAtNonOption;
  651.         skipParsing = false;
  652.         currentOption = null;
  653.         expectedOpts = new ArrayList<>(options.getRequiredOptions());
  654.         // clear the data from the groups
  655.         for (final OptionGroup group : options.getOptionGroups()) {
  656.             group.setSelected(null);
  657.         }
  658.         cmd = CommandLine.builder().setDeprecatedHandler(deprecatedHandler).build();
  659.         if (arguments != null) {
  660.             for (final String argument : arguments) {
  661.                 handleToken(argument);
  662.             }
  663.         }
  664.         // check the arguments of the last option
  665.         checkRequiredArgs();
  666.         // add the default options
  667.         handleProperties(properties);
  668.         checkRequiredOptions();
  669.         return cmd;
  670.     }

  671.     /**
  672.      * Strips balanced leading and trailing quotes if the stripLeadingAndTrailingQuotes is set
  673.      * If stripLeadingAndTrailingQuotes is null, then do not strip
  674.      *
  675.      * @param token a string
  676.      * @return token with the quotes stripped (if set)
  677.      */
  678.     private String stripLeadingAndTrailingQuotesDefaultOff(final String token) {
  679.         if (stripLeadingAndTrailingQuotes != null && stripLeadingAndTrailingQuotes) {
  680.             return Util.stripLeadingAndTrailingQuotes(token);
  681.         }
  682.         return token;
  683.     }

  684.     /**
  685.      * Strips balanced leading and trailing quotes if the stripLeadingAndTrailingQuotes is set
  686.      * If stripLeadingAndTrailingQuotes is null, then do not strip
  687.      *
  688.      * @param token a string
  689.      * @return token with the quotes stripped (if set)
  690.      */
  691.     private String stripLeadingAndTrailingQuotesDefaultOn(final String token) {
  692.         if (stripLeadingAndTrailingQuotes == null || stripLeadingAndTrailingQuotes) {
  693.             return Util.stripLeadingAndTrailingQuotes(token);
  694.         }
  695.         return token;
  696.     }

  697.     /**
  698.      * Removes the option or its group from the list of expected elements.
  699.      *
  700.      * @param option
  701.      */
  702.     private void updateRequiredOptions(final Option option) throws AlreadySelectedException {
  703.         if (option.isRequired()) {
  704.             expectedOpts.remove(option.getKey());
  705.         }

  706.         // if the option is in an OptionGroup make that option the selected option of the group
  707.         if (options.getOptionGroup(option) != null) {
  708.             final OptionGroup group = options.getOptionGroup(option);

  709.             if (group.isRequired()) {
  710.                 expectedOpts.remove(group);
  711.             }

  712.             group.setSelected(option);
  713.         }
  714.     }
  715. }