Example usage for io.netty.channel FileRegion position

List of usage examples for io.netty.channel FileRegion position

Introduction

In this page you can find the example usage for io.netty.channel FileRegion position.

Prototype

long position();

Source Link

Document

Returns the offset in the file where the transfer began.

Usage

From source file:reactor.ipc.netty.NettyOutboundTest.java

License:Open Source License

@Test
public void sendFileWithoutTlsUsesFileRegion() throws URISyntaxException, IOException {
    List<Class<?>> messageClasses = new ArrayList<>(2);

    EmbeddedChannel channel = new EmbeddedChannel(new MessageToMessageEncoder<FileRegion>() {

        @Override/* w w w. ja v  a  2  s  .c om*/
        protected void encode(ChannelHandlerContext ctx, FileRegion msg, List<Object> out) throws Exception {
            ByteArrayOutputStream bais = new ByteArrayOutputStream();
            WritableByteChannel wbc = Channels.newChannel(bais);

            msg.transferTo(wbc, msg.position());
            out.add(new String(bais.toByteArray()));
        }
    }, new MessageToMessageEncoder<Object>() {
        @Override
        protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
            messageClasses.add(msg.getClass());
            ReferenceCountUtil.retain(msg);
            out.add(msg);
        }
    });
    NettyContext mockContext = () -> channel;
    NettyOutbound outbound = new NettyOutbound() {
        @Override
        public NettyContext context() {
            return mockContext;
        }

        @Override
        public FileChunkedStrategy getFileChunkedStrategy() {
            return FILE_CHUNKED_STRATEGY_1024_NOPIPELINE;
        }
    };
    channel.writeOneOutbound(1);

    outbound.sendFile(Paths.get(getClass().getResource("/largeFile.txt").toURI())).then().block();

    assertThat(channel.inboundMessages()).isEmpty();
    assertThat(channel.outboundMessages()).hasSize(2);
    assertThat(messageClasses).containsExactly(Integer.class, DefaultFileRegion.class);

    assertThat(channel.outboundMessages()).element(1).asString().startsWith(
            "This is an UTF-8 file that is larger than 1024 bytes.\nIt contains accents like .\nGARBAGE")
            .endsWith("GARBAGE\nEnd of File");
}