ArrayOfByteArraysOutput extends AbstractRockerOutput<ArrayOfByteArraysOutput> { public ReadableByteChannel asReadableByteChannel() { return new ReadableByteChannel() { private boolean closed = false; private int offset = 0; private final int length = getByteLength(); private int chunkIndex = 0; private int chunkOffset = 0; @Override public int read(ByteBuffer dst) throws IOException { if (closed) { throw new ClosedChannelException(); } if (arrays.isEmpty() || offset >= length) { return -1; } int readBytes = 0; while (dst.hasRemaining() && (offset < length)) { byte[] chunk = arrays.get(chunkIndex); int chunkLength = chunk.length - chunkOffset; int capacity = dst.remaining(); if (capacity < chunkLength) { chunkLength = capacity; } dst.put(chunk, chunkOffset, chunkLength); offset += chunkLength; chunkOffset += chunkLength; if (chunkOffset >= chunk.length) { chunkIndex++; chunkOffset = 0; } readBytes += chunkLength; } return readBytes; } @Override public boolean isOpen() { return !closed; } @Override public void close() throws IOException { closed = true; } }; } ArrayOfByteArraysOutput(ContentType contentType, String charsetName);  ArrayOfByteArraysOutput(ContentType contentType, Charset charset); List<byte[]> getArrays(); @Override ArrayOfByteArraysOutput w(String string); @Override ArrayOfByteArraysOutput w(byte[] bytes); byte[] toByteArray(); @Override String toString(); ReadableByteChannel asReadableByteChannel(); InputStream asInputStream(); static RockerOutputFactory<ArrayOfByteArraysOutput> FACTORY; }
@Test public void asReadableByteChannel() throws Exception { ArrayOfByteArraysOutput out = new ArrayOfByteArraysOutput(ContentType.HTML, "UTF-8"); out.w("T"); out.w("E"); ReadableByteChannel rbc; ByteBuffer buf; int bytesRead; rbc = out.asReadableByteChannel(); Assert.assertTrue(rbc.isOpen()); buf = ByteBuffer.allocate(5); bytesRead = rbc.read(buf); Assert.assertEquals(2, bytesRead); Assert.assertEquals((byte)'T', buf.get(0)); Assert.assertEquals((byte)'E', buf.get(1)); Assert.assertEquals(-1, rbc.read(buf)); rbc = out.asReadableByteChannel(); buf = ByteBuffer.allocate(1); bytesRead = rbc.read(buf); Assert.assertEquals(1, bytesRead); Assert.assertEquals((byte)'T', buf.get(0)); buf.flip(); bytesRead = rbc.read(buf); Assert.assertEquals(1, bytesRead); Assert.assertEquals((byte)'E', buf.get(0)); Assert.assertEquals(-1, rbc.read(buf)); rbc = out.asReadableByteChannel(); buf = ByteBuffer.allocate(2); bytesRead = rbc.read(buf); Assert.assertEquals(2, bytesRead); Assert.assertEquals((byte)'T', buf.get(0)); Assert.assertEquals((byte)'E', buf.get(1)); Assert.assertEquals(-1, rbc.read(buf)); }