1 18 19 package com.martiansoftware.nailgun; 20 21 import java.io.FilterInputStream ; 22 import java.io.IOException ; 23 24 30 class NGInputStream extends FilterInputStream { 31 32 private byte[] header; 33 private boolean eof = false; 34 private long remaining = 0; 35 36 40 public NGInputStream(java.io.InputStream in) { 41 super(in); 42 header = new byte[5]; 43 } 44 45 51 private void readHeader() throws IOException { 52 if (eof) return; 53 54 int bytesRead = in.read(header); 55 int thisPass = 0; 56 while (bytesRead < 5) { 57 thisPass = in.read(header, bytesRead, 5 - bytesRead); 58 if (thisPass < 0) { 59 eof = true; 60 return; 61 } 62 bytesRead += thisPass; 63 } 64 switch(header[4]) { 65 case NGConstants.CHUNKTYPE_STDIN: 66 remaining = LongUtils.fromArray(header, 0); 67 break; 68 69 case NGConstants.CHUNKTYPE_STDIN_EOF: 70 eof = true; 71 break; 72 73 default: throw(new IOException ("Unknown stream type: " + (char) header[4])); 74 } 75 } 76 77 80 public int available() throws IOException { 81 if (eof) return(0); 82 if (remaining > 0) return (in.available()); 83 return (Math.max(0, in.available() - 5)); 84 } 85 86 89 public boolean markSupported() { 90 return (false); 91 } 92 93 96 public int read() throws IOException { 97 return((read(header, 0, 1) == -1) ? -1 : (int) header[0]); 101 } 102 103 106 public int read(byte[] b) throws IOException { 107 return (read(b, 0, b.length)); 108 } 109 110 113 public int read(byte[] b, int offset, int length) throws IOException { 114 if (remaining == 0) readHeader(); 115 if (eof) return(-1); 116 117 int bytesToRead = Math.min((int) remaining, length); 118 int result = in.read(b, offset, bytesToRead); 119 remaining -= result; 120 return (result); 121 } 122 123 } 124 | Popular Tags |