1 16 17 package org.apache.axis.transport.http; 18 19 import java.io.IOException ; 20 import java.io.InputStream ; 21 22 public class NonBlockingBufferedInputStream extends InputStream { 23 24 private InputStream in; 26 27 private int remainingContent = Integer.MAX_VALUE; 29 30 private byte[] buffer = new byte[4096]; 32 private int offset = 0; private int numbytes = 0; 35 39 public void setInputStream (InputStream in) { 40 this.in = in; 41 numbytes = 0; 42 offset = 0; 43 remainingContent = (in==null)? 0 : Integer.MAX_VALUE; 44 } 45 46 51 public void setContentLength (int value) { 52 if (in != null) this.remainingContent = value - (numbytes-offset); 53 } 54 55 62 private void refillBuffer() throws IOException { 63 if (remainingContent <= 0 || in == null) return; 64 65 numbytes = in.available(); 67 if (numbytes > remainingContent) numbytes=remainingContent; 68 if (numbytes > buffer.length) numbytes=buffer.length; 69 if (numbytes <= 0) numbytes = 1; 70 71 numbytes = in.read(buffer, 0, numbytes); 73 74 remainingContent -= numbytes; 76 offset = 0; 77 } 78 79 84 public int read() throws IOException { 85 if (in == null) return -1; 86 if (offset >= numbytes) refillBuffer(); 87 if (offset >= numbytes) return -1; 88 return buffer[offset++] & 0xFF; 89 } 90 91 99 public int read(byte[] dest) throws IOException { 100 return read(dest, 0, dest.length); 101 } 102 103 114 public int read(byte[] dest, int off, int len) throws IOException { 115 int ready = numbytes - offset; 116 117 if (ready >= len) { 118 System.arraycopy(buffer, offset, dest, off, len); 119 offset += len; 120 return len; 121 } else if (ready>0) { 122 System.arraycopy(buffer, offset, dest, off, ready); 123 offset = numbytes; 124 return ready; 125 } else { 126 if (in == null) return -1; 127 refillBuffer(); 128 if (offset >= numbytes) return -1; 129 return read(dest,off,len); 130 } 131 } 132 133 139 public int skip(int len) throws IOException { 140 int count = 0; 141 while (len-->0 && read()>=0) count++; 142 return count; 143 } 144 145 149 public int available() throws IOException { 150 if (in == null) return 0; 151 152 return (numbytes-offset) + in.available(); 154 } 155 156 159 public void close() throws IOException { 160 setInputStream(null); 161 } 162 163 169 public int peek() throws IOException { 170 if (in == null) return -1; 171 if (offset >= numbytes) refillBuffer(); 172 if (offset >= numbytes) return -1; 173 return buffer[offset] & 0xFF; 174 } 175 } 176 177 | Popular Tags |