Skip to content

Instantly share code, notes, and snippets.

@slorber
Created August 27, 2013 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slorber/6354490 to your computer and use it in GitHub Desktop.
Save slorber/6354490 to your computer and use it in GitHub Desktop.
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