1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.launcher;
19
20 import java.io.InputStream;
21 import java.io.IOException;
22 import java.io.OutputStream;
23
24 /**
25 * A class for connecting an OutputStream to an InputStream.
26 *
27 * @author Patrick Luby
28 */
29 public class StreamConnector extends Thread {
30
31 //------------------------------------------------------------------ Fields
32
33 /**
34 * Input stream to read from.
35 */
36 private InputStream is = null;
37
38 /**
39 * Output stream to write to.
40 */
41 private OutputStream os = null;
42
43 //------------------------------------------------------------ Constructors
44
45 /**
46 * Specify the streams that this object will connect in the {@link #run()}
47 * method.
48 *
49 * @param is the InputStream to read from.
50 * @param os the OutputStream to write to.
51 */
52 public StreamConnector(InputStream is, OutputStream os) {
53
54 this.is = is;
55 this.os = os;
56
57 }
58
59 //----------------------------------------------------------------- Methods
60
61 /**
62 * Connect the InputStream and OutputStream objects specified in the
63 * {@link #StreamConnector(InputStream, OutputStream)} constructor.
64 */
65 public void run() {
66
67 // If the InputStream is null, don't do anything
68 if (is == null)
69 return;
70
71 // Connect the streams until the InputStream is unreadable
72 try {
73 int bytesRead = 0;
74 byte[] buf = new byte[4096];
75 while ((bytesRead = is.read(buf)) != -1) {
76 if (os != null && bytesRead > 0) {
77 os.write(buf, 0, bytesRead);
78 os.flush();
79 }
80 yield();
81 }
82 } catch (IOException e) {}
83
84 }
85
86 }