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:com.heliosapm.streams.metrichub.tsdbclient.ConnectionManager.java

License:Apache License

/**
 * {@inheritDoc}/*from  w  ww .  j  av  a  2  s. co  m*/
 * @see io.netty.channel.ChannelInboundHandlerAdapter#channelRead(io.netty.channel.ChannelHandlerContext, java.lang.Object)
 */
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    ReferenceCountUtil.retain(msg);
    super.channelRead(ctx, msg);
}

From source file:com.heliosapm.tsdblite.handlers.http.HttpSwitch.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final HttpRequest msg, final List<Object> out)
        throws Exception {
    final String uri = msg.uri();
    log.info("-----------------------> URI [{}]", uri);
    if (uri.endsWith("/favicon.ico")) {
        final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, favicon);
        resp.headers().set(HttpHeaders.CONTENT_TYPE, "image/x-icon");
        resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, favSize);
        ctx.writeAndFlush(resp);/*from   w  w w.  ja v  a  2 s .c o  m*/
        return;
    }
    ReferenceCountUtil.retain(msg);
    final ChannelPipeline p = ctx.pipeline();

    final int index = uri.indexOf("/api/");
    final String endpoint = index == -1 ? "" : uri.substring(5);
    if (index != -1 && pureJsonEndPoints.contains(endpoint)) {
        log.info("Switching to PureJSON handler");
        p.addLast(eventExecutorGroup, "httpToJson", httpToJson);
        //         p.addLast("jsonLogger", loggingHandler);
        p.addLast("jsonDecoder", new JsonObjectDecoder(true));
        //         p.addLast("jsonLogger", loggingHandler);
        p.addLast("traceHandler", traceHandler);
        p.remove(this);
        if (msg instanceof FullHttpMessage) {
            out.add(msg);
        }

    } else {
        log.info("Switching to Http Request Manager");
        out.add(msg);
        p.addLast(eventExecutorGroup, "requestManager", HttpRequestManager.getInstance());
        p.remove(this);
    }
}

From source file:com.tc.websocket.server.handler.WebSocketValidationHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (this.isValidRequest(ctx, req)) {
        ReferenceCountUtil.retain(req);
        ctx.fireChannelRead(req);/*from  w w  w .  j a va2s .  c om*/
    }
}

From source file:example.http2.helloworld.server.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
 */// w w w .j a v a  2s. c o  m
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();
    final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec,
            upgradeCodecFactory);
    final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler = new CleartextHttp2ServerUpgradeHandler(
            sourceCodec, upgradeHandler, new HelloWorldHttp2HandlerBuilder().build());

    p.addLast(cleartextHttp2ServerUpgradeHandler);
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null,
                    new HelloWorldHttp1Handler("Direct. No Upgrade Attempted."));
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    });

    p.addLast(new UserEventLogger());
}

From source file:http2.server.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
 *//*from w ww.j  a v a  2  s .c om*/
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    // ?
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null,
                    new HelloWorldHttp1Handler("Direct. No Upgrade Attempted."));
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    });

    p.addLast(new UserEventLogger());
}

From source file:io.liveoak.common.protocol.DebugHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    log.debugf("%s read : %s // %s", this.name, msg, msg.getClass());
    if (msg instanceof ByteBuf) {
        log.debug(((ByteBuf) msg).toString(Charset.defaultCharset()));
    }//from  www  .j  a v  a 2s . c  o m
    ReferenceCountUtil.retain(msg);
    super.channelRead(ctx, msg);
}

