/* this belongs to the WebRaveler package */ package webraveler.io; import java.io.*; import webraveler.http.HTTPMessage; /** * InputStream that decodes Chunked encoding * * @author The Web Raveler Development Squad * @version 1.0 */ public class ChunkedInputStream extends InputStream{ /* instance variables */ InputStream input; int bytesLeft= -1; boolean closed= false; /* constructors */ /** * */ public ChunkedInputStream(InputStream input){ this.input = input; } /* instance methods */ /** * Reads a byte from the input stream * * @return an int representing the byte read */ public int read() throws IOException{ if(closed) return -1; if( bytesLeft > 0 ){ //read from chunk bytesLeft--; return input.read(); } else { //new chunk, so read its length String line; if( bytesLeft == 0) //first line, no extra crlf HTTPMessage.readLine(input); line= HTTPMessage.readLine(input); try{ int c= line.indexOf(' '); if(c < 0) c= line.indexOf('\r'); if(c < 0) c= line.indexOf('\n'); if(c < 0) c= line.length(); bytesLeft= Integer.parseInt(line.substring(0,c), 16); } catch(NumberFormatException e){ throw new IOException("Bad Transfer Encoding"); } if( bytesLeft == 0 ) {//we found the terminating chunk closed= true; while( (line= HTTPMessage.readLine(input)) != null && line.length() > 0); //clear trailers } return read(); } } /** * Closes the input streams */ public void close() throws IOException{ } }