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:com.tesora.dve.db.mysql.RedistTargetSite.java

License:Open Source License

@Override
public void close() {
    try {//from   ww  w  . ja v  a 2  s .c  o  m
        this.closeActivePreparedStatement();
    } finally {
        ReferenceCountUtil.release(this.bufferedExecute);
        this.bufferedExecute = null;
        this.queuedRowSetCount.set(0);
    }
}

From source file:com.tesora.dve.server.connectionmanager.loaddata.MSPLoadDataDecoder.java

License:Open Source License

@Override
protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
    //TODO: Avoid discarding/mangling a query on remove in the (unlikely) case where the client pipelined a request. -sgossard
    closePreparedStatements(myLoadDataInfileContext);

    //now we are sure we won't be getting any more packets, so turn autoread back on.
    resumeInput(ctx);//w  w w.  jav  a 2s .c  om

    //just to be safe, we'll release any bytebufs we are still holding.
    while (!decodedFrameQueue.isEmpty()) {
        ReferenceCountUtil.release(decodedFrameQueue.remove());
    }
}

From source file:com.tesora.dve.server.connectionmanager.loaddata.MSPLoadDataDecoder.java

License:Open Source License

private void processQueuedOutput(ChannelHandlerContext ctx) throws Exception {
    byte packetNumber = 0;
    for (;;) {/*from  ww w  .j av  a2 s  . c om*/
        ByteBuf nextDecodedFrame = decodedFrameQueue.poll();

        if (nextDecodedFrame == null)
            break;

        try {
            if (encounteredError == null) {

                packetNumber = nextDecodedFrame.readByte();
                byte[] frameData = MysqlAPIUtils.readBytes(nextDecodedFrame);

                final List<List<byte[]>> parsedRows = LoadDataBlockExecutor.processDataBlock(ctx, ssCon,
                        frameData);

                insertRequest(ctx, parsedRows);

                waitingForInsert = true;

                if (waitingForInsert)
                    break; //OK, we sent out an insert. We'll wait for it to come back before sending another.
            }
        } catch (Throwable t) {
            failLoadData(t);
        } finally {
            ReferenceCountUtil.release(nextDecodedFrame);
        }
    }

    if (waitingForInsert) {
        pauseInput(ctx);
        return;
    }

    boolean loadDataIsFinished = decodedEOF || (encounteredError != null);

    if (loadDataIsFinished) {
        sendResponseAndRemove(ctx);
    } else {
        //not waiting for input, haven't seen input EOF or thrown an exception, must need more input data.
        resumeInput(ctx);
    }

}

