1 10 package org.mmbase.util.externalprocess; 11 12 import java.io.BufferedOutputStream ; 13 import java.io.BufferedInputStream ; 14 import java.io.InputStream ; 15 import java.io.OutputStream ; 16 import java.io.IOException ; 17 18 import org.mmbase.util.logging.Logger; 19 import org.mmbase.util.logging.Logging; 20 21 29 class StreamCopyThread extends Thread { 30 31 32 private static Logger log = Logging.getLoggerInstance(StreamCopyThread.class.getName()); 33 34 37 protected static final long WAIT_DELAY = 25; 38 39 42 public static final int BUFFER_SIZE = 1024; 43 44 47 private InputStream inputStream; 48 49 52 private OutputStream outputStream; 53 54 57 private boolean processInput = false; 58 59 62 private boolean finished = false; 63 64 72 public StreamCopyThread(String name, InputStream in, OutputStream out, boolean pInput) { 73 this(null, name, in, out, pInput); 74 } 75 76 86 public StreamCopyThread( 87 ThreadGroup group, 88 String name, 89 InputStream in, 90 OutputStream out, 91 boolean pInput) { 92 super(group, name); 93 processInput = pInput; 94 outputStream = out; 95 inputStream = in; 96 setDaemon(true); 97 } 98 99 102 public void run() { 103 BufferedInputStream reader = new BufferedInputStream (inputStream); 104 BufferedOutputStream writer = null; 105 if (outputStream != null) { 106 writer = new BufferedOutputStream (outputStream); 107 } 108 try { 109 116 try { 117 Thread.sleep(WAIT_DELAY); 118 } catch (InterruptedException e) { 119 } 121 122 int size = 0; 123 byte[] buffer = new byte[StreamCopyThread.BUFFER_SIZE]; 125 126 while ((size = reader.read(buffer)) != -1) { 127 if (writer != null) { 128 writer.write(buffer, 0, size); 129 writer.flush(); 130 } 131 133 } 137 } catch (IOException x) { 138 } finally { 140 147 if (processInput) { 148 try { 149 if (writer != null) { 150 writer.close(); 151 } 152 } catch (IOException e) { 153 } 155 } else { 156 try { 157 if (reader != null) { 158 reader.close(); 159 } 160 } catch (IOException e) { 161 } 163 } 164 complete(); 165 } 166 } 167 168 173 public synchronized boolean finished() { 174 return finished; 175 } 176 177 181 public synchronized void waitFor() { 182 while (!finished) { 183 try { 184 wait(); 185 } catch (InterruptedException e) {} 186 } 187 } 188 189 193 protected synchronized void complete() { 194 finished = true; 195 notify(); 196 log.debug("StreamCopy " + this.getName() + " finished."); 197 } 198 } | Popular Tags |