1 package example; 2 3 import com.caucho.util.L10N; 4 import java.util.logging.Logger ; 5 import java.util.logging.Level ; 6 7 import com.caucho.vfs.ReadStream; 8 import java.io.IOException ; 9 import java.util.HashMap ; 10 11 17 public class Parser { 18 static protected final Logger log = 19 Logger.getLogger(Parser.class.getName()); 20 static final L10N L = new L10N(Parser.class); 21 22 private ReadStream _readStream; 24 String _error; 25 26 private StringBuffer _buffer = new StringBuffer (); 28 29 private HashMap _commands = new HashMap (); 31 32 public Parser() 33 { 34 _commands.put("set-prophet",new SetProphetCommand()); 35 _commands.put("ask",new AskCommand()); 36 } 37 38 public void init(ReadStream readStream) 39 { 40 _readStream = readStream; 41 _error = null; 42 } 43 44 45 52 public AbstractCommand nextCommand() 53 throws IOException 54 { 55 String cmd = parseToken(); 56 if (cmd == null) { 57 return null; 58 } 59 AbstractCommand command = (AbstractCommand) _commands.get(cmd.toLowerCase()); 60 61 if (command == null) { 62 _error = "Unknown command `" + cmd + "'"; 63 } else { 64 command.parse(this); 65 if (command.isError()) { 66 _error = command.getError(); 67 command = null; 68 } 69 } 70 71 return command; 72 } 73 74 public boolean isError() 75 { 76 return _error != null; 77 } 78 79 public String getError() 80 { 81 return _error; 82 } 83 84 85 88 boolean isEOS(int ch) 89 { 90 return ch < 0; 91 } 92 93 96 boolean isWhitespace(int ch) 97 { 98 return isEOS(ch) || Character.isWhitespace((char) ch); 99 } 100 101 107 int eatWhitespace() 108 throws IOException 109 { 110 int ch; 111 while (!isEOS(ch = _readStream.read())) { 112 if (!isWhitespace(ch)) { 113 _readStream.unread(); 114 break; 115 } 116 } 117 return ch; 118 } 119 120 125 126 String parseToken() 127 throws IOException 128 { 129 String token = null; 130 131 int ch = eatWhitespace(); 132 133 if (ch >= 0) { 134 _buffer.setLength(0); 135 136 while (!isEOS(ch = _readStream.read())) { 137 if (isWhitespace(ch)) { 138 _readStream.unread(); 139 break; 140 } 141 _buffer.append((char)ch); 142 } 143 token = _buffer.toString(); 144 } 145 146 return token; 147 } 148 } 149 150 | Popular Tags |