/Users/lyon/j4p/src/ip/gui/CommandLineInterpreter.java
|
1 package ip.gui;
2
3 import ip.gui.dialog.MessLog;
4
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7 import java.io.BufferedReader;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.InputStreamReader;
11 import java.lang.reflect.Method;
12 import java.util.StringTokenizer;
13
14
15 public class CommandLineInterpreter
16 implements ActionListener {
17
18 private Object delegate;
19 private InputStream
20 commandInputStream = System.in;
21
22 public CommandLineInterpreter(Object o) {
23 delegate = o;
24 }
25
26 public void setInputStream(InputStream is) {
27 commandInputStream = is;
28 }
29
30 public void actionPerformed(ActionEvent e) {
31 invokeMethodString(e.getActionCommand());
32 }
33
34 public void invokeMethodString(String line) {
35 StringTokenizer st = new StringTokenizer(line);
36 while (st.hasMoreTokens()) {
37 String toks = st.nextToken();
38 Object o = null;
39 try {
40 Class parentClass
41 = delegate.getClass();
42
43 Method m =
44 parentClass.getMethod(
45 toks,
46 new Class[]{});
47
48 m.invoke(delegate, null);
49 } catch (Exception e) {
50 MessLog.error(e);
51 }
52 }
53 }
54
55 /**
56 commandLine - this should be
57 improved using a queue of commands that
58 are executed in a thread. Thus the commandLine
59 reader could just enqueue the commands for
60 execution at a later time (when
61 free cycles are available). As it is, a prompt
62 does not appear until the command is finished.
63 Worse, input is not accepted from the user,
64 so no type-ahead is possible. Type-ahead
65 should be possible, but I am not sure how
66 to implement it. Suggestions?
67 - DL
68
69 */
70 public void runCommandLineInterpreter() {
71 InputStreamReader isr =
72 new InputStreamReader(commandInputStream);
73 BufferedReader br = new BufferedReader(isr);
74 System.out.print(">");
75 String line = null;
76 try {
77 while ((line = br.readLine()) != null) {
78 if (line.equals("quit"))
79 return;
80 invokeMethodString(line);
81 System.out.print(">");
82 }
83 } catch (IOException e) {
84 System.out.println(e);
85 }
86 }
87 }