Example usage for io.netty.util ReferenceCountUtil release

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

Introduction

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

Prototype

public static boolean release(Object msg) 

Source Link

Document

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

Usage

From source file:blazingcache.network.netty.DataMessageDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;/*from   w ww.j av  a  2  s.  co m*/
    try {
        ctx.fireChannelRead(DodoMessageUtils.decodeMessage(in));
    } finally {
        ReferenceCountUtil.release(msg);
    }

}

From source file:cc.agentx.client.net.nio.XRelayHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {/*from ww  w  .j a  va2  s  .c  om*/
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                } else {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                    }
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

From source file:cc.agentx.server.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {/*w w  w  .  j  ava  2  s. com*/
        ByteBuf byteBuf = (ByteBuf) msg;
        if (!byteBuf.hasArray()) {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0, bytes);

            if (!requestParsed) {
                if (!exposedRequest) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes == null) {
                        log.info("\tClient -> Proxy           \tHalf Request");
                        return;
                    }
                }
                XRequest xRequest = requestWrapper.parse(bytes);
                String host = xRequest.getHost();
                int port = xRequest.getPort();
                int dataLength = xRequest.getSubsequentDataLength();
                if (dataLength > 0) {
                    byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length);
                    if (exposedRequest) {
                        tailData = wrapper.unwrap(tailData);
                        if (tailData != null) {
                            tailDataBuffer.write(tailData, 0, tailData.length);
                        }
                    } else {
                        tailDataBuffer.write(tailData, 0, tailData.length);
                    }
                }
                log.info("\tClient -> Proxy           \tTarget {}:{}{}", host, port,
                        DnsCache.isCached(host) ? " [Cached]" : "");
                if (xRequest.getAtyp() == XRequest.Type.DOMAIN) {
                    try {
                        host = DnsCache.get(host);
                        if (host == null) {
                            host = xRequest.getHost();
                        }
                    } catch (UnknownHostException e) {
                        log.warn("\tClient <- Proxy           \tBad DNS! ({})", e.getMessage());
                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        return;
                    }
                }

                Promise<Channel> promise = ctx.executor().newPromise();
                promise.addListener(new FutureListener<Channel>() {
                    @Override
                    public void operationComplete(final Future<Channel> future) throws Exception {
                        final Channel outboundChannel = future.getNow();
                        if (future.isSuccess()) {
                            // handle tail
                            byte[] tailData = tailDataBuffer.toByteArray();
                            tailDataBuffer.close();
                            if (tailData.length > 0) {
                                log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length);
                            }
                            outboundChannel
                                    .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData)
                                            : Unpooled.EMPTY_BUFFER)
                                    .addListener(channelFuture -> {
                                        // task handover
                                        outboundChannel.pipeline()
                                                .addLast(new XRelayHandler(ctx.channel(), wrapper, false));
                                        ctx.pipeline()
                                                .addLast(new XRelayHandler(outboundChannel, wrapper, true));
                                        ctx.pipeline().remove(XConnectHandler.this);
                                    });

                        } else {
                            if (ctx.channel().isActive()) {
                                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

                final String finalHost = host;
                bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (!future.isSuccess()) {
                                    if (ctx.channel().isActive()) {
                                        log.warn("\tClient <- Proxy           \tBad Ping! ({}:{})", finalHost,
                                                port);
                                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                                .addListener(ChannelFutureListener.CLOSE);
                                    }
                                }
                            }
                        });

                requestParsed = true;
            } else {
                bytes = wrapper.unwrap(bytes);
                if (bytes != null)
                    tailDataBuffer.write(bytes, 0, bytes.length);
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:cc.agentx.server.net.nio.XRelayHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {// w  w w .  ja  v a  2  s  .co m
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                    }
                } else {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

From source file:cn.david.socks.RelayHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (relayChannel.isActive()) {
        relayChannel.writeAndFlush(msg);
    } else {/*  w ww . j  a va2 s  .co m*/
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.aerofs.baseline.http.FinalInboundHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ReferenceCountUtil.release(msg);
    Channels.close(ctx, "unhandled message");
}

From source file:com.alltobid.quotabid.BidServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ReferenceCountUtil.release(msg);
}

