1

I'd like to adapt the code below to use a ANTLRReaderStream so I don't have to create a new parser for each line. But it needs to process each line individually, which I don't have any idea how to do currently, and I don't see any way to ask the parser whether it has data ready (or whatever would be the equivalent of String line = stdin.readLine().

main loop:

stdin = new BufferedReader(new InputStreamReader(System.in));

while (true) {
    String line = stdin.readLine();
    if (line == null) {
        System.exit(0);
    }

    processLine(line.trim());
}

handle a single line:

public void processLine(String line) throws IOException {
    try {
        QuotaControlCommandsLexer lexer = new QuotaControlCommandsLexer();
        lexer.setCharStream(new ANTLRStringStream(line));           
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        QuotaControlCommandsParser parser = new QuotaControlCommandsParser(tokens);

        Command cmd = parser.command();
        boolean result = cmd.execute();         
        output(result ? "1" : "0");
        stdout.flush();
    }
    catch (RecognitionException e) {
        logger.error("invalid command: " + line);
        output("ERROR: invalid command `" + line + "`");
    }
}
Brad Mace
  • 27,194
  • 17
  • 102
  • 148

1 Answers1

1

If using JDK1.6 we can do the main loop as the following:

    Console console = System.console();

    if (console != null) {
        String line = null;

        while ((line = console.readLine()) != null) {
            processLine(line.trim());
        }
    } else {
        System.out.println("No console available!!");
    }
Zecas
  • 647
  • 4
  • 23
  • The goal was to find an implementation that doesn't require creating a new parser and lexer instance for each line of input. It looks like this would involve `ANTLRReaderStream` but I haven't been able to determine how to use it for this. – Brad Mace Jul 10 '12 at 14:33
  • fair enough, sorry for the trouble – Zecas Jul 11 '12 at 14:58