Example usage for io.netty.util ReferenceCountUtil retain

List of usage examples for io.netty.util ReferenceCountUtil retain

Introduction

In this page you can find the example usage for io.netty.util ReferenceCountUtil retain.

Prototype

@SuppressWarnings("unchecked")
public static <T> T retain(T msg) 

Source Link

Document

Try to call ReferenceCounted#retain() if the specified message implements ReferenceCounted .

Usage

From source file:reactor.ipc.netty.http.server.HttpServerWSOperations.java

License:Open Source License

void sendClose(CloseWebSocketFrame frame, ChannelFutureListener listener) {
    if (frame != null && !frame.isFinalFragment()) {
        channel().writeAndFlush(frame);/*from   w  w  w .j  a v a  2s .co  m*/
        return;
    }
    if (CLOSE_SENT.getAndSet(this, 1) == 0) {
        ChannelFuture f = channel().writeAndFlush(frame == null ? new CloseWebSocketFrame() : frame);
        if (listener != null) {
            f.addListener(listener);
        }
        return;
    }
    ReferenceCountUtil.retain(frame);
}

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/*from w  ww. ja  va 2 s .c  o  m*/
        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");
}

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

License:Open Source License

@Test
public void sendFileWithTlsUsesChunkedFile()
        throws URISyntaxException, NoSuchAlgorithmException, SSLException, CertificateException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    final SslHandler sslHandler = sslCtx.newHandler(ByteBufAllocator.DEFAULT);

    List<Class<?>> messageWritten = new ArrayList<>(2);
    List<Object> clearMessages = new ArrayList<>(2);

    EmbeddedChannel channel = new EmbeddedChannel(
            //outbound: pipeline reads inverted
            //bytes are encrypted
            sslHandler,//from w  w w . j a  v  a  2 s.c o m
            //capture the chunks unencrypted, transform as Strings:
            new MessageToMessageEncoder<ByteBuf>() {
                @Override
                protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
                        throws Exception {
                    clearMessages.add(msg.toString(CharsetUtil.UTF_8));
                    out.add(msg.retain()); //the encoder will release the buffer, make sure it is retained for SslHandler
                }
            },
            //transform the ChunkedFile into ByteBuf chunks:
            new ChunkedWriteHandler(),
            //helps to ensure a ChunkedFile was written outs
            new MessageToMessageEncoder<Object>() {
                @Override
                protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out)
                        throws Exception {
                    messageWritten.add(msg.getClass());
                    //passing the ChunkedFile through this method releases it, which is undesired
                    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);

    try {
        outbound.sendFile(Paths.get(getClass().getResource("/largeFile.txt").toURI())).then()
                .block(Duration.ofSeconds(1)); //TODO investigate why this hangs
    } catch (IllegalStateException e) {
        if (!"Timeout on blocking read for 1000 MILLISECONDS".equals(e.getMessage()))
            throw e;
        System.err.println(e);
    }

    assertThat(messageWritten).containsExactly(Integer.class, ChunkedFile.class);

    assertThat(clearMessages).hasSize(2).element(0).asString().startsWith(
            "This is an UTF-8 file that is larger than 1024 bytes.\nIt contains accents like .\nGARBAGE")
            .endsWith("1024 mark here ->");
    assertThat(clearMessages).element(1).asString().startsWith("<- 1024 mark here").endsWith("End of File");
}

From source file:rxweb.engine.server.netty.UnicastContentSubject.java

License:Apache License

@Override
public void onNext(T t) {
    // Retain so that post-buffer, the ByteBuf does not get released.
    // Release will be done after reading from the subject.
    ReferenceCountUtil.retain(t);
    state.bufferedObserver.onNext(t);//from  w w  w.  j  ava2s.  c  o  m

    // Schedule timeout once and when not subscribed yet.
    if (state.casTimeoutScheduled() && state.state == State.STATES.UNSUBSCRIBED.ordinal()) {
        timeoutScheduler.subscribe(new Action1<Long>() { // Schedule timeout after the first content arrives.
            @Override
            public void call(Long aLong) {
                disposeIfNotSubscribed();
            }
        });
    }
}

From source file:sailfish.remoting.handler.NegotiateChannelHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Protocol msg) throws Exception {
    if (!ChannelUtil.clientSide(ctx) && msg.request() && msg.heartbeat()) {
        dealNegotiate(ctx, msg);/*from  w  w  w.  j av a 2s .c om*/
        return;
    }
    // no sense to Protocol in fact
    ReferenceCountUtil.retain(msg);
    ctx.fireChannelRead(msg);
}