View Javadoc
1   package org.codehaus.plexus.util.cli;
2   
3   /*
4    * Copyright The Codehaus Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.io.OutputStream;
22  
23  import org.apache.commons.io.IOUtils;
24  
25  /**
26   * Read from an InputStream and write the output to an OutputStream.
27   * 
28   * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a>
29   * @version $Id$
30   */
31  public class StreamFeeder extends AbstractStreamHandler {
32  
33  	private InputStream input;
34  	private OutputStream output;
35  
36  	/**
37  	 * Create a new StreamFeeder
38  	 * 
39  	 * @param input
40  	 *            Stream to read from
41  	 * @param output
42  	 *            Stream to write to
43  	 */
44  	public StreamFeeder(InputStream input, OutputStream output) {
45  		this.input = input;
46  		this.output = output;
47  	}
48  
49  	// ----------------------------------------------------------------------
50  	// Runnable implementation
51  	// ----------------------------------------------------------------------
52  
53  	@Override
54  	public void run() {
55  		try {
56  			feed();
57  		} catch (Throwable ex) {
58  			// Catch everything so the streams will be closed and flagged as done.
59  		} finally {
60  			close();
61  			synchronized (this) {
62  				setDone();
63  				this.notifyAll();
64  			}
65  		}
66  	}
67  
68  	// ----------------------------------------------------------------------
69  	//
70  	// ----------------------------------------------------------------------
71  
72  	public void close() {
73  		if (input != null) {
74  			synchronized (input) {
75  				IOUtils.closeQuietly(input);
76  				input = null;
77  			}
78  		}
79  
80  		if (output != null) {
81  			synchronized (output) {
82  				IOUtils.closeQuietly(output);
83  				output = null;
84  			}
85  		}
86  	}
87  
88  	// ----------------------------------------------------------------------
89  	//
90  	// ----------------------------------------------------------------------
91  
92  	private void feed() throws IOException {
93  		int data = input.read();
94  
95  		while (!isDone() && data != -1) {
96  			synchronized (output) {
97  				if (!isDisabled()) {
98  					output.write(data);
99  				}
100 
101 				data = input.read();
102 			}
103 		}
104 	}
105 
106 }