View Javadoc

    1   package groovy.ui;
    2
    3   import groovy.lang.Closure;
    4
    5   import java.io.FilterOutputStream;
    6   import java.io.IOException;
    7   import java.io.PrintStream;
    8
    9   /***
    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.call(new String(b, off, len));
    49  		if (result.booleanValue()) {
    50  			out.write(b, off, len);
    51  		}
    52  	}
    53
    54  	/***
    55  	 * Intercepts output - single characters
    56  	 */
    57  	public void write(int b) throws IOException {
    58  		Boolean result = (Boolean) callback.call(String.valueOf((char) b));
    59  		if (result.booleanValue()) {
    60  			out.write(b);
    61  		}
    62  	}
    63  }