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 /**
24 * Read from an InputStream and write the output to an OutputStream.
25 *
26 * @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
27 * @version $Id$
28 */
29 public class StreamFeeder extends AbstractStreamHandler {
30 private InputStream input;
31
32 private OutputStream output;
33
34
35 /**
36 * Create a new StreamFeeder
37 *
38 * @param input Stream to read from
39 * @param output Stream to write to
40 */
41 public StreamFeeder( InputStream input, OutputStream output )
42 {
43 this.input = input;
44
45 this.output = output;
46 }
47
48 // ----------------------------------------------------------------------
49 // Runnable implementation
50 // ----------------------------------------------------------------------
51
52 public void run()
53 {
54 try
55 {
56 feed();
57 }
58 catch ( Throwable ex )
59 {
60 // Catched everything so the streams will be closed and flagged as done.
61 }
62 finally
63 {
64 close();
65
66 synchronized ( this )
67 {
68 setDone();
69
70 this.notifyAll();
71 }
72 }
73 }
74
75 // ----------------------------------------------------------------------
76 //
77 // ----------------------------------------------------------------------
78
79 public void close()
80 {
81 if ( input != null )
82 {
83 synchronized ( input )
84 {
85 try
86 {
87 input.close();
88 }
89 catch ( IOException ex )
90 {
91 // ignore
92 }
93
94 input = null;
95 }
96 }
97
98 if ( output != null )
99 {
100 synchronized ( output )
101 {
102 try
103 {
104 output.close();
105 }
106 catch ( IOException ex )
107 {
108 // ignore
109 }
110
111 output = null;
112 }
113 }
114 }
115
116 // ----------------------------------------------------------------------
117 //
118 // ----------------------------------------------------------------------
119
120 private void feed()
121 throws IOException
122 {
123 int data = input.read();
124
125 while ( !isDone() && data != -1 )
126 {
127 synchronized ( output )
128 {
129 if ( !isDisabled())
130 {
131 output.write( data );
132 }
133
134 data = input.read();
135 }
136 }
137 }
138
139 }