1 5 package com.oreilly.servlet.multipart; 6 7 import java.io.FilterInputStream ; 8 import java.io.IOException ; 9 import javax.servlet.ServletInputStream ; 10 11 31 public class PartInputStream extends FilterInputStream { 32 33 private String boundary; 34 35 36 private byte [] buf = new byte[64*1024]; 38 39 private int count; 40 41 42 private int pos; 43 44 45 private boolean eof; 46 47 54 PartInputStream(ServletInputStream in, 55 String boundary) throws IOException { 56 super(in); 57 this.boundary = boundary; 58 } 59 60 69 private void fill() throws IOException 70 { 71 if (eof) 72 return; 73 74 if (count > 0) 76 { 77 if (count - pos == 2) { 79 System.arraycopy(buf, pos, buf, 0, count - pos); 81 count -= pos; 82 pos = 0; 83 } else { 84 throw new IllegalStateException ("fill() detected illegal buffer state"); 86 } 87 } 88 89 int read = 0; 93 int boundaryLength = boundary.length(); 94 int maxRead = buf.length - boundaryLength - 2; while (count < maxRead) { 96 read = ((ServletInputStream )in).readLine(buf, count, buf.length - count); 98 if (read == -1) { 100 throw new IOException ("unexpected end of part"); 101 } else { 102 if (read >= boundaryLength) { 103 eof = true; 104 for (int i=0; i < boundaryLength; i++) { 105 if (boundary.charAt(i) != buf[count + i]) { 106 eof = false; 108 break; 109 } 110 } 111 if (eof) { 112 break; 113 } 114 } 115 } 116 count += read; 118 } 119 } 120 121 132 public int read() throws IOException { 133 if (count - pos <= 2) { 134 fill(); 135 if (count - pos <= 2) { 136 return -1; 137 } 138 } 139 return buf[pos++] & 0xff; 140 } 141 142 155 public int read(byte b[]) throws IOException { 156 return read(b, 0, b.length); 157 } 158 159 174 public int read(byte b[], int off, int len) throws IOException 175 { 176 int total = 0; 177 if (len == 0) { 178 return 0; 179 } 180 181 int avail = count - pos - 2; 182 if (avail <= 0) { 183 fill(); 184 avail = count - pos - 2; 185 if(avail <= 0) { 186 return -1; 187 } 188 } 189 int copy = Math.min(len, avail); 190 System.arraycopy(buf, pos, b, off, copy); 191 pos += copy; 192 total += copy; 193 194 while (total < len) { 195 fill(); 196 avail = count - pos - 2; 197 if(avail <= 0) { 198 return total; 199 } 200 copy = Math.min(len - total, avail); 201 System.arraycopy(buf, pos, b, off + total, copy); 202 pos += copy; 203 total += copy; 204 } 205 return total; 206 } 207 208 218 public int available() throws IOException { 219 int avail = (count - pos - 2) + in.available(); 220 return (avail < 0 ? 0 : avail); 222 } 223 224 236 public void close() throws IOException { 237 if (!eof) { 238 while (read(buf, 0, buf.length) != -1) 239 ; } 241 } 242 } 243 | Popular Tags |