From source file:com.bloom.zerofs.rest.HealthCheckHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    boolean forwardObj = false;
    if (obj instanceof HttpRequest) {
        if (request == null && ((HttpRequest) obj).getUri().equals(healthCheckUri)) {
            nettyMetrics.healthCheckRequestRate.mark();
            startTimeInMs = System.currentTimeMillis();
            logger.trace("Handling health check request while in state " + restServerState.isServiceUp());
            request = (HttpRequest) obj;
            if (restServerState.isServiceUp()) {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                        Unpooled.wrappedBuffer(GOOD));
                HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request));
                HttpHeaders.setContentLength(response, GOOD.length);
            } else {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.SERVICE_UNAVAILABLE, Unpooled.wrappedBuffer(BAD));
                HttpHeaders.setKeepAlive(response, false);
                HttpHeaders.setContentLength(response, BAD.length);
            }/*from w  ww.  jav a  2  s  .co  m*/
            nettyMetrics.healthCheckRequestProcessingTimeInMs
                    .update(System.currentTimeMillis() - startTimeInMs);
        } else {
            // Rest server could be down even if not for health check request. We intentionally don't take any action in this
            // handler for such cases and leave it to the downstream handlers to handle it
            forwardObj = true;
        }
    }
    if (obj instanceof LastHttpContent) {
        if (response != null) {
            // response was created when we received the request with health check uri
            ChannelFuture future = ctx.writeAndFlush(response);
            if (!HttpHeaders.isKeepAlive(response)) {
                future.addListener(ChannelFutureListener.CLOSE);
            }
            request = null;
            response = null;
            nettyMetrics.healthCheckRequestRoundTripTimeInMs.update(System.currentTimeMillis() - startTimeInMs);
        } else {
            // request was not for health check uri
            forwardObj = true;
        }
    } else if (request == null) {
        // http Content which is not LastHttpContent is not intended for this handler
        forwardObj = true;
    }
    if (forwardObj) {
        super.channelRead(ctx, obj);
    } else {
        ReferenceCountUtil.release(obj);
    }
}

From source file:com.bloom.zerofs.rest.NettyMultipartRequest.java

License:Open Source License

@Override
public void close() {
    super.close();
    logger.trace("Closing NettyMultipartRequest with {} raw content chunks unread", rawRequestContents.size());
    HttpContent content = rawRequestContents.poll();
    while (content != null) {
        ReferenceCountUtil.release(content);
        content = rawRequestContents.poll();
    }//from w  ww.  j av  a 2s  .co  m
}

From source file:com.bloom.zerofs.rest.NettyMultipartRequest.java

License:Open Source License

/**
 * {@inheritDoc}/*from w w w .  ja va2  s. c o m*/
 * @param asyncWritableChannel the {@link AsyncWritableChannel} to read the data into.
 * @param callback the {@link Callback} that will be invoked either when all the data in the channel has been emptied
 *                 into the {@code asyncWritableChannel} or if there is an exception in doing so. This can be null.
 * @return the {@link Future} that will eventually contain the result of the operation.
 * @throws IllegalStateException if an attempt is made to read the channel before calling {@link #prepare()} or if
 *                                this function is called more than once.
 */
@Override
public Future<Long> readInto(AsyncWritableChannel asyncWritableChannel, Callback<Long> callback) {
    if (callbackWrapper != null) {
        throw new IllegalStateException("ReadableStreamChannel cannot be read more than once");
    } else if (!readyForRead) {
        throw new IllegalStateException("The channel cannot be read yet");
    }
    callbackWrapper = new ReadIntoCallbackWrapper(callback);
    if (!isOpen()) {
        nettyMetrics.multipartRequestAlreadyClosedError.inc();
        callbackWrapper.invokeCallback(new ClosedChannelException());
    }
    HttpContent content = requestContents.poll();
    while (content != null) {
        try {
            writeContent(asyncWritableChannel, callbackWrapper, content);
        } finally {
            ReferenceCountUtil.release(content);
        }
        content = requestContents.poll();
    }
    return callbackWrapper.futureResult;
}