001 package nl.cwi.sen1.consolegrabber; 002 003 import java.io.BufferedReader; 004 import java.io.InputStreamReader; 005 import java.io.IOException; 006 import java.util.Scanner; 007 import java.util.regex.MatchResult; 008 009 import aterm.ATerm; 010 import aterm.pure.PureFactory; 011 012 public class ConsoleGrabber implements ConsoleGrabberTif { 013 private ConsoleGrabberBridge bridge; 014 015 private PureFactory pureFactory = new PureFactory(); 016 017 public ConsoleGrabber(String[] args) { 018 bridge = new ConsoleGrabberBridge(pureFactory, this); 019 try { 020 bridge.init(args); 021 bridge.connect(); 022 } catch (IOException e) { 023 System.err.println("Could not establish connection to ToolBus: "+ e); 024 System.exit(1); 025 } 026 027 Thread thread = new Thread(new Runnable() { 028 public void run() { 029 try { 030 bridge.run(); 031 } catch (java.lang.RuntimeException e) { 032 e.printStackTrace(); 033 } 034 } 035 }); 036 thread.setName("ConsoleGrabber"); 037 thread.start(); 038 } 039 040 public void sendMessage(String message) { 041 ATerm event = pureFactory.make("console-message(<str>)", message); 042 bridge.postEvent(event); 043 } 044 045 public static void main(String[] args) throws IOException{ 046 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 047 String line = null; 048 int maxTries = 100; 049 050 while (maxTries-- > 0 && (line = br.readLine()) != null) { 051 try { 052 Scanner s = new Scanner(line); 053 s.findInLine("The ToolBus server allocated port \\((\\d+)\\)"); 054 MatchResult result = s.match(); 055 056 System.out.println(line); // Print the message we matched on. 057 058 String port = result.group(1); 059 args = buildToolArgs(port); 060 061 ConsoleGrabber grabber = new ConsoleGrabber(args); 062 063 // Eat up all input and send it line by line to the ToolBus 064 while((line = br.readLine()) != null) { 065 grabber.sendMessage(line + "\n"); 066 } 067 068 break; // End of file 069 } catch (IllegalStateException e) { 070 // ToolBus port not yet found, echo the input to stderr 071 System.err.println(line); 072 } 073 } 074 075 if (maxTries == 0) { 076 System.err.println("console-grabber: failed to find ToolBus port. Continuing to print on stderr..."); 077 078 // If we have something to print left, simply print it 079 while((line = br.readLine()) != null){ 080 System.err.print(line); 081 } 082 } 083 084 br.close(); 085 } 086 087 private static String[] buildToolArgs(String port) { 088 String[] args; 089 args = new String[6]; 090 args[0] = "-TB_HOST"; 091 args[1] = "localhost"; 092 args[2] = "-TB_PORT"; 093 args[3] = port; 094 args[4] = "-TB_TOOL_NAME"; 095 args[5] = "console-grabber"; 096 return args; 097 } 098 099 public void recTerminate(ATerm t0) { 100 //System.exit(0); 101 } 102 103 public void recAckEvent(ATerm t0) { 104 } 105 }