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:io.scalecube.socketio.pipeline.WebSocketHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?/*from   w  w w .j a  v  a  2  s. co m*/
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        if (req.getMethod() == HttpMethod.GET && req.getUri().startsWith(connectPath)) {
            final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
            final String requestPath = queryDecoder.path();

            if (log.isDebugEnabled())
                log.debug("Received HTTP {} handshake request: {} {} from channel: {}",
                        getTransportType().getName(), req.getMethod(), requestPath, ctx.channel());

            handshake(ctx, req, requestPath);

            ReferenceCountUtil.release(msg);
            return;
        }
    } else if (msg instanceof WebSocketFrame && isCurrentHandlerSession(ctx)) {
        handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        return;
    }
    ctx.fireChannelRead(msg);
}

From source file:io.scalecube.socketio.pipeline.XHRPollingHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?//  w  w  w  . j a va 2  s  .co  m
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        if (requestPath.startsWith(connectPath)) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP XHR-Polling request: {} {} from channel: {}", requestMethod,
                        requestPath, ctx.channel());

            final String sessionId = PipelineUtils.getSessionId(requestPath);
            final String origin = PipelineUtils.getOrigin(req);

            if (HttpMethod.GET.equals(requestMethod)) {
                SocketAddress clientIp = PipelineUtils.getHeaderClientIPParamValue(req, remoteAddressHeader);

                // Process polling request from client
                final ConnectPacket packet = new ConnectPacket(sessionId, origin);
                packet.setTransportType(TransportType.XHR_POLLING);
                packet.setRemoteAddress(clientIp);

                ctx.fireChannelRead(packet);
            } else if (HttpMethod.POST.equals(requestMethod)) {
                // Process message request from client
                List<Packet> packets = PacketFramer.decodePacketsFrame(req.content());
                for (Packet packet : packets) {
                    packet.setSessionId(sessionId);
                    packet.setOrigin(origin);
                    ctx.fireChannelRead(packet);
                }
            } else {
                log.warn("Can't process HTTP XHR-Polling request. Unknown request method: {} from channel: {}",
                        requestMethod, ctx.channel());
            }
            ReferenceCountUtil.release(msg);
            return;
        }
    }

    ctx.fireChannelRead(msg);
}

From source file:io.vertx.core.http.impl.ClientConnection.java

License:Open Source License