From source file:com.twocater.diamond.core.netty.http.HttpDecoder.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    LoggerConstant.nettyHandlerLog.debug("{}", new Object[] { ctx.channel() });

    FullHttpRequest request = (FullHttpRequest) msg;

    try {//  www  .java2 s.com
        if (request.getDecoderResult().isFailure()) {
            debug.debug("decoderfail:{}", request);
            ctx.close();
            return;
        }

        //        LoggingHandler

        HttpHeaders headers = request.headers();
        //        StringBuilder buf = new StringBuilder();
        //        if (!headers.isEmpty()) {
        //            for (Map.Entry<String, String> h : headers) {
        //                String key = h.getKey();
        //                String value = h.getValue();
        //                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
        //            }
        //            buf.append("\r\n");
        //        }
        //        System.out.println(buf.toString());

        // ?
        Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
        for (String name : headers.names()) {
            headersMap.put(name, headers.getAll(name));
        }

        // ??
        byte[] data = null;
        int n = request.content().readableBytes();
        if (n > 0) {
            data = new byte[n];
            request.content().readBytes(data);
        }

        HttpRequestMessage httpRequestMessage = new HttpRequestMessage(request.getMethod(),
                request.getProtocolVersion(), request.getUri(), headersMap, data);

        ctx.fireChannelRead(httpRequestMessage);

    } finally {
        // ???netty??
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.vela.iot.active.netty.http2.server.LastInboundHandler.java

License:Apache License

public void finishAndReleaseAll() throws Exception {
    checkException();/* w  w  w.  j a va  2 s. c  om*/
    Object o;
    while ((o = readInboundMessageOrUserEvent()) != null) {
        ReferenceCountUtil.release(o);
    }
}

From source file:com.xx_dev.apn.proxy.ApnProxyRelayHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    LoggerUtil.debug(logger, ctx.channel().attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), tag, msg);

    if (relayChannel.isActive()) {
        relayChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override//w  w  w.  j  ava  2 s .co m
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!ctx.channel().config().getOption(ChannelOption.AUTO_READ)) {
                    ctx.read();
                }
            }
        });
    } else {
        ReferenceCountUtil.release(msg);
    }

}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get()
            .getRemote();//from   ww  w  .j  av a 2  s.c  o m

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Use old remote channel");
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Create new remote channel");

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new ApnProxyRemoteForwardChannelInitializer(uaChannel, this));

            // set local address
            if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
                bootstrap.localAddress(new InetSocketAddress(
                        (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
            }

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getRemoteHost(),
                    apnProxyRemote.getRemotePort());

            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        LoggerUtil.error(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                                "Remote channel create fail");

                        // send error response
                        String errorMsg = "remote connect to "
                                + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote()
                                        .getRemoteAddr()
                                + " fail";
                        HttpMessage errorResponseMsg = HttpErrorUtil
                                .buildHttpErrorMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorMsg);
                        uaChannel.writeAndFlush(errorResponseMsg);
                        httpContentBuffer.clear();

                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        HttpContent hc = ((HttpContent) msg);
        //hc.retain();

        //HttpContent _hc = hc.copy();

        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        final HttpRequest httpRequest = (HttpRequest) msg;

        //Channel uaChannel = uaChannelCtx.channel();

        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.AUTO_READ, false)
                .handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel()));

        final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel()
                .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

        // set local address
        if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
            bootstrap.localAddress(new InetSocketAddress(
                    (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
        }/*  ww  w. j  a  v a2 s  . co m*/

        bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort())
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            if (apnProxyRemote.isAppleyRemoteRule()) {
                                uaChannelCtx.pipeline().remove("codec");
                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);

                                // add relay handler
                                uaChannelCtx.pipeline()
                                        .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel()));

                                future1.channel()
                                        .writeAndFlush(Unpooled.copiedBuffer(
                                                constructConnectRequestForProxy(httpRequest, apnProxyRemote),
                                                CharsetUtil.UTF_8))
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future2)
                                                    throws Exception {
                                                if (!future2.channel().config()
                                                        .getOption(ChannelOption.AUTO_READ)) {
                                                    future2.channel().read();
                                                }
                                            }
                                        });

                            } else {
                                HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1,
                                        new HttpResponseStatus(200, "Connection established"));
                                uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future2)
                                                    throws Exception {
                                                // remove handlers
                                                uaChannelCtx.pipeline().remove("codec");
                                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                                uaChannelCtx.pipeline()
                                                        .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);

                                                // add relay handler
                                                uaChannelCtx.pipeline()
                                                        .addLast(new ApnProxyRelayHandler(
                                                                "UA --> " + apnProxyRemote.getRemoteAddr(),
                                                                future1.channel()));
                                            }

                                        });
                            }

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

    }
    ReferenceCountUtil.release(msg);
}

From source file:com.xx_dev.apn.proxy.expriment.HttpServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof LastHttpContent) {

        DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        httpResponse.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

        ctx.write(httpResponse);//from  w ww .  j  av a2 s  . co  m

        String s = "1234567890";

        for (int i = 0; i < 100000; i++) {
            DefaultHttpContent c1 = new DefaultHttpContent(Unpooled.copiedBuffer(s, CharsetUtil.UTF_8));

            ctx.writeAndFlush(c1);
        }

        DefaultLastHttpContent c3 = new DefaultLastHttpContent();

        ctx.writeAndFlush(c3);
    }

    ReferenceCountUtil.release(msg);
}

From source file:com.yahoo.pulsar.broker.admin.BrokerStats.java

License:Apache License

@GET
@Path("/destinations")
@ApiOperation(value = "Get all the destination stats by namesapce", response = OutputStream.class, responseContainer = "OutputStream") // https://github.com/swagger-api/swagger-ui/issues/558
                                                                                                                                       // map
                                                                                                                                       // support
                                                                                                                                       // missing
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission") })
public StreamingOutput getDestinations2() throws Exception {
    // Ensure super user access only
    validateSuperUserAccess();//  w ww  .j  a  v  a 2  s. c o m
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            ByteBuf statsBuf = null;
            try {
                statsBuf = pulsar().getBrokerService().getDimensionMetrics();
                output.write(statsBuf.array(), statsBuf.arrayOffset(), statsBuf.readableBytes());
            } catch (Exception e) {
                throw new WebApplicationException(e);
            } finally {
                ReferenceCountUtil.release(statsBuf);
            }
        }
    };
}