(no commit message)
[utils] / socketproxy / src / org / wamblee / socketproxy / ForwarderThread.java
1 package org.wamblee.socketproxy;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6
7 /**
8  * Forwarder thread which handles forwarding of an input stream to
9  * an output stream. 
10  */
11
12 public class ForwarderThread extends Thread {
13
14     private String _prefix;
15
16     private Barrier _barrier;
17
18     private InputStream _is;
19
20     private OutputStream _os;
21
22     /**
23      * Constructs the forwarder thread.
24      * @param aPrefix Prefix to use in the output. 
25      * @param aBarrier Barrier to block on before actually closing the stream. 
26      *        This is done to make sure that connections are only closed in th e
27      *        proxy when the forwarders in both directions are ready to close. 
28      * @param aIs Input stream to read from.
29      * @param aOs Output stream to forward to.
30      */
31     public ForwarderThread( String aPrefix, Barrier aBarrier,
32             InputStream aIs, OutputStream aOs ) {
33         _prefix = aPrefix;
34         _is = aIs;
35         _os = aOs;
36         _barrier = aBarrier;
37     }
38
39     public void run( ) {
40         boolean firstChar = true;
41         try {
42             int c = _is.read( );
43             while ( c > 0 ) {
44                 try {
45                     _os.write( c );
46                     _os.flush( );
47                     if ( firstChar ) {
48                         System.out.print( _prefix );
49                         firstChar = false;
50                     }
51                     System.out.print( (char) c );
52                     if ( c == '\n' ) {
53                         firstChar = true;
54                     }
55                 } catch ( IOException e ) {
56                 }
57
58                 c = _is.read( );
59             }
60         } catch ( IOException e ) {
61         }
62         closeStreams();
63     }
64
65     /**
66      * @param is
67      * @param os
68      */
69     private void closeStreams( ) {
70         _barrier.block( ); // wait until the other forwarder for the other direction
71                            // is also closed.
72         try {
73             _is.close( );
74         } catch ( IOException e1 ) {
75             // Empty.
76         }
77         try {
78             _os.flush( );
79             _os.close( );
80         } catch ( IOException e1 ) {
81             // Empty
82         }
83         System.out.println(_prefix + " closed");
84     }
85
86 }