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:org.apache.activemq.artemis.core.remoting.impl.netty.HttpAcceptorHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    FullHttpRequest request = (FullHttpRequest) msg;
    HttpMethod method = request.getMethod();
    // if we are a post then we send upstream, otherwise we are just being prompted for a response.
    if (method.equals(HttpMethod.POST)) {
        ctx.fireChannelRead(ReferenceCountUtil.retain(((FullHttpRequest) msg).content()));
        // add a new response
        responses.put(new ResponseHolder(System.currentTimeMillis() + responseTime,
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)));
        ReferenceCountUtil.release(msg);
        return;//  w w  w  . jav a 2 s.co  m
    }
    super.channelRead(ctx, msg);
}

From source file:org.apache.activemq.transport.amqp.client.AmqpConnection.java

License:Apache License

@Override
public void onData(final ByteBuf incoming) {

    // We need to retain until the serializer gets around to processing it.
    ReferenceCountUtil.retain(incoming);

    serializer.execute(new Runnable() {

        @Override//from   w w  w  .ja  v  a 2  s.  c  o m
        public void run() {
            ByteBuffer source = incoming.nioBuffer();
            LOG.trace("Client Received from Broker {} bytes:", source.remaining());

            if (protonTransport.isClosed()) {
                LOG.debug("Ignoring incoming data because transport is closed");
                return;
            }

            do {
                ByteBuffer buffer = protonTransport.getInputBuffer();
                int limit = Math.min(buffer.remaining(), source.remaining());
                ByteBuffer duplicate = source.duplicate();
                duplicate.limit(source.position() + limit);
                buffer.put(duplicate);
                protonTransport.processInput();
                source.position(source.position() + limit);
            } while (source.hasRemaining());

            ReferenceCountUtil.release(incoming);

            // Process the state changes from the latest data and then answer back
            // any pending updates to the Broker.
            processUpdates();
            pumpToProtonTransport();
        }
    });
}

From source file:org.apache.qpid.jms.provider.amqp.AmqpProvider.java

License:Apache License

@Override
public void onData(final ByteBuf input) {

    // We need to retain until the serializer gets around to processing it.
    ReferenceCountUtil.retain(input);

    serializer.execute(new Runnable() {

        @Override/*from  w ww  .j  ava  2 s  . com*/
        public void run() {
            try {
                if (isTraceBytes()) {
                    TRACE_BYTES.info("Received: {}", ByteBufUtil.hexDump(input));
                }

                ByteBuffer source = input.nioBuffer();

                do {
                    ByteBuffer buffer = protonTransport.getInputBuffer();
                    int limit = Math.min(buffer.remaining(), source.remaining());
                    ByteBuffer duplicate = source.duplicate();
                    duplicate.limit(source.position() + limit);
                    buffer.put(duplicate);
                    protonTransport.processInput().checkIsOk();
                    source.position(source.position() + limit);
                } while (source.hasRemaining());

                ReferenceCountUtil.release(input);

                // Process the state changes from the latest data and then answer back
                // any pending updates to the Broker.
                processUpdates();
                pumpToProtonTransport();
            } catch (Throwable t) {
                LOG.warn("Caught problem during data processing: {}", t.getMessage(), t);

                fireProviderException(t);
            }
        }
    });
}

From source file:org.bridje.http.impl.HttpWsSwitch.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) {
    if (!added && msg instanceof HttpRequest) {
        String path = ((HttpRequest) msg).getUri();
        WsServerHandler handler = findHandler(path);
        if (handler != null) {
            ctx.pipeline().addAfter("switch", "aggregator", new HttpObjectAggregator(65536));
            ctx.pipeline().addAfter("aggregator", "wsprotocol",
                    new WebSocketServerProtocolHandler(path, null, true));
            ctx.pipeline().addAfter("wsprotocol", "wshandler", new WsFrameHandler(handler));
            added = true;/*from w ww. j av  a  2  s  .com*/
        }
    }
    ReferenceCountUtil.retain(msg);
    out.add(msg);
}

From source file:org.dcache.xrootd.protocol.messages.AsyncResponse.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) {
    try {/*from   www . ja va2  s  .c o m*/
        int dlen = getDataLength();
        ByteBuf header = ctx.alloc().buffer(8 + dlen);
        try {
            header.writeShort(0);
            header.writeShort(kXR_attn);
            header.writeInt(dlen);
            header.writeInt(kXR_asynresp);
            header.writeInt(0);
        } catch (Error | RuntimeException t) {
            promise.setFailure(t);
            header.release();
            return;
        }
        ctx.write(header).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    promise.tryFailure(future.cause());
                }
            }
        });

        ChannelPromise channelPromise = ctx.newPromise();
        channelPromise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    promise.trySuccess();
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        });
        ReferenceCountUtil.retain(response).writeTo(ctx, channelPromise);
    } finally {
        release();
    }
}

