View Javadoc
1   package org.codehaus.plexus.util.cli;
2   
3   import java.io.BufferedReader;
4   import java.io.IOException;
5   import java.io.InputStream;
6   import java.io.InputStreamReader;
7   import java.io.PrintWriter;
8   
9   import org.codehaus.plexus.util.IOUtil;
10  
11  /**
12   * Class to pump the error stream during Process's runtime. Copied from the Ant built-in task.
13   */
14  public class StreamPumper extends AbstractStreamHandler {
15  
16  	private final BufferedReader in;
17  	private final StreamConsumer consumer;
18  	private final PrintWriter out;
19  	private volatile Exception exception = null;
20  	private static final int SIZE = 1024;
21  
22  	public StreamPumper(InputStream in) {
23  		this(in, (StreamConsumer) null);
24  	}
25  
26  	public StreamPumper(InputStream in, StreamConsumer consumer) {
27  		this(in, null, consumer);
28  	}
29  
30  	public StreamPumper(InputStream in, PrintWriter writer) {
31  		this(in, writer, null);
32  	}
33  
34  	public StreamPumper(InputStream in, PrintWriter writer, StreamConsumer consumer) {
35  		this.in = new BufferedReader(new InputStreamReader(in), SIZE);
36  		this.out = writer;
37  		this.consumer = consumer;
38  	}
39  
40  	@Override
41  	public void run() {
42  		try {
43  			for (String line = in.readLine(); line != null; line = in.readLine()) {
44  				try {
45  					if (exception == null) {
46  						consumeLine(line);
47  					}
48  				} catch (Exception t) {
49  					exception = t;
50  				}
51  
52  				if (out != null) {
53  					out.println(line);
54  					out.flush();
55  				}
56  			}
57  		} catch (IOException e) {
58  			exception = e;
59  		} finally {
60  			IOUtil.close(in);
61  			synchronized (this) {
62  				setDone();
63  				this.notifyAll();
64  			}
65  		}
66  	}
67  
68  	public void flush() {
69  		if (out != null) {
70  			out.flush();
71  		}
72  	}
73  
74  	public void close() {
75  		IOUtil.close(out);
76  	}
77  
78  	public Exception getException() {
79  		return exception;
80  	}
81  
82  	private void consumeLine(String line) {
83  		if (consumer != null && !isDisabled()) {
84  			consumer.consumeLine(line);
85  		}
86  	}
87  }