Example usage for io.netty.channel ChannelPipeline remove

List of usage examples for io.netty.channel ChannelPipeline remove

Introduction

In this page you can find the example usage for io.netty.channel ChannelPipeline remove.

Prototype

<T extends ChannelHandler> T remove(Class<T> handlerType);

Source Link

Document

Removes the ChannelHandler of the specified type from this pipeline.

Usage

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());//from w  ww.  j  a  va2  s .c om
    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:io.vertx.core.http.impl.WebSocketHandshakeInboundHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse resp = (HttpResponse) msg;
        response = new DefaultFullHttpResponse(resp.protocolVersion(), resp.status());
        response.headers().add(resp.headers());
    }/*from   www  .  j a v a2s.com*/
    if (msg instanceof HttpContent) {
        if (response != null) {
            response.content().writeBytes(((HttpContent) msg).content());
            if (msg instanceof LastHttpContent) {
                response.trailingHeaders().add(((LastHttpContent) msg).trailingHeaders());
                ChannelPipeline pipeline = chctx.pipeline();
                pipeline.remove(WebSocketHandshakeInboundHandler.this);
                ChannelHandler handler = pipeline.get(HttpContentDecompressor.class);
                if (handler != null) {
                    // remove decompressor as its not needed anymore once connection was upgraded to websockets
                    ctx.pipeline().remove(handler);
                }
                Future<Void> fut = handshakeComplete(response);
                wsHandler.handle(fut);
            }
        }
    }
}

From source file:io.werval.server.netty.SubProtocolSwitchHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext context, Object message) throws Exception {
    if (message instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) message;
        LOG.trace("Switching to plain HTTP protocol");
        ChannelPipeline pipeline = context.pipeline();

        int maxBodySize = app.config().intNumber(WERVAL_HTTP_REQUESTS_BODY_MAX_SIZE);
        int diskThreshold = app.config().intNumber(WERVAL_HTTP_REQUESTS_BODY_DISK_THRESHOLD);
        pipeline.addLast("http-aggregator",
                new HttpRequestAggregator(helper, app.events(), maxBodySize, diskThreshold, app.tmpdir()));
        pipeline.addLast("werval-http", new WervalHttpHandler(app, devSpi));

        pipeline.remove(this);

        context.fireChannelRead(request);
    } else if (message instanceof WebSocketFrame) {
        WebSocketFrame frame = (WebSocketFrame) message;
        LOG.trace("Switching to WebSocket protocol");
        ChannelPipeline pipeline = context.pipeline();

        pipeline.addLast("werval-websocket", new WervalSocketHandler(app, devSpi));

        pipeline.remove(this);

        frame.retain(); // TODO Check this
        context.fireChannelRead(frame);//from   ww  w  .  j a  v  a 2s. c  o  m
    } else {
        LOG.warn("Received a message of an unknown type ({}), channel will be closed.", message.getClass());
        context.channel().close();
    }
}

From source file:jp.llv.locapi.PacketHandler.java

License:Open Source License

protected static void unhandle(ProxiedPlayer player) {
    ChannelPipeline chp = getPipeline(player);
    try {//www  . ja v a2 s  .  c o m
        chp.remove(PACKET_LISTENER);
    } catch (NoSuchElementException ex) {
        //do nothing
    }
}

From source file:net.sourceforge.entrainer.socket.PortUnificationHandler.java

License:Open Source License

private void switchToWebSockets(ChannelHandlerContext ctx) throws Exception {
    ChannelPipeline pipeline = ctx.pipeline();

    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("handler", webSocketHandler);
    webSocketHandler.channelActive(ctx);

    pipeline.remove(this);
}

From source file:net.sourceforge.entrainer.socket.PortUnificationHandler.java

License:Open Source License

private void switchToJava(ChannelHandlerContext ctx) throws Exception {
    ChannelPipeline pipeline = ctx.pipeline();

    pipeline.addLast(new LengthFieldBasedFrameDecoder(10000, 0, 4, 0, 4));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new LengthFieldPrepender(4));
    pipeline.addLast(new StringEncoder());
    pipeline.addLast(nettyConnectionHandler);
    nettyConnectionHandler.channelActive(ctx);

    pipeline.remove(this);
}

From source file:org.aotorrent.client.OutboundHandshakeHandler.java

License:Apache License

@Override
protected synchronized void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    final ByteBuf buf = (ByteBuf) msg;

    if (handshakeDone) {
        super.channelRead(ctx, msg);
        return;/*from  w  w  w .  j a va  2  s.  c om*/
    }

    try {

        HandshakeRequest handshakeRequest = new HandshakeRequest(buf);

        if (ArrayUtils.isEquals(handshakeRequest.getInfoHash(), torrentEngine.getInfoHash())) {
            handshakeDone = true;
            PeerConnection peerConnection = new PeerConnection(torrentEngine, ctx);
            torrentEngine.registerConnection(ctx.channel().remoteAddress(), peerConnection);
            final ChannelPipeline pipeline = ctx.pipeline();
            pipeline.addLast("peerConnection", peerConnection);
            pipeline.remove(this);
            ByteBuf out = ((ByteBuf) msg).copy();
            ctx.fireChannelRead(out);
            peerConnection.sendBitField();
        }

    } finally {
        buf.release();
    }
}