From source file:io.liveoak.container.protocols.http.HttpRequestBodyHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {

    if (msg instanceof LastHttpContent) {

        ByteBuf content = ((HttpContent) msg).content();
        if (fileUpload != null) {
            // if it's a PUT or a POST
            fileUpload.addContent(content.retain(), true);

            // TODO - not sure this is ever necessary - defensive coding
            if (request.state() != null) {
                ((LazyResourceState) request.state()).fileUpload(fileUpload);
            } else {
                fileUpload.delete();/*  w  w  w .  ja va2  s  .c  o m*/
            }

            if (completion != null) {
                // complete the request as body is now fully available
                completion.run();
                completion = null;
            } else {
                // mark that body is fully available
                complete = true;
            }
        } else if (content.readableBytes() > 0) {
            log.debug("on LastHttpContent: " + content.readableBytes() + " bytes discarded!");
        }

    } else if (msg instanceof HttpContent) {

        ByteBuf content = ((HttpContent) msg).content();
        if (fileUpload != null) {
            fileUpload.addContent(content.retain(), false);
        } else if (content.readableBytes() > 0) {
            log.debug("on HttpContent: " + content.readableBytes() + " bytes discarded!");
        }

        // only continue reading body if resource has declared interest
        if (completion != null) {
            ctx.pipeline().firstContext().read();
        }

    } else if (msg instanceof ResourceRequest) {
        // beginning of a new request
        complete = false;
        if (fileUpload != null) {
            fileUpload.delete();
        }
        fileUpload = null;

        ResourceRequest request = (ResourceRequest) msg;
        if (request.requestType() != RequestType.CREATE && request.requestType() != RequestType.UPDATE) {
            // not POST or PUT
            out.add(request);
            ctx.pipeline().firstContext().read();
            return;
        }

        // use original HttpRequest to get to Content-Length, and Content-Type
        HttpRequest original = (HttpRequest) request.requestContext().requestAttributes()
                .getAttribute("HTTP_REQUEST");

        // use last component of target URI as posted resource filename
        List<ResourcePath.Segment> segments = request.resourcePath().segments();
        String filename = segments.size() < 1 ? "unknown" : segments.get(segments.size() - 1).name();
        factory.createAttribute(original, "filename", filename);

        String contentLength = original.headers().get(CONTENT_LENGTH);
        long clen = 0;
        if (contentLength != null) {
            factory.createAttribute(original, CONTENT_LENGTH, contentLength);
            try {
                clen = Long.parseLong(contentLength);
            } catch (Exception ignored) {
                log.debug("Invalid Content-Length received: " + contentLength);
            }
        }

        String contentType = original.headers().get(CONTENT_TYPE);
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        factory.createAttribute(original, CONTENT_TYPE, contentType);
        fileUpload = factory.createFileUpload(original, request.resourcePath().toString(), filename,
                contentType, "binary", Charset.forName("utf-8"), clen);

        // save request for later, so we can update it with fileUpload once body is fully available
        this.request = request;

        out.add(request);

    } else if (msg instanceof Invocation) {

        Invocation invocation = (Invocation) msg;
        if (complete) {
            // body is fully available we should continue processing the request
            invocation.run();
        } else {
            completion = invocation;
        }
    } else {
        // in any other case simply pass the message on as if we're not here
        out.add(ReferenceCountUtil.retain(msg));
    }
}

From source file:io.liveoak.container.protocols.websocket.WebSocketHandshakerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpRequest)) {
        DefaultHttpRequest req = (DefaultHttpRequest) msg;
        String upgrade = req.headers().get(HttpHeaders.Names.UPGRADE);
        if (HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
            // ensure FullHttpRequest by installing HttpObjectAggregator in front of this handler
            ReferenceCountUtil.retain(msg);
            this.configurator.switchToWebSocketsHandshake(ctx.pipeline());
            ctx.pipeline().fireChannelRead(msg);
        } else {/*from w ww.j a  v  a  2s  . c  om*/
            ReferenceCountUtil.retain(msg);
            this.configurator.switchToPlainHttp(ctx.pipeline());
            ctx.pipeline().fireChannelRead(msg);
        }
    } else {
        // do the handshake
        FullHttpRequest req = (FullHttpRequest) msg;
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.getUri(), null,
                false);
        WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            ChannelFuture future = handshaker.handshake(ctx.channel(), req);
            future.addListener(f -> {
                this.configurator.switchToWebSockets(ctx.pipeline());
            });
        }
    }
}

From source file:io.liveoak.stomp.common.AbstractControlFrameHandler.java

License:Open Source License

public void handleFrame(ChannelHandlerContext ctx, StompFrame msg) throws StompServerException {
    if (msg instanceof StompControlFrame) {
        handleControlFrame(ctx, (StompControlFrame) msg);
        return;//from  www  . j  a va2s  .  c om
    }

    ReferenceCountUtil.retain(msg);
    ctx.fireChannelRead(msg);
}

From source file:io.liveoak.stomp.common.AbstractFrameHandler.java

License:Open Source License

public void channelRead0(ChannelHandlerContext ctx, StompFrame msg) throws Exception {
    if (this.command != null) {
        if (msg.command().equals(this.command)) {
            handleFrame(ctx, msg);//from  w w  w  .j  a v a 2s.c  o m
            return;
        }
    }

    ReferenceCountUtil.retain(msg);
    ctx.fireChannelRead(msg);
}