+ new functionality: in methods append, print, println you may declare CSS class name for output text
1 package org.vaadin.console;
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.OutputStream;
6 import java.io.PrintStream;
7 import java.io.Serializable;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.List;
16 import org.vaadin.rpc.ServerSideHandler;
17 import org.vaadin.rpc.ServerSideProxy;
18 import org.vaadin.rpc.client.Method;
20 import com.vaadin.terminal.PaintException;
21 import com.vaadin.terminal.PaintTarget;
22 import com.vaadin.ui.AbstractComponent;
23 import com.vaadin.ui.Component;
26 * Server side component for the VTextConsole widget.
28 * @author Sami Ekblad / Vaadin
31 @com.vaadin.ui.ClientWidget(org.vaadin.console.client.ui.VTextConsole.class)
32 public class Console extends AbstractComponent implements Component.Focusable {
34 private static final long serialVersionUID = 590258219352859644L;
35 private Handler handler;
36 private final HashMap<String, Command> commands = new HashMap<String, Command>();
37 private final Config config = new Config();
39 private static final String DEFAULT_PS = "}> ";
40 private static final String DEFAULT_GREETING = "Console ready.";
41 private static final int DEFAULT_BUFFER = 0;
42 private static final int DEFAULT_COLS = -1;
43 private static final int DEFAULT_ROWS = -1;
44 private static final boolean DEFAULT_WRAP = true;
45 private static final boolean DEFAULT_PRINT_PROMPT_ON_INPUT= true;
46 private static final int MAX_COLS = 500;
47 private static final int MAX_ROWS = 200;
49 public boolean isWrap() {
53 public void setWrap(final boolean wrap) {
55 client.call("setWrap", wrap);
58 public boolean isPrintPromptOnInput(){
59 return config.isPrintPromptOnInput;
62 public void setPrintPromptOnInput(final boolean isPrintPromptOnInput){
63 config.isPrintPromptOnInput = isPrintPromptOnInput;
64 client.call("setPrintPromptOnInput", isPrintPromptOnInput);
67 private final ServerSideProxy client = new ServerSideProxy(
68 new ClientCallback());
71 * Inner class to handle client calls.
74 public class ClientCallback implements ServerSideHandler {
76 private static final long serialVersionUID = 3992611573500588703L;
78 public void requestRepaint() {
79 Console.this.requestRepaint();
82 public Object[] initRequestFromClient() {
83 return new Object[] { config.cols, config.rows,
84 config.maxBufferSize, config.wrap, config.isPrintPromptOnInput, config.greeting,
88 public void callFromClient(String method, Object[] params) {
89 // TODO Auto-generated method stub
96 * The tab order number of this field.
98 private int tabIndex = 0;
99 @SuppressWarnings("unused")
100 private Integer fontw;
101 @SuppressWarnings("unused")
102 private Integer fonth;
103 private PrintStream printStream;
104 private String lastSuggestInput;
105 private List<CommandProvider> commandProviders;
108 * An inner class for holding the configuration data.
110 public static class Config implements Serializable {
112 private static final long serialVersionUID = -812601232248504108L;
114 int maxBufferSize = DEFAULT_BUFFER;
115 int cols = DEFAULT_COLS;
116 int rows = DEFAULT_ROWS;
117 boolean wrap = DEFAULT_WRAP;
118 boolean isPrintPromptOnInput = DEFAULT_PRINT_PROMPT_ON_INPUT;
119 String ps = DEFAULT_PS;
120 String greeting = DEFAULT_GREETING;
125 * Console Handler interface.
127 * Handler provides a hook to handle various console related events and
128 * override the default processing.
131 public interface Handler extends Serializable {
134 * Called when user uses TAB to complete the command entered into the
141 Set<String> getSuggestions(Console console, String lastInput);
144 * Called when user has entered input to the Console and presses enter
150 void inputReceived(Console console, String lastInput);
153 * Handle an exception during a Command execution.
160 void handleException(Console console, Exception e, Command cmd,
164 * Handle situation where a command could not be found.
169 void commandNotFound(Console console, String[] argv);
174 * Commands that can be executed against the Component instance. They
175 * provide convenient string to method mapping. Basically, a Command is a
176 * method that that can be executed in Component. It can have parameters or
180 public interface Command extends Serializable {
183 * Execute a Command with arguments.
190 public Object execute(Console console, String[] argv) throws Exception;
193 * Get usage information about this command.
199 public String getUsage(Console console, String[] argv);
203 * Interface for providing Commands to the console. One can register a
204 * command providers to console instead of individual commands to provide a
208 public interface CommandProvider extends Serializable {
211 * List all available command from this provider.
216 Set<String> getAvailableCommands(Console console);
219 * Get Command instance based on command name.
225 Command getCommand(Console console, String commandName);
229 public void addCommandProvider(final CommandProvider commandProvider) {
230 if (commandProviders == null) {
231 commandProviders = new ArrayList<CommandProvider>();
233 commandProviders.add(commandProvider);
236 public void removeCommandProvider(final CommandProvider commandProvider) {
237 if (commandProviders == null) {
240 commandProviders.remove(commandProvider);
243 public void removeAllCommandProviders() {
244 if (commandProviders == null) {
247 commandProviders.clear();
250 public Console(final Console.Handler handler) {
257 setHandler(new DefaultConsoleHandler());
261 private void registerCallbacks() {
262 client.register("suggest", new Method() {
264 public void invoke(String methodName, Object[] params) {
265 handleSuggest((String) params[0]);
268 client.register("input", new Method() {
270 public void invoke(String methodName, Object[] params) {
271 handleInput((String) params[0]);
278 public void paintContent(final PaintTarget target) throws PaintException {
279 super.paintContent(target);
280 client.paintContent(target);
284 public void changeVariables(final Object source,
285 final Map<String, Object> variables) {
286 super.changeVariables(source, variables);
287 client.changeVariables(source, variables);
288 if (variables.containsKey("width")) {
289 setWidth((String) variables.get("width"));
291 if (variables.containsKey("height")) {
292 setHeight((String) variables.get("height"));
294 if (variables.containsKey("fontw")) {
295 fontw = (Integer) variables.get("fontw");
297 if (variables.containsKey("fonth")) {
298 fonth = (Integer) variables.get("fonth");
300 if (variables.containsKey("cols")) {
301 config.cols = (Integer) variables.get("cols");
303 if (variables.containsKey("rows")) {
304 config.rows = (Integer) variables.get("rows");
309 * Overridden to filter client-side calculation/changes and avoid loops.
313 public void setWidth(float width, int unit) {
314 if (width != getWidth() || unit != getWidthUnits()) {
315 super.setWidth(width, unit);
320 * Overridden to filter client-side calculation/changes and avoid loops.
324 public void setHeight(float height, int unit) {
325 if (height != getHeight() || unit != getHeightUnits()) {
326 super.setHeight(height, unit);
330 protected void handleSuggest(final String input) {
332 final boolean cancelIfNotASingleMatch = (input != null && !input
333 .equals(lastSuggestInput));
334 lastSuggestInput = input;
336 final Set<String> matches = handler.getSuggestions(this, input);
338 if (matches == null || matches.size() == 0) {
343 // Output the original
344 final String prefix = parseCommandPrefix(input);
345 String output = input.substring(0, input.lastIndexOf(prefix));
346 if (matches.size() == 1) {
347 // Output the only match
348 output += matches.iterator().next() + " "; // append the single
352 // We output until the common prefix
353 StringBuilder commonPrefix = new StringBuilder(prefix);
354 final int maxLen = matches.iterator().next().length();
355 for (int i = prefix.length(); i < maxLen; i++) {
357 boolean charMatch = true;
358 for (final String m : matches) {
361 } else if (i < m.length()) {
362 charMatch &= m.charAt(i) == c;
372 commonPrefix.append(c);
375 output += commonPrefix.toString();
376 if (prefix.equals(commonPrefix.toString())
377 && !cancelIfNotASingleMatch) {
378 final StringBuffer suggestions = new StringBuffer("\n");
379 for (final String m : matches) {
380 suggestions.append(" " + m);
382 print(suggestions.toString());
385 lastSuggestInput = output; // next suggest will not beep
397 protected void handleInput(final String input) {
399 // Ask registered handler
400 handler.inputReceived(this, input);
404 protected void parseAndExecuteCommand(final String input) {
405 final String[] argv = parseInput(input);
406 if (argv != null && argv.length > 0) {
407 final Command c = getCommand(argv[0]);
409 final String result = executeCommand(c, argv);
410 if (result != null) {
414 handler.commandNotFound(this, argv);
419 protected String executeCommand(final Command cmd, final String[] argv) {
421 final Object r = cmd.execute(this, argv);
422 return r != null ? "" + r : null;
423 } catch (final Exception e) {
424 handler.handleException(this, e, cmd, argv);
429 protected String parseCommandPrefix(final String input) {
433 if (!input.endsWith(" ")) {
434 final String[] argv = parseInput(input);
435 if (argv != null && argv.length > 0) {
436 return argv[argv.length - 1];
442 protected static String[] parseInput(final String input) {
443 if (input != null && !"".equals(input.trim())) {
444 final String[] temp = input.split(" ");
445 if (temp != null && temp.length > 0) {
446 final List<String> parsed = new ArrayList<String>(temp.length);
447 String current = null;
448 for (final String element : temp) {
449 final int quotCount = count(element, '\"');
450 if (quotCount > 0 && quotCount % 2 != 0) {
451 // uneven number of quotes star or end combining params
452 if (current != null) {
453 parsed.add(current + " "
454 + element.replaceAll("\"", "")); // end
457 current = element.replaceAll("\"", ""); // start
459 } else if (current != null) {
460 current += " " + element.replaceAll("\"", "");
462 parsed.add(element.replaceAll("\"", ""));
466 // TODO: actually this is not quite right: We have an open quote
467 // somewhere. Exception maybe?
468 if (current != null) {
469 parsed.add(current.replaceAll("\"", ""));
471 return parsed.toArray(new String[] {});
474 return new String[] {};
477 protected static int count(final String sourceString, final char lookFor) {
478 if (sourceString == null) {
482 for (int i = 0; i < sourceString.length(); i++) {
483 final char c = sourceString.charAt(i);
491 public void print(final String output) {
492 client.call("print", output);
497 * @param className CSS class name for string
499 public void print(final String output, final String className) {
500 client.call("print", output, className);
503 public String getGreeting() {
504 return config.greeting;
507 public String getPs() {
511 public int getMaxBufferSize() {
512 return config.maxBufferSize;
515 public int getRows() {
519 public void setGreeting(final String greeting) {
520 config.greeting = greeting;
521 client.call("setGreeting", greeting);
524 public void setPs(final String ps) {
525 config.ps = ps == null ? DEFAULT_PS : ps;
526 client.call("setPs", config.ps);
529 public void setMaxBufferSize(final int lines) {
530 config.maxBufferSize = lines > 0 ? lines : 0;
531 client.call("setMaxBufferSize", config.maxBufferSize);
534 public void setRows(final int rows) {
536 if (config.rows < 1) {
539 if (config.rows > MAX_ROWS) {
540 config.rows = MAX_ROWS;
542 client.call("setRows", rows);
545 public int getCols() {
549 public void setCols(final int cols) {
551 if (config.cols < 1) {
554 if (config.cols > MAX_COLS) {
555 config.cols = MAX_COLS;
557 client.call("setCols", config.cols);
560 public void prompt() {
561 client.call("prompt");
564 public void prompt(final String initialInput) {
565 client.call("prompt", initialInput);
568 public void println(final String string) {
569 client.call("println", string);
574 * @param className CSS class name for string
576 public void println(final String string, final String className) {
577 client.call("println", string, className);
580 public void append(final String string) {
581 client.call("append", string);
586 * @param className CSS class name for string
588 public void append(final String string, final String className) {
589 client.call("append", string, className);
592 public void newLine() {
593 client.call("newLine");
596 public void newLineIfNotEndsWithNewLine() {
597 client.call("newLineIfNotEndsWithNewLine");
600 public void reset() {
601 client.call("reset");
604 public void clear() {
608 public void formFeed() {
612 public void carriageReturn() {
616 public void lineFeed() {
620 public void clearCommandHistory() {
621 client.call("clearHistory");
624 public void clearBuffer() {
625 client.call("clearBuffer");
628 public void scrollToEnd() {
629 client.call("scrollToEnd");
632 public void focusInput() {
633 client.call("focusInput");
637 * Gets the Tabulator index of this Focusable component.
639 * @see com.vaadin.ui.Component.Focusable#getTabIndex()
641 public int getTabIndex() {
646 * Sets the Tabulator index of this Focusable component.
648 * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
650 public void setTabIndex(final int tabIndex) {
651 this.tabIndex = tabIndex;
658 public void focus() {
662 /* PrintStream implementation for console output. */
664 public PrintStream getPrintStream() {
665 if (printStream == null) {
666 printStream = new PrintStream(new OutputStream() {
668 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
671 public void write(final int b) throws IOException {
680 public void flush() throws IOException {
683 Console.this.print(buffer.toString());
691 /* Generic command handling */
694 * Add a Command to this Console.
696 * This will override the any commands of the same name available via
697 * {@link CommandProvider}.
699 public void addCommand(final String name, final Command cmd) {
700 commands.put(name, cmd);
704 * Remove a command from this console.
706 * This does not remove Command available from {@link CommandProvider}.
710 public void removeCommand(final String cmdName) {
711 commands.remove(cmdName);
715 * Get a Command by its name.
720 public Command getCommand(final String cmdName) {
722 // Try directly registered command first
723 Command cmd = commands.get(cmdName);
728 // Ask from the providers
729 if (commandProviders != null) {
730 for (final CommandProvider cp : commandProviders) {
731 cmd = cp.getCommand(this, cmdName);
743 * Get the current Console Handler.
747 public Handler getHandler() {
752 * Set the handler for this console.
757 public void setHandler(final Handler handler) {
758 this.handler = handler != null ? handler : new DefaultConsoleHandler();
762 * Get map of available commands in this Console.
766 public Set<String> getCommands() {
767 final Set<String> res = new HashSet<String>();
768 if (commandProviders != null) {
769 for (final CommandProvider cp : commandProviders) {
770 res.addAll(cp.getAvailableCommands(this));
773 res.addAll(commands.keySet());
774 return Collections.unmodifiableSet(res);