1 55 56 package org.jboss.axis.transport.http; 57 58 import java.io.IOException ; 59 import java.io.InputStream ; 60 61 public class NonBlockingBufferedInputStream extends InputStream 62 { 63 64 private InputStream in; 66 67 private int remainingContent = Integer.MAX_VALUE; 69 70 private byte[] buffer = new byte[4096]; 72 private int offset = 0; private int numbytes = 0; 75 80 public void setInputStream(InputStream in) 81 { 82 this.in = in; 83 numbytes = 0; 84 offset = 0; 85 remainingContent = (in == null) ? 0 : Integer.MAX_VALUE; 86 } 87 88 94 public void setContentLength(int value) 95 { 96 if (in != null) this.remainingContent = value - (numbytes - offset); 97 } 98 99 107 private void refillBuffer() throws IOException 108 { 109 if (remainingContent <= 0 || in == null) return; 110 111 numbytes = in.available(); 113 if (numbytes > remainingContent) numbytes = remainingContent; 114 if (numbytes > buffer.length) numbytes = buffer.length; 115 if (numbytes <= 0) numbytes = 1; 116 117 numbytes = in.read(buffer, 0, numbytes); 119 120 remainingContent -= numbytes; 122 offset = 0; 123 } 124 125 131 public int read() throws IOException 132 { 133 if (in == null) return -1; 134 if (offset >= numbytes) refillBuffer(); 135 if (offset >= numbytes) return -1; 136 return buffer[offset++]; 137 } 138 139 148 public int read(byte[] dest) throws IOException 149 { 150 return read(dest, 0, dest.length); 151 } 152 153 165 public int read(byte[] dest, int off, int len) throws IOException 166 { 167 int ready = numbytes - offset; 168 169 if (ready >= len) 170 { 171 System.arraycopy(buffer, offset, dest, off, len); 172 offset += len; 173 return len; 174 } 175 else if (ready > 0) 176 { 177 System.arraycopy(buffer, offset, dest, off, ready); 178 offset = numbytes; 179 return ready; 180 } 181 else 182 { 183 if (in == null) return -1; 184 refillBuffer(); 185 if (offset >= numbytes) return -1; 186 return read(dest, off, len); 187 } 188 } 189 190 197 public int skip(int len) throws IOException 198 { 199 int count = 0; 200 while (len-- > 0 && read() >= 0) count++; 201 return count; 202 } 203 204 209 public int available() throws IOException 210 { 211 if (in == null) return 0; 212 213 return (numbytes - offset) + in.available(); 215 } 216 217 220 public void close() throws IOException 221 { 222 setInputStream(null); 223 } 224 225 232 public int peek() throws IOException 233 { 234 if (in == null) return -1; 235 if (offset >= numbytes) refillBuffer(); 236 if (offset >= numbytes) return -1; 237 return buffer[offset]; 238 } 239 } 240 241 | Popular Tags |