Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 Tatsuhiro Tsujikawa
   *
   * Permission is hereby granted, free of charge, to any person
   * obtaining a copy of this software and associated documentation
   * files (the "Software"), to deal in the Software without
   * restriction, including without limitation the rights to use, copy,
   * modify, merge, publish, distribute, sublicense, and/or sell copies
   * of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
  *
  * The above copyright notice and this permission notice shall be
  * included in all copies or substantial portions of the Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
 package net.sourceforge.argparse4j.internal;
 
 import java.util.List;
 import java.util.Map;
 
The application code must not use this class directly.
 
 public final class SubparsersImpl implements Subparsers {
 
     private ArgumentParserImpl mainParser_;
    
The key is subparser command or alias name and value is subparser object. The real command and alias names share the same subparser object. To identify the aliases, check key equals to SubparserImpl.getCommand(). If they are equal, it is not alias.
 
     private Map<StringSubparserImplparsers_ = new LinkedHashMap<StringSubparserImpl>();
     private String help_ = "";
     private String title_ = "";
     private String description_ = "";
     private String dest_ = "";
     private String metavar_ = "";
 
     public SubparsersImpl(ArgumentParserImpl mainParser) {
          = mainParser;
     }
 
     @Override
     public SubparserImpl addParser(String command) {
         return addParser(commandtrue.getPrefixChars());
     }
 
     @Override
     public SubparserImpl addParser(String commandboolean addHelp) {
         return addParser(commandaddHelp.getPrefixChars());
     }
 
     @Override
     public SubparserImpl addParser(String commandboolean addHelp,
             String prefixChars) {
         if (command == null || command.isEmpty()) {
             throw new IllegalArgumentException(
                     "command cannot be null or empty");
         } else if (.containsKey(command)) {
             throw new IllegalArgumentException(String.format(
                     "command '%s' has been already used"command));
         }
         SubparserImpl parser = new SubparserImpl(.getProg(),
                 addHelpprefixChars.getFromFilePrefixChars(),
                 .getTextWidthCounter(), command);
         .put(commandparser);
         return parser;
     }
 
     @Override
     public SubparsersImpl dest(String dest) {
          = TextHelper.nonNull(dest);
         return this;
     }
 
     @Override
     public SubparsersImpl help(String help) {
          = TextHelper.nonNull(help);
         return this;
     }
    @Override
    public SubparsersImpl title(String title) {
         = TextHelper.nonNull(title);
        return this;
    }
    public String getTitle() {
        return ;
    }
    @Override
    public SubparsersImpl description(String description) {
         = TextHelper.nonNull(description);
        return this;
    }
    public String getDescription() {
        return ;
    }
    @Override
    public SubparsersImpl metavar(String metavar) {
         = TextHelper.nonNull(metavar);
        return this;
    }
    public boolean hasSubCommand() {
        return !.isEmpty();
    }

    
Get next SubparserImpl from given command and state. This function resolves abbreviated command input as well. If the given command is ambiguous, net.sourceforge.argparse4j.inf.ArgumentParserException will be thrown. If no matching SubparserImpl is found, this function returns null.

Parameters:
state
command
Returns:
next SubparserImpl or null
Throws:
net.sourceforge.argparse4j.inf.ArgumentParserException
    private SubparserImpl resolveNextSubparser(ParseState stateString command)
            throws ArgumentParserException {
        SubparserImpl ap = .get(state.getArg());
        if (ap == null) {
            List<Stringcand = TextHelper.findPrefix(.keySet(),
                    command);
            int size = cand.size();
            if (size == 1) {
                ap = .get(cand.get(0));
            } else if (size > 1) {
                // Sort it to make unit test easier
                Collections.sort(cand);
                throw new ArgumentParserException(String.format(
                        "ambiguous command: %s could match %s"command,
                        TextHelper.concat(cand, 0, ", ")), );
            }
        }
        return ap;
    }
    public void parseArg(ParseState stateMap<StringObjectopts)
            throws ArgumentParserException {
        if (.isEmpty()) {
            throw new IllegalArgumentException("too many arguments");
        }
        SubparserImpl ap = resolveNextSubparser(statestate.getArg());
        if (ap == null) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<StringSubparserImplentry : .entrySet()) {
                sb.append("'").append(entry.getKey()).append("', ");
            }
            sb.delete(sb.length() - 2, sb.length());
            throw new UnrecognizedCommandException(String.format(
                    "invalid choice: '%s' (choose from %s)"state.getArg(),
                    sb.toString()), state.getArg());
        } else {
            ++state.index;
            ap.parseArgs(stateopts);
            // Call after parseArgs to overwrite dest_ attribute set by
            // sub-parsers.
            if (!.isEmpty()) {
                opts.put(ap.getCommand());
            }
        }
    }
    public String formatShortSyntax() {
        if (.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            for (Map.Entry<StringSubparserImplentry : .entrySet()) {
                sb.append(entry.getKey()).append(",");
            }
            if (sb.length() > 1) {
                sb.delete(sb.length() - 1, sb.length());
            }
            sb.append("}");
            return sb.toString();
        } else {
            return ;
        }
    }

    
Writes the help message for this and descendants.

Parameters:
writer The writer to output
format_width column width
    public void printSubparserHelp(PrintWriter writerint format_width) {
        TextHelper.printHelp(writerformatShortSyntax(), ,
                .getTextWidthCounter(), format_width);
        for (Map.Entry<StringSubparserImplentry : .entrySet()) {
            // Don't generate help for aliases.
            if (entry.getKey().equals(entry.getValue().getCommand())) {
                entry.getValue().printSubparserHelp(writerformat_width);
            }
        }
    }

    
Returns collection of the sub-command name under this object.

Returns:
collection of the sub-comman name
    public Collection<StringgetCommands() {
        return .keySet();
    }

    
Adds Subparser alias names for given Subparser. For each SubparsersImpl instance, alias names and commands must be unique. If duplication is found, java.lang.IllegalArgumentException is thrown.

Parameters:
subparser Subparser to add alias names
alias alias name
    public void addAlias(SubparserImpl subparserString... alias) {
        for (String command : alias) {
            if (.containsKey(command)) {
                throw new IllegalArgumentException(String.format(
                        "command '%s' has been already used"command));
            } else {
                .put(commandsubparser);
            }
        }
    }
New to GrepCode? Check out our FAQ X