01: package groovy.ui;
02:
03: import groovy.lang.Closure;
04:
05: import java.io.FilterOutputStream;
06: import java.io.IOException;
07: import java.io.PrintStream;
08:
09: /**
10: * Intercepts System.out. Implementation helper for Console.groovy.
11: */
12: class SystemOutputInterceptor extends FilterOutputStream {
13:
14: private Closure callback;
15:
16: /**
17: * Constructor
18: *
19: * @param callback
20: * accepts a string to be sent to std out and returns a Boolean.
21: * If the return value is true, output will be sent to
22: * System.out, otherwise it will not.
23: */
24: public SystemOutputInterceptor(Closure callback) {
25: super (System.out);
26: this .callback = callback;
27: }
28:
29: /**
30: * Starts intercepting System.out
31: */
32: public void start() {
33: System.setOut(new PrintStream(this ));
34: }
35:
36: /**
37: * Stops intercepting System.out, sending output to whereever it was
38: * going when this interceptor was created.
39: */
40: public void stop() {
41: System.setOut((PrintStream) out);
42: }
43:
44: /**
45: * Intercepts output - moret common case of byte[]
46: */
47: public void write(byte[] b, int off, int len) throws IOException {
48: Boolean result = (Boolean) callback
49: .call(new String(b, off, len));
50: if (result.booleanValue()) {
51: out.write(b, off, len);
52: }
53: }
54:
55: /**
56: * Intercepts output - single characters
57: */
58: public void write(int b) throws IOException {
59: Boolean result = (Boolean) callback.call(String
60: .valueOf((char) b));
61: if (result.booleanValue()) {
62: out.write(b);
63: }
64: }
65: }
|