View Javadoc
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   
9         https://www.apache.org/licenses/LICENSE-2.0
10  
11    Unless required by applicable law or agreed to in writing, software
12    distributed under the License is distributed on an "AS IS" BASIS,
13    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14    See the License for the specific language governing permissions and
15    limitations under the License.
16   */
17  
18  package org.apache.commons.cli;
19  
20  import java.util.ArrayList;
21  import java.util.Enumeration;
22  import java.util.List;
23  import java.util.Objects;
24  import java.util.Properties;
25  import java.util.function.Consumer;
26  import java.util.function.Supplier;
27  
28  /**
29   * Default parser.
30   *
31   * @since 1.3
32   */
33  public class DefaultParser implements CommandLineParser {
34  
35      /**
36       * A nested builder class to create {@code DefaultParser} instances
37       * using descriptive methods.
38       *
39       * Example usage:
40       * <pre>
41       * DefaultParser parser = Option.builder()
42       *     .setAllowPartialMatching(false)
43       *     .setStripLeadingAndTrailingQuotes(false)
44       *     .build();
45       * </pre>
46       *
47       * @since 1.5.0
48       */
49      public static final class Builder implements Supplier<DefaultParser> {
50  
51          /** Flag indicating if partial matching of long options is supported. */
52          private boolean allowPartialMatching = true;
53  
54          /**
55           * The deprecated option handler.
56           * <p>
57           * If you want to serialize this field, use a serialization proxy.
58           * </p>
59           */
60          private Consumer<Option> deprecatedHandler = CommandLine.Builder.DEPRECATED_HANDLER;
61  
62          /** Flag indicating if balanced leading and trailing double quotes should be stripped from option arguments. */
63          private Boolean stripLeadingAndTrailingQuotes;
64  
65          /**
66           * Constructs a new {@code Builder} for a {@code DefaultParser} instance.
67           *
68           * Both allowPartialMatching and stripLeadingAndTrailingQuotes are true by default,
69           * mimicking the argument-less constructor.
70           */
71          private Builder() {
72          }
73  
74          /**
75           * Builds an DefaultParser with the values declared by this {@link Builder}.
76           *
77           * @return the new {@link DefaultParser}.
78           * @since 1.5.0
79           * @deprecated Use {@link #get()}.
80           */
81          @Deprecated
82          public DefaultParser build() {
83              return get();
84          }
85  
86          /**
87           * Builds an DefaultParser with the values declared by this {@link Builder}.
88           *
89           * @return the new {@link DefaultParser}.
90           * @since 1.10.0
91           */
92          @Override
93          public DefaultParser get() {
94              return new DefaultParser(allowPartialMatching, stripLeadingAndTrailingQuotes, deprecatedHandler);
95          }
96  
97          /**
98           * Sets if partial matching of long options is supported.
99           *
100          * By "partial matching" we mean that given the following code:
101          *
102          * <pre>
103          * {
104          *     &#64;code
105          *     final Options options = new Options();
106          *     options.addOption(new Option("d", "debug", false, "Turn on debug."));
107          *     options.addOption(new Option("e", "extract", false, "Turn on extract."));
108          *     options.addOption(new Option("o", "option", true, "Turn on option with argument."));
109          * }
110          * </pre>
111          *
112          * If "partial matching" is turned on, {@code -de} only matches the {@code "debug"} option. However, with
113          * "partial matching" disabled, {@code -de} would enable both {@code debug} as well as {@code extract}
114          *
115          * @param allowPartialMatching whether to allow partial matching of long options.
116          * @return {@code this} instance..
117          * @since 1.5.0
118          */
119         public Builder setAllowPartialMatching(final boolean allowPartialMatching) {
120             this.allowPartialMatching = allowPartialMatching;
121             return this;
122         }
123 
124         /**
125          * Sets the deprecated option handler.
126          *
127          * @param deprecatedHandler the deprecated option handler.
128          * @return {@code this} instance.
129          * @since 1.7.0
130          */
131         public Builder setDeprecatedHandler(final Consumer<Option> deprecatedHandler) {
132             this.deprecatedHandler = deprecatedHandler;
133             return this;
134         }
135 
136         /**
137          * Sets if balanced leading and trailing double quotes should be stripped from option arguments.
138          *
139          * If "stripping of balanced leading and trailing double quotes from option arguments" is true,
140          * the outermost balanced double quotes of option arguments values will be removed.
141          * For example, {@code -o '"x"'} getValue() will return {@code x}, instead of {@code "x"}
142          *
143          * If "stripping of balanced leading and trailing double quotes from option arguments" is null,
144          * then quotes will be stripped from option values separated by space from the option, but
145          * kept in other cases, which is the historic behavior.
146          *
147          * @param stripLeadingAndTrailingQuotes whether balanced leading and trailing double quotes should be stripped from option arguments.
148          * @return {@code this} instance.
149          * @since 1.5.0
150          */
151         public Builder setStripLeadingAndTrailingQuotes(final Boolean stripLeadingAndTrailingQuotes) {
152             this.stripLeadingAndTrailingQuotes = stripLeadingAndTrailingQuotes;
153             return this;
154         }
155     }
156 
157     /**
158      * Enum representing possible actions that may be done when "non option" is discovered during parsing.
159      *
160      * @since 1.10.0
161      */
162     public enum NonOptionAction {
163         /**
164          * Parsing continues and current token is ignored.
165          */
166         IGNORE,
167         /**
168          * Parsing continues and current token is added to command line arguments.
169          */
170         SKIP,
171         /**
172          * Parsing will stop and remaining tokens are added to command line arguments.
173          * Equivalent of {@code stopAtNonOption = true}.
174          */
175         STOP,
176         /**
177          * Parsing will abort and exception is thrown.
178          * Equivalent of {@code stopAtNonOption = false}.
179          */
180         THROW;
181     }
182 
183     /**
184      * Creates a new {@link Builder} to create an {@link DefaultParser} using descriptive
185      * methods.
186      *
187      * @return a new {@link Builder} instance
188      * @since 1.5.0
189      */
190     public static Builder builder() {
191         return new Builder();
192     }
193 
194     static int indexOfEqual(final String token) {
195         return token.indexOf(Char.EQUAL);
196     }
197 
198     /** The command-line instance. */
199     protected CommandLine cmd;
200 
201     /** The current options. */
202     protected Options options;
203 
204     /**
205      * Flag indicating how unrecognized tokens are handled. {@code true} to stop the parsing and add the remaining
206      * tokens to the args list. {@code false} to throw an exception.
207      *
208      * @deprecated Use {@link #nonOptionAction} instead. This field is unused, and left for binary compatibility reasons.
209      */
210     @Deprecated
211     protected boolean stopAtNonOption;
212 
213     /**
214      * Action to happen when "non option" token is discovered.
215      *
216      * @since 1.10.0
217      */
218     protected NonOptionAction nonOptionAction;
219 
220     /** The token currently processed. */
221     protected String currentToken;
222 
223     /** The last option parsed. */
224     protected Option currentOption;
225 
226     /** Flag indicating if tokens should no longer be analyzed and simply added as arguments of the command line. */
227     protected boolean skipParsing;
228 
229     /** The required options and groups expected to be found when parsing the command line. */
230     // This can contain either a String (addOption) or an OptionGroup (addOptionGroup)
231     // TODO this seems wrong
232     protected List expectedOpts;
233 
234     /** Flag indicating if partial matching of long options is supported. */
235     private final boolean allowPartialMatching;
236 
237     /** Flag indicating if balanced leading and trailing double quotes should be stripped from option arguments.
238      * null represents the historic arbitrary behavior */
239     private final Boolean stripLeadingAndTrailingQuotes;
240 
241     /**
242      * The deprecated option handler.
243      * <p>
244      * If you want to serialize this field, use a serialization proxy.
245      * </p>
246      */
247     private final Consumer<Option> deprecatedHandler;
248 
249     /**
250      * Creates a new DefaultParser instance with partial matching enabled.
251      *
252      * By "partial matching" we mean that given the following code:
253      *
254      * <pre>
255      * {
256      *     &#64;code
257      *     final Options options = new Options();
258      *     options.addOption(new Option("d", "debug", false, "Turn on debug."));
259      *     options.addOption(new Option("e", "extract", false, "Turn on extract."));
260      *     options.addOption(new Option("o", "option", true, "Turn on option with argument."));
261      * }
262      * </pre>
263      *
264      * with "partial matching" turned on, {@code -de} only matches the {@code "debug"} option. However, with
265      * "partial matching" disabled, {@code -de} would enable both {@code debug} as well as {@code extract}
266      * options.
267      */
268     public DefaultParser() {
269         this.allowPartialMatching = true;
270         this.stripLeadingAndTrailingQuotes = null;
271         this.deprecatedHandler = CommandLine.Builder.DEPRECATED_HANDLER;
272     }
273 
274     /**
275      * Create a new DefaultParser instance with the specified partial matching policy.
276      *
277      * By "partial matching" we mean that given the following code:
278      *
279      * <pre>
280      * {
281      *     &#64;code
282      *     final Options options = new Options();
283      *     options.addOption(new Option("d", "debug", false, "Turn on debug."));
284      *     options.addOption(new Option("e", "extract", false, "Turn on extract."));
285      *     options.addOption(new Option("o", "option", true, "Turn on option with argument."));
286      * }
287      * </pre>
288      *
289      * with "partial matching" turned on, {@code -de} only matches the {@code "debug"} option. However, with
290      * "partial matching" disabled, {@code -de} would enable both {@code debug} as well as {@code extract}
291      * options.
292      *
293      * @param allowPartialMatching if partial matching of long options shall be enabled
294      */
295     public DefaultParser(final boolean allowPartialMatching) {
296         this.allowPartialMatching = allowPartialMatching;
297         this.stripLeadingAndTrailingQuotes = null;
298         this.deprecatedHandler = CommandLine.Builder.DEPRECATED_HANDLER;
299     }
300 
301     /**
302      * Creates a new DefaultParser instance with the specified partial matching and quote
303      * stripping policy.
304      *
305      * @param allowPartialMatching if partial matching of long options shall be enabled
306      * @param stripLeadingAndTrailingQuotes if balanced outer double quoutes should be stripped
307      */
308     private DefaultParser(final boolean allowPartialMatching, final Boolean stripLeadingAndTrailingQuotes, final Consumer<Option> deprecatedHandler) {
309         this.allowPartialMatching = allowPartialMatching;
310         this.stripLeadingAndTrailingQuotes = stripLeadingAndTrailingQuotes;
311         this.deprecatedHandler = deprecatedHandler;
312     }
313 
314     /**
315      * Adds token to command line {@link CommandLine#addArg(String)}.
316      *
317      * @param token the unrecognized option/argument.
318      * @since 1.10.0
319      */
320     protected void addArg(final String token) {
321         cmd.addArg(token);
322     }
323 
324     /**
325      * Throws a {@link MissingArgumentException} if the current option didn't receive the number of arguments expected.
326      */
327     private void checkRequiredArgs() throws ParseException {
328         if (currentOption != null && currentOption.requiresArg()) {
329             if (isJavaProperty(currentOption.getKey()) && currentOption.getValuesList().size() == 1) {
330                 return;
331             }
332             throw new MissingArgumentException(currentOption);
333         }
334     }
335 
336     /**
337      * Throws a {@link MissingOptionException} if all of the required options are not present.
338      *
339      * @throws MissingOptionException if any of the required Options are not present.
340      */
341     protected void checkRequiredOptions() throws MissingOptionException {
342         // if there are required options that have not been processed
343         if (!expectedOpts.isEmpty()) {
344             throw new MissingOptionException(expectedOpts);
345         }
346     }
347 
348     /**
349      * Searches for a prefix that is the long name of an option (-Xmx512m).
350      *
351      * @param token
352      */
353     private String getLongPrefix(final String token) {
354         final String t = Util.stripLeadingHyphens(token);
355         int i;
356         String opt = null;
357         for (i = t.length() - 2; i > 1; i--) {
358             final String prefix = t.substring(0, i);
359             if (options.hasLongOption(prefix)) {
360                 opt = prefix;
361                 break;
362             }
363         }
364         return opt;
365     }
366 
367     /**
368      * Gets a list of matching option strings for the given token, depending on the selected partial matching policy.
369      *
370      * @param token the token (may contain leading dashes).
371      * @return the list of matching option strings or an empty list if no matching option could be found.
372      */
373     private List<String> getMatchingLongOptions(final String token) {
374         if (allowPartialMatching) {
375             return options.getMatchingOptions(token);
376         }
377         final List<String> matches = new ArrayList<>(1);
378         if (options.hasLongOption(token)) {
379             matches.add(options.getOption(token).getLongOpt());
380         }
381         return matches;
382     }
383 
384     /**
385      * Breaks {@code token} into its constituent parts using the following algorithm.
386      *
387      * <ul>
388      * <li>ignore the first character ("<strong>-</strong>")</li>
389      * <li>for each remaining character check if an {@link Option} exists with that id.</li>
390      * <li>if an {@link Option} does exist then add that character prepended with "<strong>-</strong>" to the list of processed
391      * tokens.</li>
392      * <li>if the {@link Option} can have an argument value and there are remaining characters in the token then add the
393      * remaining characters as a token to the list of processed tokens.</li>
394      * <li>if an {@link Option} does <strong>NOT</strong> exist <strong>AND</strong> {@code stopAtNonOption} <strong>IS</strong> set then add the
395      * special token "<strong>--</strong>" followed by the remaining characters and also the remaining tokens directly to the
396      * processed tokens list.</li>
397      * <li>if an {@link Option} does <strong>NOT</strong> exist <strong>AND</strong> {@code stopAtNonOption} <strong>IS NOT</strong> set then add
398      * that character prepended with "<strong>-</strong>".</li>
399      * </ul>
400      *
401      * @param token The current token to be <strong>burst</strong> at the first non-Option encountered.
402      * @throws ParseException if there are any problems encountered while parsing the command line token.
403      */
404     protected void handleConcatenatedOptions(final String token) throws ParseException {
405         for (int i = 1; i < token.length(); i++) {
406             final String ch = String.valueOf(token.charAt(i));
407             if (!options.hasOption(ch)) {
408                 handleUnknownToken(nonOptionAction == NonOptionAction.STOP && i > 1 ? token.substring(i) : token);
409                 break;
410             }
411             handleOption(options.getOption(ch));
412             if (currentOption != null && token.length() != i + 1) {
413                 // add the trail as an argument of the option
414                 currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(token.substring(i + 1)));
415                 break;
416             }
417         }
418     }
419 
420     /**
421      * Handles the following tokens:
422      * <pre>
423      * --L --L=V --L V --l
424      * </pre>
425      *
426      * @param token the command line token to handle.
427      */
428     private void handleLongOption(final String token) throws ParseException {
429         if (indexOfEqual(token) == -1) {
430             handleLongOptionWithoutEqual(token);
431         } else {
432             handleLongOptionWithEqual(token);
433         }
434     }
435 
436     /**
437      * Handles the following tokens:
438      * <pre>
439      * --L=V -L=V --l=V -l=V
440      * </pre>
441      *
442      * @param token the command line token to handle.
443      */
444     private void handleLongOptionWithEqual(final String token) throws ParseException {
445         final int pos = indexOfEqual(token);
446         final String value = token.substring(pos + 1);
447         final String opt = token.substring(0, pos);
448         final List<String> matchingOpts = getMatchingLongOptions(opt);
449         if (matchingOpts.isEmpty()) {
450             handleUnknownToken(currentToken);
451         } else if (matchingOpts.size() > 1 && !options.hasLongOption(opt)) {
452             throw new AmbiguousOptionException(opt, matchingOpts);
453         } else {
454             final String key = options.hasLongOption(opt) ? opt : matchingOpts.get(0);
455             final Option option = options.getOption(key);
456             if (option.acceptsArg()) {
457                 handleOption(option);
458                 currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(value));
459                 currentOption = null;
460             } else {
461                 handleUnknownToken(currentToken);
462             }
463         }
464     }
465 
466     /**
467      * Handles the following tokens:
468      *
469      * <pre>
470      * --L -L --l -l
471      * </pre>
472      *
473      * @param token the command line token to handle.
474      */
475     private void handleLongOptionWithoutEqual(final String token) throws ParseException {
476         final List<String> matchingOpts = getMatchingLongOptions(token);
477         if (matchingOpts.isEmpty()) {
478             handleUnknownToken(currentToken);
479         } else if (matchingOpts.size() > 1 && !options.hasLongOption(token)) {
480             throw new AmbiguousOptionException(token, matchingOpts);
481         } else {
482             final String key = options.hasLongOption(token) ? token : matchingOpts.get(0);
483             handleOption(options.getOption(key));
484         }
485     }
486 
487     private void handleOption(final Option option) throws ParseException {
488         // check the previous option before handling the next one
489         checkRequiredArgs();
490         final Option copy = (Option) option.clone();
491         updateRequiredOptions(copy);
492         cmd.addOption(copy);
493         currentOption = copy.hasArg() ? copy : null;
494     }
495 
496     /**
497      * Sets the values of Options using the values in {@code properties}.
498      *
499      * @param properties The value properties to be processed.
500      */
501     private void handleProperties(final Properties properties) throws ParseException {
502         if (properties == null) {
503             return;
504         }
505         for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
506             final String option = e.nextElement().toString();
507             final Option opt = options.getOption(option);
508             if (opt == null) {
509                 throw new UnrecognizedOptionException("Default option wasn't defined", option);
510             }
511             // if the option is part of a group, check if another option of the group has been selected
512             final OptionGroup optionGroup = options.getOptionGroup(opt);
513             final boolean selected = optionGroup != null && optionGroup.isSelected();
514             if (!cmd.hasOption(option) && !selected) {
515                 // get the value from the properties
516                 final String value = properties.getProperty(option);
517 
518                 if (opt.hasArg()) {
519                     if (Util.isEmpty(opt.getValues())) {
520                         opt.processValue(stripLeadingAndTrailingQuotesDefaultOff(value));
521                     }
522                 } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) {
523                     // if the value is not yes, true or 1 then don't add the option to the CommandLine
524                     continue;
525                 }
526                 handleOption(opt);
527                 currentOption = null;
528             }
529         }
530     }
531 
532     /**
533      * Handles the following tokens:
534      * <pre>
535      * -S -SV -S V -S=V -S1S2 -S1S2 V -SV1=V2
536      *
537      * -L -LV -L V -L=V -l
538      * </pre>
539      *
540      * @param hyphenToken the command line token to handle.
541      */
542     private void handleShortAndLongOption(final String hyphenToken) throws ParseException {
543         final String token = Util.stripLeadingHyphens(hyphenToken);
544         final int pos = indexOfEqual(token);
545         if (token.length() == 1) {
546             // -S
547             if (options.hasShortOption(token)) {
548                 handleOption(options.getOption(token));
549             } else {
550                 handleUnknownToken(hyphenToken);
551             }
552         } else if (pos == -1) {
553             // no equal sign found (-xxx)
554             if (options.hasShortOption(token)) {
555                 handleOption(options.getOption(token));
556             } else if (!getMatchingLongOptions(token).isEmpty()) {
557                 // -L or -l
558                 handleLongOptionWithoutEqual(hyphenToken);
559             } else {
560                 // look for a long prefix (-Xmx512m)
561                 final String opt = getLongPrefix(token);
562 
563                 if (opt != null && options.getOption(opt).acceptsArg()) {
564                     handleOption(options.getOption(opt));
565                     currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(token.substring(opt.length())));
566                     currentOption = null;
567                 } else if (isJavaProperty(token)) {
568                     // -SV1 (-Dflag)
569                     handleOption(options.getOption(token.substring(0, 1)));
570                     currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(token.substring(1)));
571                     currentOption = null;
572                 } else {
573                     // -S1S2S3 or -S1S2V
574                     handleConcatenatedOptions(hyphenToken);
575                 }
576             }
577         } else {
578             // equal sign found (-xxx=yyy)
579             final String opt = token.substring(0, pos);
580             final String value = token.substring(pos + 1);
581 
582             if (opt.length() == 1) {
583                 // -S=V
584                 final Option option = options.getOption(opt);
585                 if (option != null && option.acceptsArg()) {
586                     handleOption(option);
587                     currentOption.processValue(value);
588                     currentOption = null;
589                 } else {
590                     handleUnknownToken(hyphenToken);
591                 }
592             } else if (isJavaProperty(opt)) {
593                 // -SV1=V2 (-Dkey=value)
594                 handleOption(options.getOption(opt.substring(0, 1)));
595                 currentOption.processValue(opt.substring(1));
596                 currentOption.processValue(value);
597                 currentOption = null;
598             } else {
599                 // -L=V or -l=V
600                 handleLongOptionWithEqual(hyphenToken);
601             }
602         }
603     }
604 
605     /**
606      * Handles any command line token.
607      *
608      * @param token the command line token to handle.
609      * @throws ParseException
610      */
611     private void handleToken(final String token) throws ParseException {
612         if (token != null) {
613             currentToken = token;
614             if (skipParsing) {
615                 addArg(token);
616             } else if ("--".equals(token)) {
617                 skipParsing = true;
618             } else if (currentOption != null && currentOption.acceptsArg() && isArgument(token)) {
619                 currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOn(token));
620             } else if (token.startsWith("--")) {
621                 handleLongOption(token);
622             } else if (token.startsWith("-") && !"-".equals(token)) {
623                 handleShortAndLongOption(token);
624             } else {
625                 handleUnknownToken(token);
626             }
627             if (currentOption != null && !currentOption.acceptsArg()) {
628                 currentOption = null;
629             }
630         }
631     }
632 
633     /**
634      * Handles an unknown token. If the token starts with a dash an UnrecognizedOptionException is thrown. Otherwise the
635      * token is added to the arguments of the command line. If the stopAtNonOption flag is set, this stops the parsing and
636      * the remaining tokens are added as-is in the arguments of the command line.
637      *
638      * @param token the command line token to handle.
639      * @throws ParseException if parsing should fail.
640      * @since 1.10.0
641      */
642     protected void handleUnknownToken(final String token) throws ParseException {
643         if (token.startsWith("-") && token.length() > 1 && nonOptionAction == NonOptionAction.THROW) {
644             throw new UnrecognizedOptionException("Unrecognized option: " + token, token);
645         }
646         if (!token.startsWith("-") || token.equals("-") || token.length() > 1 && nonOptionAction != NonOptionAction.IGNORE) {
647             addArg(token);
648         }
649         if (nonOptionAction == NonOptionAction.STOP) {
650             skipParsing = true;
651         }
652     }
653 
654     /**
655      * Tests if the token is a valid argument.
656      *
657      * @param token
658      */
659     private boolean isArgument(final String token) {
660         return !isOption(token) || isNegativeNumber(token);
661     }
662 
663     /**
664      * Tests if the specified token is a Java-like property (-Dkey=value).
665      */
666     private boolean isJavaProperty(final String token) {
667         final String opt = token.isEmpty() ? null : token.substring(0, 1);
668         final Option option = options.getOption(opt);
669         return option != null && (option.getArgs() >= 2 || option.getArgs() == Option.UNLIMITED_VALUES);
670     }
671 
672     /**
673      * Tests if the token looks like a long option.
674      *
675      * @param token
676      */
677     private boolean isLongOption(final String token) {
678         if (token == null || !token.startsWith("-") || token.length() == 1) {
679             return false;
680         }
681         final int pos = indexOfEqual(token);
682         final String t = pos == -1 ? token : token.substring(0, pos);
683         if (!getMatchingLongOptions(t).isEmpty()) {
684             // long or partial long options (--L, -L, --L=V, -L=V, --l, --l=V)
685             return true;
686         }
687         if (getLongPrefix(token) != null && !token.startsWith("--")) {
688             // -LV
689             return true;
690         }
691         return false;
692     }
693 
694     /**
695      * Tests if the token is a negative number.
696      *
697      * @param token
698      */
699     private boolean isNegativeNumber(final String token) {
700         try {
701             Double.parseDouble(token);
702             return true;
703         } catch (final NumberFormatException e) {
704             return false;
705         }
706     }
707 
708     /**
709      * Tests if the token looks like an option.
710      *
711      * @param token
712      */
713     private boolean isOption(final String token) {
714         return isLongOption(token) || isShortOption(token);
715     }
716 
717     /**
718      * Tests if the token looks like a short option.
719      *
720      * @param token
721      */
722     private boolean isShortOption(final String token) {
723         // short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
724         if (token == null || !token.startsWith("-") || token.length() == 1) {
725             return false;
726         }
727         // remove leading "-" and "=value"
728         final int pos = indexOfEqual(token);
729         final String optName = pos == -1 ? token.substring(1) : token.substring(1, pos);
730         if (options.hasShortOption(optName)) {
731             return true;
732         }
733         // check for several concatenated short options
734         return !optName.isEmpty() && options.hasShortOption(String.valueOf(optName.charAt(0)));
735     }
736 
737     /**
738      * Parses the arguments according to the specified options and properties.
739      *
740      * @param options the specified Options
741      * @param properties command line option name-value pairs
742      * @param nonOptionAction see {@link NonOptionAction}.
743      * @param arguments the command line arguments
744      *
745      * @return the list of atomic option and value tokens.
746      * @throws ParseException if there are any problems encountered while parsing the command line tokens.
747      * @since 1.10.0
748      */
749     public CommandLine parse(final Options options, final Properties properties, final NonOptionAction nonOptionAction, final String... arguments)
750             throws ParseException {
751         this.options = Objects.requireNonNull(options, "options");
752         this.nonOptionAction = nonOptionAction;
753         skipParsing = false;
754         currentOption = null;
755         expectedOpts = new ArrayList<>(options.getRequiredOptions());
756         // clear the data from the groups
757         for (final OptionGroup optionGroup : options.getOptionGroups()) {
758             optionGroup.setSelected(null);
759         }
760         cmd = CommandLine.builder().setDeprecatedHandler(deprecatedHandler).get();
761         if (arguments != null) {
762             for (final String argument : arguments) {
763                 handleToken(argument);
764             }
765         }
766         // check the arguments of the last option
767         checkRequiredArgs();
768         // add the default options
769         handleProperties(properties);
770         checkRequiredOptions();
771         return cmd;
772     }
773 
774     @Override
775     public CommandLine parse(final Options options, final String[] arguments) throws ParseException {
776         return parse(options, arguments, null);
777     }
778 
779     /**
780      * @see #parse(Options, Properties, NonOptionAction, String[])
781      */
782     @Override
783     public CommandLine parse(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException {
784         return parse(options, arguments, null, stopAtNonOption);
785     }
786 
787     /**
788      * Parses the arguments according to the specified options and properties.
789      *
790      * @param options the specified Options.
791      * @param arguments the command line arguments.
792      * @param properties command line option name-value pairs.
793      * @return the list of atomic option and value tokens.
794      * @throws ParseException if there are any problems encountered while parsing the command line tokens.
795      */
796     public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException {
797         return parse(options, arguments, properties, false);
798     }
799 
800     /**
801      * Parses the arguments according to the specified options and properties.
802      *
803      * @param options the specified Options.
804      * @param arguments the command line arguments.
805      * @param properties command line option name-value pairs.
806      * @param stopAtNonOption if {@code true} an unrecognized argument stops the parsing and the remaining arguments
807      *        are added to the {@link CommandLine}s args list. If {@code false} an unrecognized argument triggers a
808      *        ParseException.
809      * @return the list of atomic option and value tokens.
810      * @throws ParseException if there are any problems encountered while parsing the command line tokens.
811      * @see #parse(Options, Properties, NonOptionAction, String[])
812      */
813     public CommandLine parse(final Options options, final String[] arguments, final Properties properties, final boolean stopAtNonOption)
814         throws ParseException {
815         return parse(options, properties, stopAtNonOption ? NonOptionAction.STOP : NonOptionAction.THROW, arguments);
816     }
817 
818     /**
819      * Strips balanced leading and trailing quotes if the stripLeadingAndTrailingQuotes is set
820      * If stripLeadingAndTrailingQuotes is null, then do not strip
821      *
822      * @param token a string.
823      * @return token with the quotes stripped (if set).
824      */
825     private String stripLeadingAndTrailingQuotesDefaultOff(final String token) {
826         if (stripLeadingAndTrailingQuotes != null && stripLeadingAndTrailingQuotes) {
827             return Util.stripLeadingAndTrailingQuotes(token);
828         }
829         return token;
830     }
831 
832     /**
833      * Strips balanced leading and trailing quotes if the stripLeadingAndTrailingQuotes is set
834      * If stripLeadingAndTrailingQuotes is null, then do not strip
835      *
836      * @param token a string.
837      * @return token with the quotes stripped (if set).
838      */
839     private String stripLeadingAndTrailingQuotesDefaultOn(final String token) {
840         if (stripLeadingAndTrailingQuotes == null || stripLeadingAndTrailingQuotes) {
841             return Util.stripLeadingAndTrailingQuotes(token);
842         }
843         return token;
844     }
845 
846     /**
847      * Removes the option or its group from the list of expected elements.
848      *
849      * @param option
850      */
851     private void updateRequiredOptions(final Option option) throws AlreadySelectedException {
852         if (option.isRequired()) {
853             expectedOpts.remove(option.getKey());
854         }
855         // if the option is in an OptionGroup make that option the selected option of the group
856         if (options.getOptionGroup(option) != null) {
857             final OptionGroup optionGroup = options.getOptionGroup(option);
858             if (optionGroup.isRequired()) {
859                 expectedOpts.remove(optionGroup);
860             }
861             optionGroup.setSelected(option);
862         }
863     }
864 }