From source file:org.graylog2.inputs.syslog.tcp.SyslogTCPFramingRouterHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    if (msg.isReadable()) {
        // "Dynamically manipulating a pipeline is relatively an expensive operation."
        // https://stackoverflow.com/a/28846565
        if (handler == null) {
            if (usesOctetCountFraming(msg)) {
                handler = new SyslogOctetCountFrameDecoder();
            } else {
                handler = new DelimiterBasedFrameDecoder(maxFrameLength, delimiter);
            }/*from ww  w. j a v a2 s.  c  o  m*/
        }

        handler.channelRead(ctx, ReferenceCountUtil.retain(msg));
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:org.graylog2.inputs.transports.netty.DatagramPacketHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    final ByteBuf content = msg.content();
    out.add(ReferenceCountUtil.retain(content));
}

From source file:org.jboss.aerogear.simplepush.server.netty.NotificationHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest request = (FullHttpRequest) msg;
        final String requestUri = request.getUri();
        logger.debug(requestUri);//from   w w w  . j  ava2 s  .com
        if (requestUri.startsWith(simplePushServer.config().endpointPrefix())) {
            handleHttpRequest(ctx, request);
        } else {
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    } else {
        ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
    }
}

From source file:org.lanternpowered.server.network.NetworkSession.java

License:MIT License

/**
 * Sends a array of {@link Message}s and returns the {@link ChannelFuture}.
 *
 * @param messages The messages//from   w  w  w .  j  a  v a 2 s  . c  o m
 * @return The channel future
 */
public ChannelFuture sendWithFuture(Message... messages) {
    checkNotNull(messages, "messages");
    checkArgument(messages.length != 0, "messages cannot be empty");
    final ChannelPromise promise = this.channel.newPromise();
    if (!this.channel.isActive()) {
        return promise;
    }
    promise.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
    // Don't bother checking if we are in the event loop,
    // there is only one message.
    if (messages.length == 1) {
        this.channel.writeAndFlush(messages[0], promise);
    } else {
        final EventLoop eventLoop = this.channel.eventLoop();
        final ChannelPromise voidPromise = this.channel.voidPromise();
        if (eventLoop.inEventLoop()) {
            final int last = messages.length - 1;
            for (int i = 0; i < last; i++) {
                ReferenceCountUtil.retain(messages[i]);
                this.channel.writeAndFlush(messages[i], voidPromise);
            }
            ReferenceCountUtil.retain(messages[last]);
            this.channel.writeAndFlush(messages[last], promise);
        } else {
            // If there are more then one message, combine them inside the
            // event loop to reduce overhead of wakeup calls and object creation

            // Create a copy of the list, to avoid concurrent modifications
            final List<Message> messages0 = ImmutableList.copyOf(messages);
            messages0.forEach(ReferenceCountUtil::retain);
            eventLoop.submit(() -> {
                final Iterator<Message> it0 = messages0.iterator();
                do {
                    final Message message0 = it0.next();
                    // Only use a normal channel promise for the last message
                    this.channel.writeAndFlush(message0, it0.hasNext() ? voidPromise : promise);
                } while (it0.hasNext());
            });
        }
    }
    return promise;
}

From source file:org.lanternpowered.server.network.NetworkSession.java

License:MIT License

/**
 * Sends a iterable of {@link Message}s.
 *
 * @param messages The messages//from  w  w  w .j a v  a 2 s.  c  om
 */
public ChannelFuture sendWithFuture(Iterable<Message> messages) {
    checkNotNull(messages, "messages");
    final Iterator<Message> it = messages.iterator();
    checkArgument(it.hasNext(), "messages cannot be empty");
    final ChannelPromise promise = this.channel.newPromise();
    if (!this.channel.isActive()) {
        return promise;
    }
    promise.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
    Message message = it.next();
    // Don't bother checking if we are in the event loop,
    // there is only one message.
    if (!it.hasNext()) {
        this.channel.writeAndFlush(message, promise);
    } else {
        final EventLoop eventLoop = this.channel.eventLoop();
        final ChannelPromise voidPromise = this.channel.voidPromise();
        if (eventLoop.inEventLoop()) {
            while (true) {
                final boolean next = it.hasNext();
                // Only use a normal channel promise for the last message
                this.channel.writeAndFlush(message, next ? voidPromise : promise);
                if (!next) {
                    break;
                }
                message = it.next();
                ReferenceCountUtil.retain(message);
            }
        } else {
            // If there are more then one message, combine them inside the
            // event loop to reduce overhead of wakeup calls and object creation

            // Create a copy of the list, to avoid concurrent modifications
            final List<Message> messages0 = ImmutableList.copyOf(messages);
            messages0.forEach(ReferenceCountUtil::retain);
            eventLoop.submit(() -> {
                final Iterator<Message> it0 = messages0.iterator();
                do {
                    final Message message0 = it0.next();
                    // Only use a normal channel promise for the last message
                    this.channel.writeAndFlush(message0, it0.hasNext() ? voidPromise : promise);
                } while (it0.hasNext());
            });
        }
    }
    return promise;
}