Created
August 27, 2013 14:46
-
-
Save slorber/6354490 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class FeedBodyGeneratorOutputStream extends OutputStream { | |
private static final HeapBuffer EMPTY_BUFFER = HeapBuffer.wrap(new byte[0]); | |
private final FeedableBodyGenerator feedableBodyGenerator; | |
private FeedBodyGeneratorOutputStream(FeedableBodyGenerator feedableBodyGenerator) { | |
if ( feedableBodyGenerator == null ) { | |
throw new NullPointerException("The feedableBodyGenerator is required"); | |
} | |
this.feedableBodyGenerator = feedableBodyGenerator; | |
} | |
@Override | |
public void write(int b) throws IOException { | |
throw new RuntimeException("This class is supposed to be wrapped by a BufferedOutputStream"); | |
} | |
@Override | |
public void write(byte b[]) throws IOException { | |
throw new RuntimeException("This class is supposed to be wrapped by a BufferedOutputStream"); | |
} | |
@Override | |
public void write(byte b[], int off, int len) throws IOException { | |
checkParamConsistency(b,off,len); | |
if (len == 0) { | |
return; | |
} | |
byte[] bytesToWrite = new byte[len]; | |
System.arraycopy(b,off,bytesToWrite,0,len); | |
HeapBuffer heapBuffer = HeapBuffer.wrap(bytesToWrite); | |
feedableBodyGenerator.feed(heapBuffer,false); | |
} | |
@Override | |
public void close() throws IOException { | |
feedableBodyGenerator.feed(EMPTY_BUFFER,true); | |
} | |
// Content copied from the OutputStream class | |
private void checkParamConsistency(byte b[], int off, int len) throws IOException { | |
if (b == null) { | |
throw new NullPointerException(); | |
} else if ((off < 0) || (off > b.length) || (len < 0) || | |
((off + len) > b.length) || ((off + len) < 0)) { | |
throw new IndexOutOfBoundsException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment