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:reactor.ipc.netty.channel.NettyOperations.java

License:Open Source License

/**
 * React on inbound {@link Channel#read}
 *
 * @param msg the read payload//from   w ww  . j  av a 2 s  . co  m
 */
protected void onInboundNext(Object msg) {
    if (msg == null) {
        onChannelError(new NullPointerException("msg is null"));
        return;
    }
    if (inboundDone) {
        Operators.onNextDropped(msg);
        return;
    }
    ReferenceCountUtil.retain(msg);
    if (receiverCaughtUp && receiver != null) {
        try {
            receiver.onNext(msg);
        } finally {
            ReferenceCountUtil.release(msg);
            channel.read();
        }

    } else {
        Queue<Object> q = inboundQueue;
        if (q == null) {
            q = QueueSupplier.unbounded().get();
            inboundQueue = q;
        }
        q.offer(msg);
        if (drainReceiver()) {
            receiverCaughtUp = true;
        }
    }
}

From source file:reactor.ipc.netty.channel.NettyOperations.java

License:Open Source License

final boolean drainReceiver() {
    if (wip++ != 0) {
        return false;
    }//w w  w .  ja va  2 s  . co m

    int missed = 1;

    for (;;) {
        final Queue<Object> q = inboundQueue;
        final Subscriber<? super Object> a = receiver;

        if (a == null) {
            return false;
        }

        long r = inboundRequested;
        long e = 0L;

        while (e != r) {
            if (isCancelled()) {
                return false;
            }

            boolean d = inboundDone;
            Object v = q != null ? q.poll() : null;
            boolean empty = v == null;

            if (d && empty) {
                cancelReceiver();
                if (q != null) {
                    q.clear();
                }
                Throwable ex = error;
                if (ex != null) {
                    a.onError(ex);
                } else {
                    a.onComplete();
                }
                return false;
            }

            if (empty) {
                channel.read();
                break;
            }

            try {
                a.onNext(v);
            } finally {
                ReferenceCountUtil.release(v);
                channel.read();
            }

            e++;
        }

        if (e == r) {
            if (isCancelled()) {
                return false;
            }

            if (inboundDone && (q == null || q.isEmpty())) {
                cancelReceiver();
                if (q != null) {
                    q.clear();
                }
                Throwable ex = error;
                if (ex != null) {
                    a.onError(ex);
                } else {
                    a.onComplete();
                }
                return false;
            }
        }

        if (e != 0L) {
            if (r != Long.MAX_VALUE) {
                if ((inboundRequested -= e) > 0L) {
                    channel.read();
                }
            }
        }

        missed = (wip = wip - missed);
        if (missed == 0) {
            if (r == Long.MAX_VALUE) {
                channel.config().setAutoRead(true);
                channel.read();
                return true;
            }
            return false;
        }
    }
}

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

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // read message and track if it was keepAlive
    if (msg instanceof HttpRequest) {
        final HttpRequest request = (HttpRequest) msg;
        if (persistentConnection) {
            pendingResponses += 1;/*from  w ww .j  a  v  a2 s  .  c  om*/
            persistentConnection = isKeepAlive(request);
        } else {
            if (HttpServerOperations.log.isDebugEnabled()) {
                HttpServerOperations.log.debug(
                        "dropping pipelined HTTP request, " + "previous response requested connection close");
            }
            ReferenceCountUtil.release(msg);
            return;
        }
        if (overflow || pendingResponses > 1) {
            if (HttpServerOperations.log.isDebugEnabled()) {
                HttpServerOperations.log.debug(
                        "buffering pipelined HTTP request, " + "pending response count: {}, queue: {}",
                        pendingResponses, pipelined != null ? pipelined.size() : 0);
            }
            overflow = true;
            doPipeline(ctx, msg);
            return;
        } else {
            overflow = false;
            parentContext.createOperations(ctx.channel(), msg);

            if (!(msg instanceof FullHttpRequest)) {
                return;
            }
        }
    } else if (overflow) {
        if (HttpServerOperations.log.isDebugEnabled()) {
            HttpServerOperations.log.debug(
                    "buffering pipelined HTTP content, " + "pending response count: {}, pending pipeline:{}",
                    pendingResponses, pipelined != null ? pipelined.size() : 0);
        }
        doPipeline(ctx, msg);
        return;
    }
    ctx.fireChannelRead(msg);
}

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

License:Open Source License

final void discard() {
    if (pipelined != null && !pipelined.isEmpty()) {
        Object o;//from   www .jav  a 2s  .co m
        while ((o = pipelined.poll()) != null) {
            ReferenceCountUtil.release(o);
        }

    }
}

From source file:server.direct.RawRequestHandler.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    //ByteBufBinaryWebSocketFrameserverChannel
    if (serverChannel.isActive()) {
        ByteBuf fullByteBuf = Unpooled.wrappedBuffer(byteBufList.toArray(new ByteBuf[0]));

        //Console.debug("GogoSocksRawRequestHandler - send request, len: " + fullByteBuf.readableBytes() );
        //System.out.println(this.hashCode() + ": >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>request from browser");
        //System.out.println(fullByteBuf.duplicate().toString(CharsetUtil.UTF_8));
        //System.out.println("-----------------------------------------");

        //serverChannel.writeAndFlush?byteBufListByteBufrefCount-1??0
        serverChannel.writeAndFlush(fullByteBuf);
        byteBufList.clear();/*ww  w .  ja  v  a  2 s  .c  o  m*/
    } else {
        Console.info("GoGo", "RawRequestHandler's websocket channel is not active.");
        for (ByteBuf b : byteBufList) {
            ReferenceCountUtil.release(b);
        }
        byteBufList.clear();

        //websocket channel is not active, so close the browser connection
        ChannelUtil.closeOnFlush(ctx.channel());
    }
}

