src/main/java/org/vaadin/console/Console.java
changeset 0 c46bb04134cb
child 1 9b9d2f4b4ce0
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/main/java/org/vaadin/console/Console.java	Sun May 15 17:46:06 2011 +0400
     1.3 @@ -0,0 +1,730 @@
     1.4 +package org.vaadin.console;
     1.5 +
     1.6 +import java.io.ByteArrayOutputStream;
     1.7 +import java.io.IOException;
     1.8 +import java.io.OutputStream;
     1.9 +import java.io.PrintStream;
    1.10 +import java.io.Serializable;
    1.11 +import java.util.ArrayList;
    1.12 +import java.util.Collections;
    1.13 +import java.util.HashMap;
    1.14 +import java.util.HashSet;
    1.15 +import java.util.List;
    1.16 +import java.util.Map;
    1.17 +import java.util.Set;
    1.18 +
    1.19 +import org.vaadin.rpc.ServerSideHandler;
    1.20 +import org.vaadin.rpc.ServerSideProxy;
    1.21 +import org.vaadin.rpc.client.Method;
    1.22 +
    1.23 +import com.vaadin.terminal.PaintException;
    1.24 +import com.vaadin.terminal.PaintTarget;
    1.25 +import com.vaadin.ui.AbstractComponent;
    1.26 +import com.vaadin.ui.Component;
    1.27 +
    1.28 +/**
    1.29 + * Server side component for the VTextConsole widget.
    1.30 + *
    1.31 + * @author Sami Ekblad / Vaadin
    1.32 + *
    1.33 + */
    1.34 +@com.vaadin.ui.ClientWidget(org.vaadin.console.client.ui.VTextConsole.class)
    1.35 +public class Console extends AbstractComponent implements Component.Focusable {
    1.36 +
    1.37 +    private static final long serialVersionUID = 590258219352859644L;
    1.38 +    private Handler handler;
    1.39 +    private final HashMap<String, Command> commands = new HashMap<String, Command>();
    1.40 +    private final Config config = new Config();
    1.41 +
    1.42 +    private static final String DEFAULT_PS = "}> ";
    1.43 +    private static final String DEFAULT_GREETING = "Console ready.";
    1.44 +    private static final int DEFAULT_BUFFER = 0;
    1.45 +    private static final int DEFAULT_COLS = -1;
    1.46 +    private static final int DEFAULT_ROWS = -1;
    1.47 +    private static final boolean DEFAULT_WRAP = true;
    1.48 +    private static final int MAX_COLS = 500;
    1.49 +    private static final int MAX_ROWS = 200;
    1.50 +
    1.51 +    public boolean isWrap() {
    1.52 +        return config.wrap;
    1.53 +    }
    1.54 +
    1.55 +    public void setWrap(final boolean wrap) {
    1.56 +        config.wrap = wrap;
    1.57 +        client.call("setWrap", wrap);
    1.58 +    }
    1.59 +
    1.60 +    private final ServerSideProxy client = new ServerSideProxy(
    1.61 +            new ClientCallback());
    1.62 +
    1.63 +    /**
    1.64 +     * Inner class to handle client calls.
    1.65 +     *
    1.66 +     */
    1.67 +    public class ClientCallback implements ServerSideHandler {
    1.68 +
    1.69 +        private static final long serialVersionUID = 3992611573500588703L;
    1.70 +
    1.71 +        public void requestRepaint() {
    1.72 +            Console.this.requestRepaint();
    1.73 +        }
    1.74 +
    1.75 +        public Object[] initRequestFromClient() {
    1.76 +            return new Object[] { config.cols, config.rows,
    1.77 +                    config.maxBufferSize, config.wrap, config.greeting,
    1.78 +                    config.ps };
    1.79 +        }
    1.80 +
    1.81 +        public void callFromClient(String method, Object[] params) {
    1.82 +            // TODO Auto-generated method stub
    1.83 +
    1.84 +        }
    1.85 +
    1.86 +    }
    1.87 +
    1.88 +    /**
    1.89 +     * The tab order number of this field.
    1.90 +     */
    1.91 +    private int tabIndex = 0;
    1.92 +    @SuppressWarnings("unused")
    1.93 +    private Integer fontw;
    1.94 +    @SuppressWarnings("unused")
    1.95 +    private Integer fonth;
    1.96 +    private PrintStream printStream;
    1.97 +    private String lastSuggestInput;
    1.98 +    private List<CommandProvider> commandProviders;
    1.99 +
   1.100 +    /**
   1.101 +     * An inner class for holding the configuration data.
   1.102 +     */
   1.103 +    public static class Config implements Serializable {
   1.104 +
   1.105 +        private static final long serialVersionUID = -812601232248504108L;
   1.106 +
   1.107 +        int maxBufferSize = DEFAULT_BUFFER;
   1.108 +        int cols = DEFAULT_COLS;
   1.109 +        int rows = DEFAULT_ROWS;
   1.110 +        boolean wrap = DEFAULT_WRAP;
   1.111 +        String ps = DEFAULT_PS;
   1.112 +        String greeting = DEFAULT_GREETING;
   1.113 +
   1.114 +    }
   1.115 +
   1.116 +    /**
   1.117 +     * Console Handler interface.
   1.118 +     *
   1.119 +     * Handler provides a hook to handle various console related events and
   1.120 +     * override the default processing.
   1.121 +     *
   1.122 +     */
   1.123 +    public interface Handler extends Serializable {
   1.124 +
   1.125 +        /**
   1.126 +         * Called when user uses TAB to complete the command entered into the
   1.127 +         * Console input.
   1.128 +         *
   1.129 +         * @param console
   1.130 +         * @param lastInput
   1.131 +         * @return
   1.132 +         */
   1.133 +        Set<String> getSuggestions(Console console, String lastInput);
   1.134 +
   1.135 +        /**
   1.136 +         * Called when user has entered input to the Console and presses enter
   1.137 +         * to execute it.
   1.138 +         *
   1.139 +         * @param console
   1.140 +         * @param lastInput
   1.141 +         */
   1.142 +        void inputReceived(Console console, String lastInput);
   1.143 +
   1.144 +        /**
   1.145 +         * Handle an exception during a Command execution.
   1.146 +         *
   1.147 +         * @param console
   1.148 +         * @param e
   1.149 +         * @param cmd
   1.150 +         * @param argv
   1.151 +         */
   1.152 +        void handleException(Console console, Exception e, Command cmd,
   1.153 +                String[] argv);
   1.154 +
   1.155 +        /**
   1.156 +         * Handle situation where a command could not be found.
   1.157 +         *
   1.158 +         * @param console
   1.159 +         * @param argv
   1.160 +         */
   1.161 +        void commandNotFound(Console console, String[] argv);
   1.162 +
   1.163 +    }
   1.164 +
   1.165 +    /**
   1.166 +     * Commands that can be executed against the Component instance. They
   1.167 +     * provide convenient string to method mapping. Basically, a Command is a
   1.168 +     * method that that can be executed in Component. It can have parameters or
   1.169 +     * not.
   1.170 +     *
   1.171 +     */
   1.172 +    public interface Command extends Serializable {
   1.173 +
   1.174 +        /**
   1.175 +         * Execute a Command with arguments.
   1.176 +         *
   1.177 +         * @param console
   1.178 +         * @param argv
   1.179 +         * @return
   1.180 +         * @throws Exception
   1.181 +         */
   1.182 +        public Object execute(Console console, String[] argv) throws Exception;
   1.183 +
   1.184 +        /**
   1.185 +         * Get usage information about this command.
   1.186 +         *
   1.187 +         * @param console
   1.188 +         * @param argv
   1.189 +         * @return
   1.190 +         */
   1.191 +        public String getUsage(Console console, String[] argv);
   1.192 +    }
   1.193 +
   1.194 +    /**
   1.195 +     * Interface for providing Commands to the console. One can register a
   1.196 +     * command providers to console instead of individual commands to provide a
   1.197 +     * lot of commands.
   1.198 +     *
   1.199 +     */
   1.200 +    public interface CommandProvider extends Serializable {
   1.201 +
   1.202 +        /**
   1.203 +         * List all available command from this provider.
   1.204 +         *
   1.205 +         * @param console
   1.206 +         * @return
   1.207 +         */
   1.208 +        Set<String> getAvailableCommands(Console console);
   1.209 +
   1.210 +        /**
   1.211 +         * Get Command instance based on command name.
   1.212 +         *
   1.213 +         * @param console
   1.214 +         * @param commandName
   1.215 +         * @return
   1.216 +         */
   1.217 +        Command getCommand(Console console, String commandName);
   1.218 +
   1.219 +    }
   1.220 +
   1.221 +    public void addCommandProvider(final CommandProvider commandProvider) {
   1.222 +        if (commandProviders == null) {
   1.223 +            commandProviders = new ArrayList<CommandProvider>();
   1.224 +        }
   1.225 +        commandProviders.add(commandProvider);
   1.226 +    }
   1.227 +
   1.228 +    public void removeCommandProvider(final CommandProvider commandProvider) {
   1.229 +        if (commandProviders == null) {
   1.230 +            return;
   1.231 +        }
   1.232 +        commandProviders.remove(commandProvider);
   1.233 +    }
   1.234 +
   1.235 +    public void removeAllCommandProviders() {
   1.236 +        if (commandProviders == null) {
   1.237 +            return;
   1.238 +        }
   1.239 +        commandProviders.clear();
   1.240 +    }
   1.241 +
   1.242 +    public Console(final Console.Handler handler) {
   1.243 +        this();
   1.244 +        setHandler(handler);
   1.245 +    }
   1.246 +
   1.247 +    public Console() {
   1.248 +        setImmediate(true);
   1.249 +        setHandler(new DefaultConsoleHandler());
   1.250 +        registerCallbacks();
   1.251 +    }
   1.252 +
   1.253 +    private void registerCallbacks() {
   1.254 +        client.register("suggest", new Method() {
   1.255 +
   1.256 +            public void invoke(String methodName, Object[] params) {
   1.257 +                handleSuggest((String) params[0]);
   1.258 +            }
   1.259 +        });
   1.260 +        client.register("input", new Method() {
   1.261 +
   1.262 +            public void invoke(String methodName, Object[] params) {
   1.263 +                handleInput((String) params[0]);
   1.264 +            }
   1.265 +        });
   1.266 +
   1.267 +    }
   1.268 +
   1.269 +    @Override
   1.270 +    public void paintContent(final PaintTarget target) throws PaintException {
   1.271 +        super.paintContent(target);
   1.272 +        client.paintContent(target);
   1.273 +    }
   1.274 +
   1.275 +    @Override
   1.276 +    public void changeVariables(final Object source,
   1.277 +            final Map<String, Object> variables) {
   1.278 +        super.changeVariables(source, variables);
   1.279 +        client.changeVariables(source, variables);
   1.280 +        if (variables.containsKey("width")) {
   1.281 +            setWidth((String) variables.get("width"));
   1.282 +        }
   1.283 +        if (variables.containsKey("height")) {
   1.284 +            setHeight((String) variables.get("height"));
   1.285 +        }
   1.286 +        if (variables.containsKey("fontw")) {
   1.287 +            fontw = (Integer) variables.get("fontw");
   1.288 +        }
   1.289 +        if (variables.containsKey("fonth")) {
   1.290 +            fonth = (Integer) variables.get("fonth");
   1.291 +        }
   1.292 +        if (variables.containsKey("cols")) {
   1.293 +            config.cols = (Integer) variables.get("cols");
   1.294 +        }
   1.295 +        if (variables.containsKey("rows")) {
   1.296 +            config.rows = (Integer) variables.get("rows");
   1.297 +        }
   1.298 +    }
   1.299 +
   1.300 +    /**
   1.301 +     * Overridden to filter client-side calculation/changes and avoid loops.
   1.302 +     *
   1.303 +     */
   1.304 +    @Override
   1.305 +    public void setWidth(float width, int unit) {
   1.306 +        if (width != getWidth() || unit != getWidthUnits()) {
   1.307 +            super.setWidth(width, unit);
   1.308 +        }
   1.309 +    }
   1.310 +
   1.311 +    /**
   1.312 +     * Overridden to filter client-side calculation/changes and avoid loops.
   1.313 +     *
   1.314 +     */
   1.315 +    @Override
   1.316 +    public void setHeight(float height, int unit) {
   1.317 +        if (height != getHeight() || unit != getHeightUnits()) {
   1.318 +            super.setHeight(height, unit);
   1.319 +        }
   1.320 +    }
   1.321 +
   1.322 +    protected void handleSuggest(final String input) {
   1.323 +
   1.324 +        final boolean cancelIfNotASingleMatch = (input != null && !input
   1.325 +                .equals(lastSuggestInput));
   1.326 +        lastSuggestInput = input;
   1.327 +
   1.328 +        final Set<String> matches = handler.getSuggestions(this, input);
   1.329 +
   1.330 +        if (matches == null || matches.size() == 0) {
   1.331 +            bell();
   1.332 +            return;
   1.333 +        }
   1.334 +
   1.335 +        // Output the original
   1.336 +        final String prefix = parseCommandPrefix(input);
   1.337 +        String output = input.substring(0, input.lastIndexOf(prefix));
   1.338 +        if (matches.size() == 1) {
   1.339 +            // Output the only match
   1.340 +            output += matches.iterator().next() + " "; // append the single
   1.341 +            // match
   1.342 +        } else {
   1.343 +
   1.344 +            // We output until the common prefix
   1.345 +            StringBuilder commonPrefix = new StringBuilder(prefix);
   1.346 +            final int maxLen = matches.iterator().next().length();
   1.347 +            for (int i = prefix.length(); i < maxLen; i++) {
   1.348 +                char c = 0;
   1.349 +                boolean charMatch = true;
   1.350 +                for (final String m : matches) {
   1.351 +                    if (c == 0) {
   1.352 +                        c = m.charAt(i);
   1.353 +                    } else if (i < m.length()) {
   1.354 +                        charMatch &= m.charAt(i) == c;
   1.355 +                        if (!charMatch) {
   1.356 +                            break;
   1.357 +                        }
   1.358 +                    } else {
   1.359 +                        charMatch = false;
   1.360 +                        break;
   1.361 +                    }
   1.362 +                }
   1.363 +                if (charMatch) {
   1.364 +                    commonPrefix.append(c);
   1.365 +                }
   1.366 +            }
   1.367 +            output += commonPrefix.toString();
   1.368 +            if (prefix.equals(commonPrefix.toString())
   1.369 +                    && !cancelIfNotASingleMatch) {
   1.370 +                final StringBuffer suggestions = new StringBuffer("\n");
   1.371 +                for (final String m : matches) {
   1.372 +                    suggestions.append(" " + m);
   1.373 +                }
   1.374 +                print(suggestions.toString());
   1.375 +            } else {
   1.376 +                bell();
   1.377 +                lastSuggestInput = output; // next suggest will not beep
   1.378 +            }
   1.379 +        }
   1.380 +        prompt(output);
   1.381 +        focus();
   1.382 +
   1.383 +    }
   1.384 +
   1.385 +    public void bell() {
   1.386 +        client.call("bell");
   1.387 +    }
   1.388 +
   1.389 +    protected void handleInput(final String input) {
   1.390 +
   1.391 +        // Ask registered handler
   1.392 +        handler.inputReceived(this, input);
   1.393 +
   1.394 +    }
   1.395 +
   1.396 +    protected void parseAndExecuteCommand(final String input) {
   1.397 +        final String[] argv = parseInput(input);
   1.398 +        if (argv != null && argv.length > 0) {
   1.399 +            final Command c = getCommand(argv[0]);
   1.400 +            if (c != null) {
   1.401 +                final String result = executeCommand(c, argv);
   1.402 +                if (result != null) {
   1.403 +                    print(result);
   1.404 +                }
   1.405 +            } else {
   1.406 +                handler.commandNotFound(this, argv);
   1.407 +            }
   1.408 +        }
   1.409 +    }
   1.410 +
   1.411 +    protected String executeCommand(final Command cmd, final String[] argv) {
   1.412 +        try {
   1.413 +            final Object r = cmd.execute(this, argv);
   1.414 +            return r != null ? "" + r : null;
   1.415 +        } catch (final Exception e) {
   1.416 +            handler.handleException(this, e, cmd, argv);
   1.417 +        }
   1.418 +        return null;
   1.419 +    }
   1.420 +
   1.421 +    protected String parseCommandPrefix(final String input) {
   1.422 +        if (input == null) {
   1.423 +            return null;
   1.424 +        }
   1.425 +        if (!input.endsWith(" ")) {
   1.426 +            final String[] argv = parseInput(input);
   1.427 +            if (argv != null && argv.length > 0) {
   1.428 +                return argv[argv.length - 1];
   1.429 +            }
   1.430 +        }
   1.431 +        return "";
   1.432 +    }
   1.433 +
   1.434 +    protected static String[] parseInput(final String input) {
   1.435 +        if (input != null && !"".equals(input.trim())) {
   1.436 +            final String[] temp = input.split(" ");
   1.437 +            if (temp != null && temp.length > 0) {
   1.438 +                final List<String> parsed = new ArrayList<String>(temp.length);
   1.439 +                String current = null;
   1.440 +                for (final String element : temp) {
   1.441 +                    final int quotCount = count(element, '\"');
   1.442 +                    if (quotCount > 0 && quotCount % 2 != 0) {
   1.443 +                        // uneven number of quotes star or end combining params
   1.444 +                        if (current != null) {
   1.445 +                            parsed.add(current + " "
   1.446 +                                    + element.replaceAll("\"", "")); // end
   1.447 +                            current = null;
   1.448 +                        } else {
   1.449 +                            current = element.replaceAll("\"", ""); // start
   1.450 +                        }
   1.451 +                    } else if (current != null) {
   1.452 +                        current += " " + element.replaceAll("\"", "");
   1.453 +                    } else {
   1.454 +                        parsed.add(element.replaceAll("\"", ""));
   1.455 +                    }
   1.456 +                }
   1.457 +
   1.458 +                // TODO: actually this is not quite right: We have an open quote
   1.459 +                // somewhere. Exception maybe?
   1.460 +                if (current != null) {
   1.461 +                    parsed.add(current.replaceAll("\"", ""));
   1.462 +                }
   1.463 +                return parsed.toArray(new String[] {});
   1.464 +            }
   1.465 +        }
   1.466 +        return new String[] {};
   1.467 +    }
   1.468 +
   1.469 +    protected static int count(final String sourceString, final char lookFor) {
   1.470 +        if (sourceString == null) {
   1.471 +            return -1;
   1.472 +        }
   1.473 +        int count = 0;
   1.474 +        for (int i = 0; i < sourceString.length(); i++) {
   1.475 +            final char c = sourceString.charAt(i);
   1.476 +            if (c == lookFor) {
   1.477 +                count++;
   1.478 +            }
   1.479 +        }
   1.480 +        return count;
   1.481 +    }
   1.482 +
   1.483 +    public void print(final String output) {
   1.484 +        client.call("print", output);
   1.485 +    }
   1.486 +
   1.487 +    public String getGreeting() {
   1.488 +        return config.greeting;
   1.489 +    }
   1.490 +
   1.491 +    public String getPs() {
   1.492 +        return config.ps;
   1.493 +    }
   1.494 +
   1.495 +    public int getMaxBufferSize() {
   1.496 +        return config.maxBufferSize;
   1.497 +    }
   1.498 +
   1.499 +    public int getRows() {
   1.500 +        return config.rows;
   1.501 +    }
   1.502 +
   1.503 +    public void setGreeting(final String greeting) {
   1.504 +        config.greeting = greeting;
   1.505 +        client.call("setGreeting", greeting);
   1.506 +    }
   1.507 +
   1.508 +    public void setPs(final String ps) {
   1.509 +        config.ps = ps == null ? DEFAULT_PS : ps;
   1.510 +        client.call("setPs", config.ps);
   1.511 +    }
   1.512 +
   1.513 +    public void setMaxBufferSize(final int lines) {
   1.514 +        config.maxBufferSize = lines > 0 ? lines : 0;
   1.515 +        client.call("setMaxBufferSize", config.maxBufferSize);
   1.516 +    }
   1.517 +
   1.518 +    public void setRows(final int rows) {
   1.519 +        config.rows = rows;
   1.520 +        if (config.rows < 1) {
   1.521 +            config.rows = 1;
   1.522 +        }
   1.523 +        if (config.rows > MAX_ROWS) {
   1.524 +            config.rows = MAX_ROWS;
   1.525 +        }
   1.526 +        client.call("setRows", rows);
   1.527 +    }
   1.528 +
   1.529 +    public int getCols() {
   1.530 +        return config.cols;
   1.531 +    }
   1.532 +
   1.533 +    public void setCols(final int cols) {
   1.534 +        config.cols = cols;
   1.535 +        if (config.cols < 1) {
   1.536 +            config.cols = 1;
   1.537 +        }
   1.538 +        if (config.cols > MAX_COLS) {
   1.539 +            config.cols = MAX_COLS;
   1.540 +        }
   1.541 +        client.call("setCols", config.cols);
   1.542 +    }
   1.543 +
   1.544 +    public void prompt() {
   1.545 +        client.call("prompt");
   1.546 +    }
   1.547 +
   1.548 +    public void prompt(final String initialInput) {
   1.549 +        client.call("prompt", initialInput);
   1.550 +    }
   1.551 +
   1.552 +    public void println(final String string) {
   1.553 +        client.call("println", string);
   1.554 +    }
   1.555 +
   1.556 +    public void newLine() {
   1.557 +        client.call("newLine");
   1.558 +    }
   1.559 +
   1.560 +    public void reset() {
   1.561 +        client.call("reset");
   1.562 +    }
   1.563 +
   1.564 +    public void clear() {
   1.565 +        formFeed();
   1.566 +    }
   1.567 +
   1.568 +    public void formFeed() {
   1.569 +        client.call("ff");
   1.570 +    }
   1.571 +
   1.572 +    public void carriageReturn() {
   1.573 +        client.call("cr");
   1.574 +    }
   1.575 +
   1.576 +    public void lineFeed() {
   1.577 +        client.call("lf");
   1.578 +    }
   1.579 +
   1.580 +    public void clearCommandHistory() {
   1.581 +        client.call("clearHistory");
   1.582 +    }
   1.583 +
   1.584 +    public void clearBuffer() {
   1.585 +        client.call("clearBuffer");
   1.586 +    }
   1.587 +
   1.588 +    public void scrollToEnd() {
   1.589 +        client.call("scrollToEnd");
   1.590 +    }
   1.591 +
   1.592 +    /**
   1.593 +     * Gets the Tabulator index of this Focusable component.
   1.594 +     *
   1.595 +     * @see com.vaadin.ui.Component.Focusable#getTabIndex()
   1.596 +     */
   1.597 +    public int getTabIndex() {
   1.598 +        return tabIndex;
   1.599 +    }
   1.600 +
   1.601 +    /**
   1.602 +     * Sets the Tabulator index of this Focusable component.
   1.603 +     *
   1.604 +     * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
   1.605 +     */
   1.606 +    public void setTabIndex(final int tabIndex) {
   1.607 +        this.tabIndex = tabIndex;
   1.608 +    }
   1.609 +
   1.610 +    /**
   1.611 +     * {@inheritDoc}
   1.612 +     */
   1.613 +    @Override
   1.614 +    public void focus() {
   1.615 +        super.focus();
   1.616 +    }
   1.617 +
   1.618 +    /* PrintStream implementation for console output. */
   1.619 +
   1.620 +    public PrintStream getPrintStream() {
   1.621 +        if (printStream == null) {
   1.622 +            printStream = new PrintStream(new OutputStream() {
   1.623 +
   1.624 +                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   1.625 +
   1.626 +                @Override
   1.627 +                public void write(final int b) throws IOException {
   1.628 +                    buffer.write(b);
   1.629 +                    // Line buffering
   1.630 +                    if (13 == b) {
   1.631 +                        flush();
   1.632 +                    }
   1.633 +                }
   1.634 +
   1.635 +                @Override
   1.636 +                public void flush() throws IOException {
   1.637 +                    super.flush();
   1.638 +                    buffer.flush();
   1.639 +                    Console.this.print(buffer.toString());
   1.640 +                    buffer.reset();
   1.641 +                }
   1.642 +            }, true);
   1.643 +        }
   1.644 +        return printStream;
   1.645 +    }
   1.646 +
   1.647 +    /* Generic command handling */
   1.648 +
   1.649 +    /**
   1.650 +     * Add a Command to this Console.
   1.651 +     *
   1.652 +     * This will override the any commands of the same name available via
   1.653 +     * {@link CommandProvider}.
   1.654 +     */
   1.655 +    public void addCommand(final String name, final Command cmd) {
   1.656 +        commands.put(name, cmd);
   1.657 +    }
   1.658 +
   1.659 +    /**
   1.660 +     * Remove a command from this console.
   1.661 +     *
   1.662 +     * This does not remove Command available from {@link CommandProvider}.
   1.663 +     *
   1.664 +     * @param cmdName
   1.665 +     */
   1.666 +    public void removeCommand(final String cmdName) {
   1.667 +        commands.remove(cmdName);
   1.668 +    }
   1.669 +
   1.670 +    /**
   1.671 +     * Get a Command by its name.
   1.672 +     *
   1.673 +     * @param cmdName
   1.674 +     * @return
   1.675 +     */
   1.676 +    public Command getCommand(final String cmdName) {
   1.677 +
   1.678 +        // Try directly registered command first
   1.679 +        Command cmd = commands.get(cmdName);
   1.680 +        if (cmd != null) {
   1.681 +            return cmd;
   1.682 +        }
   1.683 +
   1.684 +        // Ask from the providers
   1.685 +        if (commandProviders != null) {
   1.686 +            for (final CommandProvider cp : commandProviders) {
   1.687 +                cmd = cp.getCommand(this, cmdName);
   1.688 +                if (cmd != null) {
   1.689 +                    return cmd;
   1.690 +                }
   1.691 +            }
   1.692 +        }
   1.693 +
   1.694 +        // Not found
   1.695 +        return null;
   1.696 +    }
   1.697 +
   1.698 +    /**
   1.699 +     * Get the current Console Handler.
   1.700 +     *
   1.701 +     * @return
   1.702 +     */
   1.703 +    public Handler getHandler() {
   1.704 +        return handler;
   1.705 +    }
   1.706 +
   1.707 +    /**
   1.708 +     * Set the handler for this console.
   1.709 +     *
   1.710 +     * @see Handler
   1.711 +     * @param handler
   1.712 +     */
   1.713 +    public void setHandler(final Handler handler) {
   1.714 +        this.handler = handler != null ? handler : new DefaultConsoleHandler();
   1.715 +    }
   1.716 +
   1.717 +    /**
   1.718 +     * Get map of available commands in this Console.
   1.719 +     *
   1.720 +     * @return
   1.721 +     */
   1.722 +    public Set<String> getCommands() {
   1.723 +        final Set<String> res = new HashSet<String>();
   1.724 +        if (commandProviders != null) {
   1.725 +            for (final CommandProvider cp : commandProviders) {
   1.726 +                res.addAll(cp.getAvailableCommands(this));
   1.727 +            }
   1.728 +        }
   1.729 +        res.addAll(commands.keySet());
   1.730 +        return Collections.unmodifiableSet(res);
   1.731 +    }
   1.732 +
   1.733 +}