public NetSocket createNetSocket() {
    // connection was upgraded to raw TCP socket
    NetSocketImpl socket = new NetSocketImpl(vertx, channel, context, client.getSslHelper(), metrics);
    socket.metric(metric());//from w ww  . j  a v a  2  s.  co  m
    Map<Channel, NetSocketImpl> connectionMap = new HashMap<>(1);
    connectionMap.put(channel, socket);

    // Flush out all pending data
    endReadAndFlush();

    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = channel.pipeline();
    ChannelHandler inflater = pipeline.get(HttpContentDecompressor.class);
    if (inflater != null) {
        pipeline.remove(inflater);
    }
    pipeline.remove("codec");
    pipeline.replace("handler", "handler", new VertxNetHandler<NetSocketImpl>(channel, socket, connectionMap) {
        @Override
        public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception {
            // remove from the real mapping
            pool.removeChannel(channel);
            super.exceptionCaught(chctx, t);
        }

        @Override
        public void channelInactive(ChannelHandlerContext chctx) throws Exception {
            // remove from the real mapping
            pool.removeChannel(channel);
            super.channelInactive(chctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
            if (msg instanceof HttpContent) {
                if (msg instanceof LastHttpContent) {
                    handleResponseEnd((LastHttpContent) msg);
                }
                ReferenceCountUtil.release(msg);
                return;
            }
            super.channelRead(chctx, msg);
        }

        @Override
        protected void handleMsgReceived(NetSocketImpl conn, Object msg) {
            ByteBuf buf = (ByteBuf) msg;
            conn.handleDataReceived(Buffer.buffer(buf));
        }
    });
    return socket;
}

From source file:io.vertx.core.http.impl.Http1xClientConnection.java

License:Open Source License

private synchronized NetSocket upgrade(StreamImpl stream) {
    if (options.isPipelining()) {
        throw new IllegalStateException("Cannot upgrade a pipe-lined request");
    }//from  ww  w . ja  va  2s .  co m
    if (upgraded) {
        throw new IllegalStateException("Request already upgraded to NetSocket");
    }
    upgraded = true;

    // connection was upgraded to raw TCP socket
    AtomicBoolean paused = new AtomicBoolean(false);
    NetSocketImpl socket = new NetSocketImpl(vertx, chctx, context, client.getSslHelper(), metrics) {
        {
            super.pause();
        }

        @Override
        public synchronized NetSocket handler(Handler<Buffer> dataHandler) {
            return super.handler(dataHandler);
        }

        @Override
        public synchronized NetSocket pause() {
            paused.set(true);
            return super.pause();
        }

        @Override
        public synchronized NetSocket resume() {
            paused.set(false);
            return super.resume();
        }
    };
    socket.metric(metric());

    // Flush out all pending data
    endReadAndFlush();

    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = chctx.pipeline();
    ChannelHandler inflater = pipeline.get(HttpContentDecompressor.class);
    if (inflater != null) {
        pipeline.remove(inflater);
    }
    pipeline.replace("handler", "handler", new VertxNetHandler(socket) {
        @Override
        public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
            if (msg instanceof HttpContent) {
                if (msg instanceof LastHttpContent) {
                    stream.endResponse((LastHttpContent) msg);
                }
                ReferenceCountUtil.release(msg);
                return;
            }
            super.channelRead(chctx, msg);
        }
    }.removeHandler(sock -> listener.onDiscard()));

    // Removing this codec might fire pending buffers in the HTTP decoder
    // this happens when the channel reads the HTTP response and the following data in a single buffer
    pipeline.remove("codec");

    // Async check to deliver the pending messages
    // because the netSocket access in HttpClientResponse is synchronous
    // we need to pause the NetSocket to avoid losing or reordering buffers
    // and then asynchronously un-pause it unless it was actually paused by the application
    context.runOnContext(v -> {
        if (!paused.get()) {
            socket.resume();
        }
    });

    return socket;
}

From source file:io.vertx.core.http.impl.Http1xServerConnection.java

License:Open Source License

NetSocket createNetSocket() {
    NetSocketImpl socket = new NetSocketImpl(vertx, chctx, context, sslHelper, metrics);
    socket.metric(metric());/*w  w w.j a va2s.c om*/
    Map<Channel, NetSocketImpl> connectionMap = new HashMap<>(1);
    connectionMap.put(chctx.channel(), socket);

    // Flush out all pending data
    endReadAndFlush();

    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = chctx.pipeline();
    ChannelHandler compressor = pipeline.get(HttpChunkContentCompressor.class);
    if (compressor != null) {
        pipeline.remove(compressor);
    }

    pipeline.remove("httpDecoder");
    if (pipeline.get("chunkedWriter") != null) {
        pipeline.remove("chunkedWriter");
    }

    chctx.pipeline().replace("handler", "handler", new VertxNetHandler(socket) {
        @Override
        public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
            if (msg instanceof HttpContent) {
                ReferenceCountUtil.release(msg);
                return;
            }
            super.channelRead(chctx, msg);
        }
    }.removeHandler(sock -> {
        if (metrics != null) {
            metrics.responseEnd(responseInProgress.metric(), responseInProgress.response());
        }
        connectionMap.remove(chctx.channel());
    }));

    // check if the encoder can be removed yet or not.
    chctx.pipeline().remove("httpEncoder");
    return socket;
}

From source file:io.vertx.core.http.impl.ServerConnection.java

License:Open Source License

