1 package hudson.remoting; 2 3 import java.io.IOException ; 4 import java.io.InputStream ; 5 import java.io.OutputStream ; 6 import java.io.Serializable ; 7 8 17 final class ProxyInputStream extends InputStream { 18 private Channel channel; 19 private int oid; 20 21 27 public ProxyInputStream(Channel channel, int oid) throws IOException { 28 this.channel = channel; 29 this.oid = oid; 30 } 31 32 @Override 33 public int read() throws IOException { 34 try { 35 Buffer buf = new Chunk(oid, 1).call(channel); 36 if(buf.len==1) 37 return buf.buf[0]; 38 else 39 return -1; 40 } catch (InterruptedException e) { 41 Thread.currentThread().interrupt(); close(); 44 return -1; 45 } 46 } 47 48 @Override 49 public int read(byte b[], int off, int len) throws IOException { 50 try { 51 Buffer buf = new Chunk(oid,len).call(channel); 52 if(buf.len==-1) return -1; 53 System.arraycopy(buf.buf,0,b,off,buf.len); 54 return buf.len; 55 } catch (InterruptedException e) { 56 Thread.currentThread().interrupt(); close(); 59 return -1; 60 } 61 } 62 63 @Override 64 public synchronized void close() throws IOException { 65 if(channel!=null) { 66 channel.send(new EOF(oid)); 67 channel = null; 68 oid = -1; 69 } 70 } 71 72 protected void finalize() throws Throwable { 73 super.finalize(); 74 close(); 75 } 76 77 private static final class Buffer implements Serializable { 78 byte[] buf; 79 int len; 80 81 public Buffer(int len) { 82 this.buf = new byte[len]; 83 } 84 85 public void read(InputStream in) throws IOException { 86 len = in.read(buf,0,buf.length); 87 } 88 89 private static final long serialVersionUID = 1L; 90 } 91 92 95 private static final class Chunk extends Request<Buffer,IOException > { 96 private final int oid; 97 private final int len; 98 99 public Chunk(int oid, int len) { 100 this.oid = oid; 101 this.len = len; 102 } 103 104 protected Buffer perform(Channel channel) throws IOException { 105 InputStream in = (InputStream ) channel.getExportedObject(oid); 106 107 Buffer buf = new Buffer(len); 108 buf.read(in); 109 return buf; 110 } 111 } 112 113 116 private static final class EOF extends Command { 117 private final int oid; 118 119 public EOF(int oid) { 120 this.oid = oid; 121 } 122 123 124 protected void execute(Channel channel) { 125 InputStream in = (InputStream ) channel.getExportedObject(oid); 126 channel.unexport(oid); 127 try { 128 in.close(); 129 } catch (IOException e) { 130 } 132 } 133 134 public String toString() { 135 return "EOF("+oid+")"; 136 } 137 138 private static final long serialVersionUID = 1L; 139 } 140 } 141 | Popular Tags |