From source file:server.direct.RawResponseHandler.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    //???/*ww w .ja  va2s .co  m*/
    if (clientChannel.isActive()) {
        ByteBuf fullByteBuf = Unpooled.wrappedBuffer(byteBufList.toArray(new ByteBuf[0]));

        //????
        /*String reqPath = ctx.channel().attr(HttpServer.REQ_PATH_KEY).get();
        Console.info("RawResponseHandler", "<<<<<< response from remote <<<<<<");
        Console.info("RawResponseHandler", fullByteBuf.duplicate().toString(CharsetUtil.UTF_8));
        Console.info("RawResponseHandler", "-----------------------------------------");*/

        clientChannel.writeAndFlush(fullByteBuf);
        byteBufList.clear();
    } else {
        //Log.info("RawResponseHandler - <<<<<< clientChannel not active after response from remote <<<<<<");
        for (ByteBuf b : byteBufList) {
            ReferenceCountUtil.release(b);
        }
        byteBufList.clear();

        //clientChannel not active, so close the websocket connection
        ChannelUtil.closeOnFlush(ctx.channel());
    }
}

From source file:taichu.kafka.test.netty4.example.discardServer.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    // ???messageReceivedChannelRead??
    // SimpleChannelInboundHandler??????messageReceived
    ///*from   w ww .j av a 2s  .  c  o  m*/
    //
    //
    // ?SimpleChannelInboundHandler??public
    // classYouTCPServerHandler extends
    // SimpleChannelInboundHandler<ByteBuf>{...}
    //
    // ???ByteBuf?messageReceived???nettysample??serverclientBigInteger
    //
    // SimpleChannelInboundHandler<BigInteger>???ByteBuf

    ByteBuf in = (ByteBuf) msg;
    try {
        while (in.isReadable()) { // (1)
            System.out.println((char) in.readByte());
            //TODO:?print???
            //?telnet???servernetty?
            //telnet?client???4GBK21
            //server?4
            //???????bytes?byte[]??utf-8gbkconsole
            //
            //            byte[] bytes= in.readByte();
            //            System.out.print(new String((byte[])in.readByte(),"utf-8"));
            //            String s  =new String(s.getBytes("gbk"),"utf-8");
            System.out.flush();
            // TODO:?jmetertelnet?read????END
        }
    } finally {
        ReferenceCountUtil.release(msg); // (2)
    }
}

From source file:tk.jomp16.irc.netty.NettyHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (idle) {//from   w w w. j  a va  2 s  .c  om
        idle = false;
    }

    ircManager.getIrcParser().parse(ircManager, (String) msg);
    ReferenceCountUtil.release(msg);
}

From source file:tonivade.redis.RedisConnectionHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {// w  w w.  j a  v a 2 s.  c o  m
        impl.receive(ctx, (RedisToken) msg);
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:uapi.web.http.netty.internal.HttpRequestDispatcher.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        if (this._request == null) {
            this._request = new NettyHttpRequest(this._logger, (HttpRequest) msg);
        }//from  www.j  a va 2s  .  com
        if (this._response == null) {
            this._response = new NettyHttpResponse(ctx, this._request);
        }
    }

    // Find out mapped handler
    if (this._handler == null) {
        List<IHttpHandler> handlers = Looper.from(this._handlers)
                .filter(handler -> this._request.uri().startsWith(handler.getUriMapping())).toList();
        if (handlers.size() == 0) {
            throw new NotFoundException("No handler is mapped to uri - {}", this._request.uri());
        }
        this._handler = handlers.get(0);
        if (handlers.size() > 1) {
            for (int i = 1; i < handlers.size(); i++) {
                if (handlers.get(i).getUriMapping().length() > this._handler.getUriMapping().length()) {
                    this._handler = handlers.get(i);
                    break;
                }
            }
        }
    }
    if (this._handler == null) {
        throw new NotFoundException("No handler is mapped to uri - {}", this._request.uri());
    }

    if (this._handler instanceof ILargeHttpHandler) {
        switch (this._request.method()) {
        case GET:
            this._handler.get(this._request, this._response);
            break;
        case PUT:
            this._handler.put(this._request, this._response);
            break;
        case PATCH:
            this._handler.patch(this._request, this._response);
            break;
        case POST:
            this._handler.post(this._request, this._response);
            break;
        case DELETE:
            this._handler.delete(this._request, this._response);
            break;
        default:
            throw new BadRequestException("Unsupported http method - {}", this._request.method());
        }
    }

    if (msg instanceof HttpContent) {
        this._request.appendBodyPart((HttpContent) msg);

        // Check body size
        if (this._request.getBodySize() > this._maxBufferSize) {
            throw new InternalServerException("The max buffer size has been reached - {}", this._maxBufferSize);
        }

        if (msg instanceof LastHttpContent) {
            this._request.addTrailer((LastHttpContent) msg);

            switch (this._request.method()) {
            case GET:
                this._handler.get(this._request, this._response);
                break;
            case PUT:
                this._handler.put(this._request, this._response);
                break;
            case POST:
                this._handler.post(this._request, this._response);
                break;
            case DELETE:
                this._handler.delete(this._request, this._response);
                break;
            default:
                throw new BadRequestException("Unsupported http method {}", this._request.method());
            }

            this._response.flush();

            if (!this._request.isKeepAlive()) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
    ReferenceCountUtil.release(msg);
}