File: PipeThread.java

package info (click to toggle)
bbmap 39.20%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,024 kB
  • sloc: java: 312,743; sh: 18,099; python: 5,247; ansic: 2,074; perl: 96; makefile: 39; xml: 38
file content (89 lines) | stat: -rwxr-xr-x 1,888 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package fileIO;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Listens to an output stream and copies it to an input stream.
 * For example, redirects the error stream of some process to stderr.
 * @author Brian Bushnell
 * @date Jan 22, 2013
 *
 */
public class PipeThread extends Thread {
	
//	public PipeThread(InputStream is_){this(is_, System.err);}
	
	public PipeThread(InputStream is_, OutputStream os_){
		is=is_;
		os=os_;
		if(is==null){throw new RuntimeException("Null input stream.");}
		if(os==null){throw new RuntimeException("Null output stream.");}
//		synchronized(list){list.add(this);}
	}
	
	@Override
	public void run(){
		final byte[] buf=new byte[8196];
		try {
			for(int len=is.read(buf); !finished && len>0; len=is.read(buf)){
				os.write(buf, 0, len);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(is!=System.in){
			try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(os!=System.out && os!=System.err){
			ReadWrite.close(os);
		}
		
		synchronized(this){
			finished=true;
			this.notify();
		}
	}
	
	public boolean finished(){
		synchronized(this){
			return finished;
		}
	}
	
	public void terminate(){
		synchronized(this){
			if(!finished){
				finished=true;
				interrupt();
			}
		}
	}
	
//	public static void killList(){
//		System.err.println("Kill list.");
//		synchronized(list){
//			for(PipeThread pt : list){
//				if(!pt.finished){
//					pt.terminate();
//				}
//			}
//		}
//	}
	
	public final InputStream is;
	public final OutputStream os;
	private volatile boolean finished=false;
	
//	private static ArrayList<PipeThread> list=new ArrayList<PipeThread>(8);
	
}