ArchiveResponseEncoder extends MessageToByteEncoder<ArchiveResponsePacket> { @Override protected void encode(ChannelHandlerContext ctx, ArchiveResponsePacket archiveResponse, ByteBuf out) throws Exception { out.writeByte(archiveResponse.getIndex()); out.writeShort(archiveResponse.getArchive()); int pos = out.readableBytes(); ByteBuf file = Unpooled.wrappedBuffer(archiveResponse.getData()); int chunkSize = Math.min(file.readableBytes(), CHUNK_SIZE - 3); writeChunk(file.readBytes(chunkSize), out); while (file.isReadable()) { out.writeByte(0xff); chunkSize = Math.min(file.readableBytes(), CHUNK_SIZE - 1); writeChunk(file.readBytes(chunkSize), out); } int size = out.readableBytes() - pos; logger.debug("Wrote index {} archive {} (size {}) in {} bytes", archiveResponse.getIndex(), archiveResponse.getArchive(), archiveResponse.getData().length, size); }    }
@Test public void testEncode() throws Exception { byte[] data = new byte[1000]; Random random = new Random(42L); random.nextBytes(data); Container container = new Container(CompressionType.NONE, -1); container.compress(data, null); byte[] compressedData = container.data; ArchiveResponsePacket archiveResponse = new ArchiveResponsePacket(); archiveResponse.setIndex(0); archiveResponse.setArchive(1); archiveResponse.setData(compressedData); ByteBuf buf = Unpooled.buffer(1024); ArchiveResponseEncoder encoder = new ArchiveResponseEncoder(); encoder.encode(null, archiveResponse, buf); ArchiveResponseDecoder decoder = new ArchiveResponseDecoder(); List<Object> out = new ArrayList<>(); decoder.decode(null, buf, out); Assert.assertEquals(1, out.size()); ArchiveResponsePacket response = (ArchiveResponsePacket) out.get(0); Assert.assertEquals(archiveResponse.getIndex(), response.getIndex()); Assert.assertEquals(archiveResponse.getArchive(), response.getArchive()); Assert.assertArrayEquals(archiveResponse.getData(), response.getData()); byte[] decompressedData = Container.decompress(response.getData(), null).data; Assert.assertArrayEquals(data, decompressedData); }