/* this belongs to the WebRaveler package */ package webraveler.io; import java.io.*; /** * OutputStream that uses Chunked encoding * * @author The Web Raveler Development Squad * @version 1.0 */ public class ChunkedOutputStream extends OutputStream{ /* instance variables */ OutputStream output; int count= 0; boolean closed= false; byte buf[]; /* constructors */ /** * */ public ChunkedOutputStream(OutputStream out){ output= out; buf= new byte[1024]; } /* instance methods */ /** * Closes the output stream and forces any buffered output bytes to be written out. */ public void close() throws IOException{ flush(); output.write("0\r\n\r\n\r\n".getBytes()); output.flush(); } /** * Flushes the output stream and forces any buffered output bytes to be written out. */ public void flush() throws IOException{ sendBuffer(buf, 0, count); count= 0; output.flush(); } /** * Writes a specified length of bytes to the output stream starting at the offset * * @param b a byte array to be written on the output stream * @param offset an integer representing the offset * @param length an integer representing the length to be written */ public void sendBuffer(byte[] b, int offset, int length) throws IOException{ if( length <= 0 ) return; output.write(Integer.toHexString(length).getBytes()); output.write("\r\n".getBytes()); output.write(b,offset,length); output.write("\r\n".getBytes()); } /** * Writes a byte to the output stream * * @param c an integer representing the byte to be written */ public void write(int c) throws IOException{ if( closed ) throw new IOException(); if( count < buf.length){ buf[count++]= (byte)c; } else { sendBuffer(buf, 0, count); count= 0; write(c); } } /** * Writes the specified bytes to the output stream * * @param b a byte array to be written on the output stream * @param offset an integer representing the offset * @param length an integer representing the length to be written */ public void write(byte[] source, int offset, int length) throws IOException{ sendBuffer(buf,0,count); count= 0; sendBuffer(source, offset, length); } }