| OLD | NEW | 
| (Empty) |  | 
 |   1 package org.adblockplus; | 
 |   2  | 
 |   3 import java.io.FilterOutputStream; | 
 |   4 import java.io.IOException; | 
 |   5 import java.io.OutputStream; | 
 |   6  | 
 |   7 /** | 
 |   8  * ChunkedOutputStream implements chunked HTTP transfer encoding wrapper for | 
 |   9  * OutputStream. | 
 |  10  */ | 
 |  11 public class ChunkedOutputStream extends FilterOutputStream | 
 |  12 { | 
 |  13   private static final byte[] CRLF = {'\r', '\n'}; | 
 |  14   private static final byte[] FINAL_CHUNK = new byte[] {'0', '\r', '\n', '\r', '
    \n'}; | 
 |  15   private boolean wroteFinalChunk = false; | 
 |  16  | 
 |  17   public ChunkedOutputStream(OutputStream out) | 
 |  18   { | 
 |  19     super(out); | 
 |  20   } | 
 |  21  | 
 |  22   @Override | 
 |  23   public void close() throws IOException | 
 |  24   { | 
 |  25     if (!wroteFinalChunk) | 
 |  26       writeFinalChunk(); | 
 |  27     super.close(); | 
 |  28   } | 
 |  29  | 
 |  30   @Override | 
 |  31   public void write(byte[] buffer, int offset, int length) throws IOException | 
 |  32   { | 
 |  33     writeChunk(buffer, offset, length); | 
 |  34   } | 
 |  35  | 
 |  36   @Override | 
 |  37   public void write(byte[] buffer) throws IOException | 
 |  38   { | 
 |  39     writeChunk(buffer, 0, buffer.length); | 
 |  40   } | 
 |  41  | 
 |  42   @Override | 
 |  43   public void write(int oneByte) throws IOException | 
 |  44   { | 
 |  45     throw new UnsupportedOperationException("Not implemented"); | 
 |  46   } | 
 |  47  | 
 |  48   public void writeFinalChunk() throws IOException | 
 |  49   { | 
 |  50     out.write(FINAL_CHUNK); | 
 |  51     out.flush(); | 
 |  52     wroteFinalChunk = true; | 
 |  53   } | 
 |  54  | 
 |  55   private void writeChunk(byte buffer[], int offset, int length) throws IOExcept
    ion | 
 |  56   { | 
 |  57     // Zero sized buffers are ok on slow connections but not in our case - zero | 
 |  58     // chunk is used to indicate the end of transfer. | 
 |  59     if (length > 0) | 
 |  60     { | 
 |  61       // Write the chunk length as a hex number | 
 |  62       writeHex(length); | 
 |  63       // Write the data | 
 |  64       out.write(buffer, offset, length); | 
 |  65       // Write a CRLF | 
 |  66       out.write(CRLF); | 
 |  67       // Flush the underlying stream | 
 |  68       out.flush(); | 
 |  69     } | 
 |  70   } | 
 |  71  | 
 |  72   private void writeHex(int i) throws IOException | 
 |  73   { | 
 |  74     out.write(Integer.toHexString(i).getBytes()); | 
 |  75     out.write(CRLF); | 
 |  76   } | 
 |  77 } | 
| OLD | NEW |