
net.windwards.options.RegistryCommandDispatcher Maven / Gradle / Ivy
The newest version!
package net.windwards.options;
import net.windwards.options.err.AmbiguousCommandException;
import net.windwards.options.err.NoSuchCommandException;
import java.util.HashMap;
import java.util.Map;
/**
* RegistryCommandDispatcher is a simple implementation of
* CommandDispatcher.handleCommand. It can be used to create commands
* that collect several subcommands into a single command, like "svn" or
* "openssl". For example:
*
*
* public RegistryExample() {
* this.addCommand("help", new Helper());
* this.addCommand("frobnicate", new Frobnicator());
* }
*
*
* For a full example, see CommandOptionParser.
*
*
* A RegistryCommandDispatcher can be tolerant. This means that the registry
* accept part of the command name. For example "frob" would match a command
* registered under the name "frobnicate". If the given command matches
* multiple commands in the registry, AmbiguousCommandException will be thrown.
*
*
* @see net.windwards.options.CommandOptionParser
*/
public class RegistryCommandDispatcher extends CommandDispatcher {
protected Map commands = new HashMap();
protected boolean tolerant = false;
/**
* Create a new RegistryCommandDispatcher. It will not be tolerant.
*/
public RegistryCommandDispatcher() { }
/**
* Create a new RegistryCommandDispatcher.
*
* @param tolerant Put this dispatcher in tolerant mode.
*/
public RegistryCommandDispatcher(boolean tolerant) {
this.tolerant = tolerant;
}
/**
* Register a new command with this registry.
*
* @param cmdname String name of the command. Matching is case
* insensitive.
* @param command An object of a class implementing C.
*/
public void addCommand(String cmdname, C command) {
this.commands.put(cmdname.toLowerCase(), command);
}
/**
* Return current tolerant status.
*
* @return True when partial name matching is turned on.
*/
public boolean getTolerant() {
return this.tolerant;
}
/**
* Control wether this dispatcher is tolerant, i.e. wether it will
* match commands on part of their name.
*
* @param tolerant
*/
public void setTolerant(boolean tolerant) {
this.tolerant = tolerant;
}
protected boolean matches(Map.Entry entry, String cmdname) {
if(this.tolerant) {
return entry.getKey().startsWith(cmdname);
}
return entry.getKey().equals(cmdname);
}
public C handleCommand(String cmdname) {
Map.Entry candidate = null;
cmdname = cmdname.toLowerCase();
for(Map.Entry entry : this.commands.entrySet()) {
if(this.matches(entry, cmdname)) {
if(candidate == null) {
candidate = entry;
} else {
throw new AmbiguousCommandException("Did you mean " +
entry.getKey() + " or " + candidate.getKey() + "?");
}
}
}
if(candidate == null) {
throw new NoSuchCommandException("No such command: " + cmdname);
}
return candidate.getValue();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy