commandinterpreter.java
来自「It is the Speech recognition software. 」· Java 代码 · 共 819 行 · 第 1/2 页
JAVA
819 行
* * @param name the name of the command. * @param command the command to be executed. * */ public void add(String name, CommandInterface command) { commandList.put(name, command); } /** * Adds an alias to the command * * @param command the name of the command. * @param alias the new aliase * */ public void addAlias(String command, String alias) { commandList.put(alias, commandList.get(command)); } /** * Add the given set of commands to the list * of commands. * @param newCommands the new commands to add to this interpreter. */ public void add(Map newCommands) { commandList.putAll(newCommands); } /** * Outputs a response to the sender. * * @param response the response to send. * */ public synchronized void putResponse(String response) { if (response != null && response.length() > 0) { out.println(response); out.flush(); if (trace) { System.out.println("Out: " + response); } } } /** * Called when the interpreter is exiting. Default behavior is * to execute an "on_exit" command. */ protected void onExit() { execute("on_exit"); System.out.println("----------\n"); } /** * Execute the given command. * * @param args command args, args[0] contains name of cmd. */ protected String execute(String[] args) { String response = ""; CommandInterface ci; if (args.length > 0) { ci = (CommandInterface) commandList.get(args[0]); if (ci != null) { response = ci.execute(this, args); } else { response = "ERR CMD_NOT_FOUND"; } totalCommands++; } return response; } /** * Execute the given command string. * * @param cmdString the command string. * */ public String execute(String cmdString) { if (trace) { System.out.println("Execute: " + cmdString); } return execute(parseMessage(cmdString)); } /** * Parses the given message into an array of strings. * * @param message the string to be parsed. * @return the parsed message as an array of strings */ protected String[] parseMessage(String message) { int tokenType; List words = new ArrayList(20); StreamTokenizer st = new StreamTokenizer(new StringReader(message)); st.resetSyntax(); st.whitespaceChars(0, ' '); st.wordChars('!', 255); st.quoteChar('"'); st.quoteChar('\"'); st.commentChar('#'); while (true) { try { tokenType = st.nextToken(); if (tokenType == StreamTokenizer.TT_WORD) { words.add(st.sval); } else if (tokenType == '\'' || tokenType == '"') { words.add(st.sval); } else if (tokenType == StreamTokenizer.TT_NUMBER) { System.out.println("Unexpected numeric token!"); } else { break; } } catch (IOException e) { break; } } return (String[]) words.toArray(new String[words.size()]); } // inherited from thread. public void run() { while (!done) { try { printPrompt(); String message = getInputLine(); if (message == null) { break; } else { if (trace) { System.out.println("\n----------"); System.out.println("In : " + message); } message = message.trim(); if (message.length() > 0) { putResponse(execute(message)); } } } catch (IOException e) { System.out.println("Exception: CommandInterpreter.run()"); break; } } onExit(); } // some history patterns used by getInputLine() private static Pattern historyPush = Pattern.compile("(.+):p"); private static Pattern editPattern = Pattern.compile("\\^(.+?)\\^(.*?)\\^?"); private static Pattern bbPattern= Pattern.compile("(!!)"); /** * Gets the input line. Deals with history. Currently we support * simple csh-like history. !! - execute last command, !-3 execute * 3 from last command, !2 execute second command in history list, * !foo - find last command that started with foo and execute it. * Also allows editing of the last command wich ^old^new^ type * replacesments * * @return the next history line or null if done */ private String getInputLine() throws IOException { String message = in.readLine(); boolean justPush = false; boolean echo = false; boolean error = false; Matcher m = historyPush.matcher(message); if (m.matches()) { justPush = true; echo = true; message = m.group(1); } if (message.startsWith("^")) { // line editing ^foo^fum^ m = editPattern.matcher(message); if (m.matches()) { String orig = m.group(1); String sub = m.group(2); try { Pattern pat = Pattern.compile(orig); Matcher subMatcher = pat.matcher(history.getLast(0)); if (subMatcher.find()) { message = subMatcher.replaceFirst(sub); echo = true; } else { error = true; putResponse(message + ": substitution failed"); } } catch (PatternSyntaxException pse) { error = true; putResponse("Bad regexp: " + pse.getDescription()); } } else { error = true; putResponse("bad substitution sytax, use ^old^new^"); } } else if ((m = bbPattern.matcher(message)).find()) { message = m.replaceAll(history.getLast(0)); echo = true; } else if (message.startsWith("!")) { if (message.matches("!\\d+")) { int which = Integer.parseInt(message.substring(1)); message = history.get(which); } else if (message.matches("!-\\d+")) { int which = Integer.parseInt(message.substring(2)); message = history.getLast(which - 1); } else { message = history.findLast(message.substring(1)); } echo = true; } if (error) { return ""; } if (message.length() > 0) { history.add(message); } if (echo) { putResponse(message); } return justPush ? "" : message; } public void close() { done = true; } /** * Prints the prompt. */ private void printPrompt() { if (prompt != null) { out.print(prompt); out.flush(); } } public boolean load(String filename) { try { FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); String inputLine; while ((inputLine = br.readLine()) != null) { String response = CommandInterpreter.this.execute(inputLine); if (!response.equals("OK")) { putResponse(response); } } fr.close(); return true; } catch (IOException ioe) { return false; } } /** * Sets the prompt for the interpreter * * @param prompt the prompt. * */ public void setPrompt(String prompt) { this.prompt = prompt; } /** * Gets the prompt for the interpreter * * @return the prompt. * */ public String getPrompt() { return prompt; } /** * Returns the output stream of this CommandInterpreter. * @return the output stream */ public PrintWriter getPrintWriter() { return out; } /** * manual tester for the command interpreter. * */ public static void main(String[] args) { CommandInterpreter ci = new CommandInterpreter(); try { System.out.println("Welcome to the Command interpreter test program"); ci.setPrompt("CI> "); ci.run(); System.out.println("Goodbye!"); } catch (Throwable t) { System.out.println(t); } } class CommandHistory { private List history = new ArrayList(100); /** * Adds a command to the history * * @param command the command to add */ public void add(String command) { history.add(command); } /** * Gets the most recent element in the history * * @param offset the offset from the most recent command * @return the last command executed */ public String getLast(int offset) { if (history.size() > offset) { return (String) history.get((history.size() - 1) - offset); } else { putResponse("command not found"); return ""; } } /** * Gets the most recent element in the history * * @param which the offset from the most recent command * @return the last command executed */ public String get(int which) { if (history.size() > which) { return (String) history.get(which); } else { putResponse("command not found"); return ""; } } /** * Finds the most recent message that starts with * the given string * * @param match the string to match * @return the last command executed that matches match */ public String findLast(String match) { for (int i = history.size() - 1; i >= 0; i--) { String cmd = get(i); if (cmd.startsWith(match)) { return cmd; } } putResponse("command not found"); return ""; } /** * Dumps the current history * */ public void dump() { for (int i = 0; i < history.size(); i++) { String cmd = get(i); putResponse(i + " " + cmd); } } }}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?