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.linecorp.armeria.client.http.HttpSessionHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof Http2Settings) {
        // Expected
    } else {/*from w  ww.jav a 2s.  c  o m*/
        try {
            final String typeInfo;
            if (msg instanceof ByteBuf) {
                typeInfo = msg + " HexDump: " + ByteBufUtil.hexDump((ByteBuf) msg);
            } else {
                typeInfo = String.valueOf(msg);
            }
            throw new IllegalStateException("unexpected message type: " + typeInfo);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

From source file:com.linecorp.armeria.client.Http1ResponseDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);/*w ww.  j av  a2s .  c o  m*/
        return;
    }

    try {
        switch (state) {
        case NEED_HEADERS:
            if (msg instanceof HttpResponse) {
                final HttpResponse nettyRes = (HttpResponse) msg;
                final DecoderResult decoderResult = nettyRes.decoderResult();
                if (!decoderResult.isSuccess()) {
                    fail(ctx, new ProtocolViolationException(decoderResult.cause()));
                    return;
                }

                if (!HttpUtil.isKeepAlive(nettyRes)) {
                    disconnectWhenFinished();
                }

                final HttpResponseWrapper res = getResponse(resId);
                assert res != null;
                this.res = res;

                if (nettyRes.status().codeClass() == HttpStatusClass.INFORMATIONAL) {
                    state = State.NEED_INFORMATIONAL_DATA;
                } else {
                    state = State.NEED_DATA_OR_TRAILING_HEADERS;
                }

                res.scheduleTimeout(ctx);
                res.write(ArmeriaHttpUtil.toArmeria(nettyRes));
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case NEED_INFORMATIONAL_DATA:
            if (msg instanceof LastHttpContent) {
                state = State.NEED_HEADERS;
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case NEED_DATA_OR_TRAILING_HEADERS:
            if (msg instanceof HttpContent) {
                final HttpContent content = (HttpContent) msg;
                final DecoderResult decoderResult = content.decoderResult();
                if (!decoderResult.isSuccess()) {
                    fail(ctx, new ProtocolViolationException(decoderResult.cause()));
                    return;
                }

                final ByteBuf data = content.content();
                final int dataLength = data.readableBytes();
                if (dataLength > 0) {
                    assert res != null;
                    final long maxContentLength = res.maxContentLength();
                    if (maxContentLength > 0 && res.writtenBytes() > maxContentLength - dataLength) {
                        fail(ctx, ContentTooLargeException.get());
                        return;
                    } else {
                        res.write(HttpData.of(data));
                    }
                }

                if (msg instanceof LastHttpContent) {
                    final HttpResponseWrapper res = removeResponse(resId++);
                    assert res != null;
                    assert this.res == res;
                    this.res = null;

                    state = State.NEED_HEADERS;

                    final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                    if (!trailingHeaders.isEmpty()) {
                        res.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                    }

                    res.close();

                    if (needsToDisconnect()) {
                        ctx.close();
                    }
                }
            } else {
                failWithUnexpectedMessageType(ctx, msg);
            }
            break;
        case DISCARD:
            break;
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linecorp.armeria.client.HttpRemoteInvoker.java

License:Apache License

private static <T> void decodeResult(ClientCodec codec, Promise<T> resultPromise, ServiceInvocationContext ctx,
        FullHttpResponse response) {/*from  w ww. ja  v  a2s  .c  o m*/
    try {
        ctx.resolvePromise(resultPromise, codec.decodeResponse(ctx, response.content(), response));
    } catch (Throwable e) {
        ctx.rejectPromise(resultPromise, e);
    } finally {
        ReferenceCountUtil.release(response);
    }
}

From source file:com.linecorp.armeria.server.http.Http1RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);//  w ww . j  av  a 2  s . c om
        return;
    }

    // this.req can be set to null by fail(), so we keep it in a local variable.
    DecodedHttpRequest req = this.req;
    try {
        if (discarding) {
            return;
        }

        if (req == null) {
            if (msg instanceof HttpRequest) {
                final HttpRequest nettyReq = (HttpRequest) msg;
                if (!nettyReq.decoderResult().isSuccess()) {
                    fail(ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                final HttpHeaders nettyHeaders = nettyReq.headers();
                final int id = ++receivedRequests;

                // Validate the 'content-length' header.
                final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
                if (contentLengthStr != null) {
                    final long contentLength;
                    try {
                        contentLength = Long.parseLong(contentLengthStr);
                    } catch (NumberFormatException ignored) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                    if (contentLength < 0) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                }

                nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme);

                this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1,
                        ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq),
                        inboundTrafficController);

                ctx.fireChannelRead(req);
            } else {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
        }

        if (req != null && msg instanceof HttpContent) {
            final HttpContent content = (HttpContent) msg;
            final DecoderResult decoderResult = content.decoderResult();
            if (!decoderResult.isSuccess()) {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                req.close(new ProtocolViolationException(decoderResult.cause()));
                return;
            }

            final ByteBuf data = content.content();
            final int dataLength = data.readableBytes();
            if (dataLength != 0) {
                final long maxContentLength = req.maxRequestLength();
                if (maxContentLength > 0 && req.writtenBytes() > maxContentLength - dataLength) {
                    fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                    req.close(ContentTooLargeException.get());
                    return;
                }

                req.write(HttpData.of(data));
            }

            if (msg instanceof LastHttpContent) {
                final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                if (!trailingHeaders.isEmpty()) {
                    req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                }

                req.close();
                this.req = req = null;
            }
        }
    } catch (Throwable t) {
        fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (req != null) {
            req.close(t);
        } else {
            logger.warn("Unexpected exception:", t);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linecorp.armeria.server.Http1RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);/*w  w  w.ja  v a2  s  .  co  m*/
        return;
    }

    // this.req can be set to null by fail(), so we keep it in a local variable.
    DecodedHttpRequest req = this.req;
    try {
        if (discarding) {
            return;
        }

        if (req == null) {
            if (msg instanceof HttpRequest) {
                final HttpRequest nettyReq = (HttpRequest) msg;
                if (!nettyReq.decoderResult().isSuccess()) {
                    fail(ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                final HttpHeaders nettyHeaders = nettyReq.headers();
                final int id = ++receivedRequests;

                // Validate the method.
                if (!HttpMethod.isSupported(nettyReq.method().name())) {
                    fail(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
                    return;
                }

                // Validate the 'content-length' header.
                final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
                final boolean contentEmpty;
                if (contentLengthStr != null) {
                    final long contentLength;
                    try {
                        contentLength = Long.parseLong(contentLengthStr);
                    } catch (NumberFormatException ignored) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                    if (contentLength < 0) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }

                    contentEmpty = contentLength == 0;
                } else {
                    contentEmpty = true;
                }

                nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme);

                this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1,
                        ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq),
                        inboundTrafficController, cfg.defaultMaxRequestLength());

                // Close the request early when it is sure that there will be
                // neither content nor trailing headers.
                if (contentEmpty && !HttpUtil.isTransferEncodingChunked(nettyReq)) {
                    req.close();
                }

                ctx.fireChannelRead(req);
            } else {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
        }

        if (req != null && msg instanceof HttpContent) {
            final HttpContent content = (HttpContent) msg;
            final DecoderResult decoderResult = content.decoderResult();
            if (!decoderResult.isSuccess()) {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                req.close(new ProtocolViolationException(decoderResult.cause()));
                return;
            }

            final ByteBuf data = content.content();
            final int dataLength = data.readableBytes();
            if (dataLength != 0) {
                req.increaseTransferredBytes(dataLength);
                final long maxContentLength = req.maxRequestLength();
                if (maxContentLength > 0 && req.transferredBytes() > maxContentLength) {
                    fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                    req.close(ContentTooLargeException.get());
                    return;
                }

                if (req.isOpen()) {
                    req.write(new ByteBufHttpData(data.retain(), false));
                }
            }

            if (msg instanceof LastHttpContent) {
                final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                if (!trailingHeaders.isEmpty()) {
                    req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                }

                req.close();
                this.req = req = null;
            }
        }
    } catch (URISyntaxException e) {
        fail(ctx, HttpResponseStatus.BAD_REQUEST);
        if (req != null) {
            req.close(e);
        }
    } catch (Throwable t) {
        fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (req != null) {
            req.close(t);
        } else {
            logger.warn("Unexpected exception:", t);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.my.netty.object.ObjectEchoClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // TODO Auto-generated method stub
    try {// ww w.j av  a  2 s.  c o  m
        System.out.println("client get message:" + msg.toString());
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.my.netty.object.ObjectEchoServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // TODO Auto-generated method stub
    try {/* w ww  .j  a va 2 s.com*/
        System.out.println("server get msg" + msg.getClass());
        ctx.write("ok" + ctx.channel());
        ctx.flush();
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.mycompany.device.FFDevice.java

public FFDevice(SocketChannel ch) {
    this.req = null;
    this.soc = ch;
    this.data_rcv = soc.alloc().buffer(512);
    this.reg_str = "";
    this.connect_time = System.currentTimeMillis();

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new IdleStateHandler(0, 0, idle_time_interval_s));
    pipeline.addLast(new MessageToByteEncoder<byte[]>() {
        @Override//  ww  w  .  j  av  a  2  s  . com
        protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
            // TODO Auto-generated method stub
            out.writeBytes(msg);
        }
    });
    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // TODO Auto-generated method stub
            ByteBuf bb = (ByteBuf) msg;
            if (reg_str.equals("")) {
                reg_str = bb.toString(Charset.defaultCharset());
                FFServer.logger.info(String.format("device that has regs %s is registed", reg_str));
            } else {
                FFServer.logger.debug(String.format("%s receive: %d bytes", reg_str, bb.readableBytes()));
                data_rcv.writeBytes(bb);
            }
            ReferenceCountUtil.release(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // TODO Auto-generated method stub
            FFServer.logger.error(cause);
            Close();
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.ALL_IDLE) {
                    FFServer.logger.info(String.format("%s in idle state", reg_str));

                    ByteBuf hb = ctx.alloc().buffer(1).writeByte('.');
                    Send(hb);
                }
            }
        }
    });

    ChannelFuture f = soc.closeFuture();
    f.addListener((ChannelFutureListener) new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            is_closed = true;
            FFServer.logger.info(String.format("%s disconnected", reg_str));
        }
    });
}

From source file:com.oskm.netty.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // TODO Auto-generated method stub
    ByteBuf in = (ByteBuf) msg;//from  www  .  j  a  v  a2s .  c  om

    try {
        while (in.isReadable()) {
            System.out.print((char) in.readByte());
            System.out.flush();
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        ReferenceCountUtil.release(msg);

    }
}

From source file:com.shun.liu.quickserver.socksproxy.RelayHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (relayChannel.isActive()) {

        relayChannel.writeAndFlush(msg);
    } else {/*w  w w.j a v  a 2s . co m*/
        ReferenceCountUtil.release(msg);
    }
}