NetSocket createNetSocket() {
    NetSocketImpl socket = new NetSocketImpl(vertx, channel, context, server.getSslHelper(), metrics);
    socket.metric(metric());//w  ww  .  ja v a 2 s.  co  m
    Map<Channel, NetSocketImpl> connectionMap = new HashMap<>(1);
    connectionMap.put(channel, socket);

    // Flush out all pending data
    endReadAndFlush();

    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = channel.pipeline();
    ChannelHandler compressor = pipeline.get(HttpChunkContentCompressor.class);
    if (compressor != null) {
        pipeline.remove(compressor);
    }

    pipeline.remove("httpDecoder");
    if (pipeline.get("chunkedWriter") != null) {
        pipeline.remove("chunkedWriter");
    }

    channel.pipeline().replace("handler", "handler",
            new VertxNetHandler<NetSocketImpl>(channel, socket, connectionMap) {
                @Override
                public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception {
                    // remove from the real mapping
                    server.removeChannel(channel);
                    super.exceptionCaught(chctx, t);
                }

                @Override
                public void channelInactive(ChannelHandlerContext chctx) throws Exception {
                    // remove from the real mapping
                    server.removeChannel(channel);
                    super.channelInactive(chctx);
                }

                @Override
                public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
                    if (msg instanceof HttpContent) {
                        ReferenceCountUtil.release(msg);
                        return;
                    }
                    super.channelRead(chctx, msg);
                }

                @Override
                protected void handleMsgReceived(NetSocketImpl conn, Object msg) {
                    ByteBuf buf = (ByteBuf) msg;
                    conn.handleDataReceived(Buffer.buffer(buf));
                }
            });

    // check if the encoder can be removed yet or not.
    if (lastWriteFuture == null) {
        channel.pipeline().remove("httpEncoder");
    } else {
        lastWriteFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                channel.pipeline().remove("httpEncoder");
            }
        });
    }
    return socket;
}

From source file:it.jnrpe.net.JNRPEServerHandler.java

License:Apache License

/**
 * Method channelRead./*from  w ww  .  j  a v a  2s .c o m*/
 * @param ctx ChannelHandlerContext
 * @param msg Object
 * @see io.netty.channel.ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)
 */
@Override
public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    try {
        JNRPERequest req = (JNRPERequest) msg;

        ReturnValue ret = commandInvoker.invoke(req.getCommand(), req.getArguments());

        JNRPEResponse res = new JNRPEResponse();
        res.setPacketVersion(PacketVersion.VERSION_2);

        res.setResultCode(ret.getStatus().intValue());
        res.setMessage(ret.getMessage());

        ChannelFuture channelFuture = ctx.writeAndFlush(res);
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:lesson.discard.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;/*from  w  w  w.  j  av  a2  s.c o m*/
    try {
        while (in.isReadable()) { // (1)
            System.out.print((char) in.readByte());
            System.out.flush();
        }
    } finally {
        ReferenceCountUtil.release(msg); // (2)
    }

}

From source file:lesson.echo.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;/*from w  w  w  .ja va 2  s  . com*/
    try {
        while (in.isReadable()) {
            System.out.print((char) in.readByte());
            System.out.flush();
        }

        ctx.write(msg);
        //ctx.flush();

    } finally {
        ReferenceCountUtil.release(msg);
    }

}

From source file:lunarion.cluster.coordinator.server.CoordinatorServerHandler.java

License:Open Source License

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

    try {//from w ww . j  a  v a  2s  . co  m
        ByteBuf buf = (ByteBuf) msg;

        MessageRequest request = new MessageRequest();
        request.read(buf);
        /* 
        System.out.println("Coordinator received command: "+ request.getCMD());
        System.out.println("Coordinator received UUID: "+ request.getUUID());
        for(int i=0;i<request.getParams().length;i++)
        {
          System.out.println("Coordinator received: "+ request.getParams()[i]);
        }
        */
        ResourceDistributed res = co.getResource(request.getParams()[0]);

        TaskRedirectMessage recvTask = new TaskRedirectMessage(request, res, ctx, logger, response_map);

        thread_executor.submit(recvTask);

    } finally {
        ReferenceCountUtil.release(msg);
    }
}