001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 * 
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 * 
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.launcher;
019
020import java.io.InputStream;
021import java.io.IOException;
022import java.io.OutputStream;
023
024 /**
025 * A class for connecting an OutputStream to an InputStream.
026 *
027 * @author Patrick Luby
028 */
029public class StreamConnector extends Thread {
030
031    //------------------------------------------------------------------ Fields
032
033    /**
034     * Input stream to read from.
035     */
036    private InputStream is = null;
037
038    /**
039     * Output stream to write to.
040     */
041    private OutputStream os = null;
042
043    //------------------------------------------------------------ Constructors
044
045    /**
046     * Specify the streams that this object will connect in the {@link #run()}
047     * method.
048     *
049     * @param is the InputStream to read from.
050     * @param os the OutputStream to write to.
051     */
052    public StreamConnector(InputStream is, OutputStream os) {
053
054        this.is = is;
055        this.os = os;
056
057    }
058
059    //----------------------------------------------------------------- Methods
060
061    /**
062     * Connect the InputStream and OutputStream objects specified in the
063     * {@link #StreamConnector(InputStream, OutputStream)} constructor.
064     */
065    public void run() {
066
067        // If the InputStream is null, don't do anything
068        if (is == null)
069            return;
070
071        // Connect the streams until the InputStream is unreadable
072        try {
073            int bytesRead = 0;
074            byte[] buf = new byte[4096];
075            while ((bytesRead = is.read(buf)) != -1) {
076                if (os != null && bytesRead > 0) {
077                    os.write(buf, 0, bytesRead);
078                    os.flush();
079                }
080                yield();
081            }
082        } catch (IOException e) {}
083
084    }
085
086}