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 */
018
019 package org.apache.commons.exec;
020
021 import org.apache.commons.exec.util.DebugUtils;
022
023 import java.io.InputStream;
024 import java.io.OutputStream;
025
026 /**
027 * Copies all data from an System.input stream to an output stream of the executed process.
028 *
029 * @author mkleint
030 */
031 public class InputStreamPumper implements Runnable {
032
033 public static final int SLEEPING_TIME = 100;
034
035 /** the input stream to pump from */
036 private final InputStream is;
037
038 /** the output stream to pmp into */
039 private final OutputStream os;
040
041 /** flag to stop the stream pumping */
042 private volatile boolean stop;
043
044
045 /**
046 * Create a new stream pumper.
047 *
048 * @param is input stream to read data from
049 * @param os output stream to write data to.
050 */
051 public InputStreamPumper(final InputStream is, final OutputStream os) {
052 this.is = is;
053 this.os = os;
054 this.stop = false;
055 }
056
057
058 /**
059 * Copies data from the input stream to the output stream. Terminates as
060 * soon as the input stream is closed or an error occurs.
061 */
062 public void run() {
063 try {
064 while (!stop) {
065 while (is.available() > 0 && !stop) {
066 os.write(is.read());
067 }
068 os.flush();
069 Thread.sleep(SLEEPING_TIME);
070 }
071 } catch (Exception e) {
072 String msg = "Got exception while reading/writing the stream";
073 DebugUtils.handleException(msg ,e);
074 } finally {
075 }
076 }
077
078
079 public void stopProcessing() {
080 stop = true;
081 }
082
083 }