From source file:org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty.NettyConnectorTest.java

License:Apache License

@Test
public void testChannelHandlerRemovedWhileCreatingConnection() throws Exception {
    BufferHandler handler = (connectionID, buffer) -> {
    };//from   ww  w. j a  v a2 s.  c  om
    Map<String, Object> params = new HashMap<>();
    final ExecutorService closeExecutor = Executors
            .newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory());
    final ExecutorService threadPool = Executors
            .newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory());
    final ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5,
            ActiveMQThreadFactory.defaultThreadFactory());
    try {
        NettyConnector connector = new NettyConnector(params, handler, listener, closeExecutor, threadPool,
                scheduledThreadPool);
        connector.start();
        final Connection connection = connector.createConnection(future -> {
            future.awaitUninterruptibly();
            Assert.assertTrue(future.isSuccess());
            final ChannelPipeline pipeline = future.channel().pipeline();
            final ActiveMQChannelHandler activeMQChannelHandler = pipeline.get(ActiveMQChannelHandler.class);
            Assert.assertNotNull(activeMQChannelHandler);
            pipeline.remove(activeMQChannelHandler);
            Assert.assertNull(pipeline.get(ActiveMQChannelHandler.class));
        });
        Assert.assertNull(connection);
        connector.close();
    } finally {
        closeExecutor.shutdownNow();
        threadPool.shutdownNow();
        scheduledThreadPool.shutdownNow();
    }
}

From source file:org.apache.hadoop.hbase.ipc.NettyRpcConnection.java

License:Apache License

private void saslNegotiate(final Channel ch) {
    UserGroupInformation ticket = getUGI();
    if (ticket == null) {
        failInit(ch, new FatalConnectionException("ticket/user is null"));
        return;//www  .j  a v a  2s . c om
    }
    Promise<Boolean> saslPromise = ch.eventLoop().newPromise();
    final NettyHBaseSaslRpcClientHandler saslHandler;
    try {
        saslHandler = new NettyHBaseSaslRpcClientHandler(saslPromise, ticket, authMethod, token,
                serverPrincipal, rpcClient.fallbackAllowed, this.rpcClient.conf);
    } catch (IOException e) {
        failInit(ch, e);
        return;
    }
    ch.pipeline().addFirst(new SaslChallengeDecoder(), saslHandler);
    saslPromise.addListener(new FutureListener<Boolean>() {

        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (future.isSuccess()) {
                ChannelPipeline p = ch.pipeline();
                p.remove(SaslChallengeDecoder.class);
                p.remove(NettyHBaseSaslRpcClientHandler.class);

                // check if negotiate with server for connection header is necessary
                if (saslHandler.isNeedProcessConnectionHeader()) {
                    Promise<Boolean> connectionHeaderPromise = ch.eventLoop().newPromise();
                    // create the handler to handle the connection header
                    ChannelHandler chHandler = new NettyHBaseRpcConnectionHeaderHandler(connectionHeaderPromise,
                            conf, connectionHeaderWithLength);

                    // add ReadTimeoutHandler to deal with server doesn't response connection header
                    // because of the different configuration in client side and server side
                    p.addFirst(new ReadTimeoutHandler(RpcClient.DEFAULT_SOCKET_TIMEOUT_READ,
                            TimeUnit.MILLISECONDS));
                    p.addLast(chHandler);
                    connectionHeaderPromise.addListener(new FutureListener<Boolean>() {
                        @Override
                        public void operationComplete(Future<Boolean> future) throws Exception {
                            if (future.isSuccess()) {
                                ChannelPipeline p = ch.pipeline();
                                p.remove(ReadTimeoutHandler.class);
                                p.remove(NettyHBaseRpcConnectionHeaderHandler.class);
                                // don't send connection header, NettyHbaseRpcConnectionHeaderHandler
                                // sent it already
                                established(ch);
                            } else {
                                final Throwable error = future.cause();
                                scheduleRelogin(error);
                                failInit(ch, toIOE(error));
                            }
                        }
                    });
                } else {
                    // send the connection header to server
                    ch.write(connectionHeaderWithLength.retainedDuplicate());
                    established(ch);
                }
            } else {
                final Throwable error = future.cause();
                scheduleRelogin(error);
                failInit(ch, toIOE(error));
            }
        }
    });
}

From source file:org.apache.hadoop.hbase.security.NettyHBaseRpcConnectionHeaderHandler.java

License:Apache License

/**
 * Remove handlers for sasl encryption and add handlers for Crypto AES encryption
 *//*from w  ww  .j a  v a2s.  c o m*/
private void setupCryptoAESHandler(ChannelPipeline p, CryptoAES cryptoAES) {
    p.remove(SaslWrapHandler.class);
    p.remove(SaslUnwrapHandler.class);
    String lengthDecoder = p.context(LengthFieldBasedFrameDecoder.class).name();
    p.addAfter(lengthDecoder, null, new CryptoAESUnwrapHandler(cryptoAES));
    p.addAfter(lengthDecoder, null, new CryptoAESWrapHandler(cryptoAES));
}