@Override
    protected void encode(ChannelHandlerContext ctx, FileRegion msg, final ByteBuf out) throws Exception {
        WritableByteChannel writableByteChannel = new WritableByteChannel() {
            @Override
            public int write(ByteBuffer src) {
                int prev = out.writerIndex();
                out.writeBytes(src);
                return out.writerIndex() - prev;
            }

            @Override
            public boolean isOpen() {
                return true;
            }

            @Override
            public void close() throws IOException {
            }
        };

        long toTransfer = msg.count();

        while (true) {
            long transferred = msg.transferred();
            if (toTransfer - transferred <= 0) {
                break;
            }
            msg.transferTo(writableByteChannel, transferred);
        }
    }
@Test
    public void testEncode() throws IOException {
        FileRegionEncoder fileRegionEncoder = new FileRegionEncoder();
        EmbeddedChannel channel = new EmbeddedChannel(fileRegionEncoder);
        File file = File.createTempFile(UUID.randomUUID().toString(), ".data");
        file.deleteOnExit();
        Random random = new Random(System.currentTimeMillis());
        int dataLength = 1 << 10;
        byte[] data = new byte[dataLength];
        random.nextBytes(data);
        write(file, data);
        FileRegion fileRegion = new DefaultFileRegion(file, 0, dataLength);
        Assert.assertEquals(0, fileRegion.transfered());
        Assert.assertEquals(dataLength, fileRegion.count());
        Assert.assertTrue(channel.writeOutbound(fileRegion));
        ByteBuf out = (ByteBuf) channel.readOutbound();
        byte[] arr = new byte[out.readableBytes()];
        out.getBytes(0, arr);
        Assert.assertArrayEquals("Data should be identical", data, arr);
    }