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:org.neo4j.bolt.transport.TransportSelectionHandler.java

License:Open Source License

private void switchToWebsocket(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    p.addLast(new HttpServerCodec(), new HttpObjectAggregator(MAX_WEBSOCKET_HANDSHAKE_SIZE),
            new WebSocketServerProtocolHandler(""), new WebSocketFrameTranslator(), new SocketTransportHandler(
                    new SocketTransportHandler.ProtocolChooser(protocolVersions, isEncrypted), logging));
    p.remove(this);
}

From source file:org.thingsplode.synapse.proxy.Dispatcher.java

License:Apache License

protected void connect() throws InterruptedException {
    try {/*from ww  w  .  ja v  a2s .  c  om*/
        ChannelFuture cf = b.connect(host, port).addListener((ChannelFutureListener) (ChannelFuture future) -> {
            if (!future.isSuccess()) {
                logger.warn("Connecting to the channel was not successfull.");
            } else {
                logger.debug("Connected Channel@EndpointProxy");
            }
        }).sync();

        ChannelHandler handler = cf.channel().pipeline().get(EndpointProxy.WS_MESSAGE_DECODER);
        if (handler != null) {
            //if websocket client handler is added to the mix, the next step is to handshake with it
            logger.debug("Initiating websocket handshake ...");
            ((WSMessageDecoder) handler).getHandshakeFuture().sync()
                    .addListener((ChannelFutureListener) (ChannelFuture future) -> {
                        if (!future.isSuccess()) {
                            //todo: close dispatcher and websocket connection
                            //((WSResponseToResponseDecoder) handler).
                        } else {
                            logger.debug("Handshake@EndpointProxy");
                            ChannelPipeline pl = future.channel().pipeline();
                            if (pl.get(EndpointProxy.HTTP_REQUEST_ENCODER) != null) {
                                pl.remove(EndpointProxy.HTTP_REQUEST_ENCODER);
                            }

                            if (pl.get(EndpointProxy.HTTP_RESPONSE_DECODER) != null) {
                                pl.remove(EndpointProxy.HTTP_RESPONSE_DECODER);
                            }

                            if (pl.get(EndpointProxy.HTTP_RESPONSE_AGGREGATOR) != null) {
                                pl.remove(EndpointProxy.HTTP_RESPONSE_AGGREGATOR);
                            }
                        }
                    });
        }

        while (!cf.isSuccess()) {
            logger.warn("Connection attempt was not successfull / retrying...");
            cf = handleReconnect(b, host, port);
            if (cf == null) {
                break;
            }
        }

        this.channel = cf.channel();
        if (channel == null) {
            throw new InterruptedException("Cannot connect.");
        }
        channel.closeFuture().addListener((ChannelFutureListener) (ChannelFuture future) -> {
            if (future.isSuccess()) {
                logger.debug("Channel@Proxy is closed / evicting active requests.");
                dispatchedFutureHandler.evictActiveRequests();
            }
        });
    } catch (Exception ex) {
        logger.warn("Could not connect: " + ex.getMessage(), ex);
        ChannelFuture cf2 = handleReconnect(b, host, port);
        if (cf2 != null) {
            this.channel = cf2.channel();
        } else {
            throw ex;
        }
    }
}

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

License:Open Source License

NetSocket createNetSocket() {
    // connection was upgraded to raw TCP socket
    upgradedConnection = true;/*from  w  w  w.  ja v a2s  .  c o  m*/
    DefaultNetSocket socket = new DefaultNetSocket(vertx, channel, context, client.tcpHelper, true);
    Map<Channel, DefaultNetSocket> connectionMap = new HashMap<Channel, DefaultNetSocket>(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(client.vertx, connectionMap) {
        @Override
        public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception {
            // remove from the real mapping
            client.connectionMap.remove(channel);
            super.exceptionCaught(chctx, t);
        }

        @Override
        public void channelInactive(ChannelHandlerContext chctx) throws Exception {
            // remove from the real mapping
            client.connectionMap.remove(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);
        }
    });
    return socket;
}

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

License:Open Source License

NetSocket createNetSocket() {
    DefaultNetSocket socket = new DefaultNetSocket(vertx, channel, context, server.tcpHelper, false);
    Map<Channel, DefaultNetSocket> connectionMap = new HashMap<Channel, DefaultNetSocket>(1);
    connectionMap.put(channel, socket);/*from  ww  w . j a v a  2s.  c o m*/

    // 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(server.vertx, connectionMap) {
        @Override
        public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception {
            // remove from the real mapping
            server.connectionMap.remove(channel);
            super.exceptionCaught(chctx, t);
        }

        @Override
        public void channelInactive(ChannelHandlerContext chctx) throws Exception {
            // remove from the real mapping
            server.connectionMap.remove(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);
        }
    });

    // 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:org.wso2.carbon.transport.http.netty.contractimpl.websocket.message.WebSocketInitMessageImpl.java

License:Open Source License

private HandshakeFuture handleHandshake(WebSocketServerHandshaker handshaker, int idleTimeout) {
    HandshakeFutureImpl handshakeFuture = new HandshakeFutureImpl();

    if (isCancelled) {
        Throwable e = new IllegalAccessException("Handshake is already cancelled!");
        handshakeFuture.notifyError(e);/*from w  ww .  j av a2  s  . c om*/
        return handshakeFuture;
    }

    try {
        ChannelFuture future = handshaker.handshake(ctx.channel(), httpRequest);
        handshakeFuture.setChannelFuture(future);
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                String selectedSubProtocol = handshaker.selectedSubprotocol();
                webSocketSourceHandler.setNegotiatedSubProtocol(selectedSubProtocol);
                setSubProtocol(selectedSubProtocol);
                WebSocketSessionImpl session = (WebSocketSessionImpl) getChannelSession();
                session.setIsOpen(true);
                session.setNegotiatedSubProtocol(selectedSubProtocol);

                //Replace HTTP handlers  with  new Handlers for WebSocket in the pipeline
                ChannelPipeline pipeline = ctx.pipeline();

                if (idleTimeout > 0) {
                    pipeline.replace(Constants.IDLE_STATE_HANDLER, Constants.IDLE_STATE_HANDLER,
                            new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS));
                } else {
                    pipeline.remove(Constants.IDLE_STATE_HANDLER);
                }
                pipeline.addLast(Constants.WEBSOCKET_SOURCE_HANDLER, webSocketSourceHandler);
                pipeline.remove(Constants.HTTP_SOURCE_HANDLER);
                setProperty(Constants.SRC_HANDLER, webSocketSourceHandler);
                handshakeFuture.notifySuccess(webSocketSourceHandler.getChannelSession());
            }
        });
        return handshakeFuture;
    } catch (Exception e) {
        /*
        Code 1002 : indicates that an endpoint is terminating the connection
        due to a protocol error.
         */
        handshaker.close(ctx.channel(),
                new CloseWebSocketFrame(1002, "Terminating the connection due to a protocol error."));
        handshakeFuture.notifyError(e);
        return handshakeFuture;
    }
}

From source file:org.wyb.sows.client.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    if (request.host().equals("127.0.0.1") || request.host().equals("localhost")) {
        System.err.println("Not able to establish bridge. Inform proxy client.");
        ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
        SocksServerUtils.closeOnFlush(ctx.channel());
    }/*from   w w w  . j  a v a 2s .  c o m*/

    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                if (SocksServer.isDebug) {
                    System.out.println("Bridge is established. Inform proxy client.");
                }
                SocksCmdResponse resp = new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType());
                resp.setProtocolVersion(request.protocolVersion());
                ctx.channel().writeAndFlush(resp).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) {
                        ChannelPipeline pipeline = ctx.pipeline();
                        pipeline.remove(SocksServerConnectHandler.this);
                        // ctx.pipeline().addLast(new StringByteCodec());
                        pipeline.addLast(new WebSocketRelayHandler(outboundChannel));
                    }
                });
            } else {
                System.err.println("Not able to establish bridge. Inform proxy client.");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    final Channel inboundChannel = ctx.channel();

    // Add authentication headers
    HttpHeaders authHeader = new DefaultHttpHeaders();
    authHeader.add(SowsAuthHelper.HEADER_SOWS_USER, this.userName);
    byte[] nonce = SowsAuthHelper.randomBytes(16);
    String seed = SowsAuthHelper.base64(nonce);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_SEED, seed);
    byte[] sha1 = SowsAuthHelper.sha1((this.passcode + seed).getBytes(CharsetUtil.US_ASCII));
    String token = SowsAuthHelper.base64(sha1);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_TOKEN, token);

    // initiating websocket client handler
    final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
            .newHandshaker(bridgeServiceUri, WebSocketVersion.V13, null, false, authHeader), promise,
            request.host(), request.port(), inboundChannel);
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                }
            });
    if (SocksServer.isDebug) {
        System.out.println("Try to connect to bridge service.");
    }
    b.connect(bridgeServiceUri.getHost(), bridgeServiceUri.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
                if (SocksServer.isDebug) {
                    System.out.printf("Brige service connection is established. host=%s,port=%d \r\n",
                            bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                }
            } else {
                // Close the connection if the connection attempt has
                // failed.
                System.err.printf("Not able to connect bridge service! host=%s,port=%d \r\n",
                        bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

}

From source file:ratpack.http.client.internal.RequestActionSupport.java

License:Apache License

public void execute(final Fulfiller<? super T> fulfiller) throws Exception {
    final AtomicBoolean redirecting = new AtomicBoolean();

    final Bootstrap b = new Bootstrap();
    b.group(this.execution.getEventLoop()).channel(ChannelImplDetector.getSocketChannelImpl())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*w  ww.  ja  v a2  s . com*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();

                    if (finalUseSsl) {
                        SSLEngine engine = SSLContext.getDefault().createSSLEngine();
                        engine.setUseClientMode(true);
                        p.addLast("ssl", new SslHandler(engine));
                    }

                    p.addLast("codec", new HttpClientCodec());
                    p.addLast("readTimeout",
                            new ReadTimeoutHandler(requestParams.readTimeoutNanos, TimeUnit.NANOSECONDS));

                    p.addLast("redirectHandler", new SimpleChannelInboundHandler<HttpObject>(false) {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
                                throws Exception {
                            if (msg instanceof HttpResponse) {
                                final HttpResponse response = (HttpResponse) msg;
                                final Headers headers = new NettyHeadersBackedHeaders(response.headers());
                                final Status status = new DefaultStatus(response.status());
                                int maxRedirects = requestSpecBacking.getMaxRedirects();
                                String locationValue = headers.get("Location");

                                //Check for redirect and location header if it is follow redirect if we have request forwarding left
                                if (shouldRedirect(status) && maxRedirects > 0 && locationValue != null) {
                                    redirecting.compareAndSet(false, true);

                                    Action<? super RequestSpec> redirectRequestConfig = Action
                                            .join(requestConfigurer, s -> {
                                                if (status.getCode() == 301 || status.getCode() == 302) {
                                                    s.method("GET");
                                                }

                                                s.redirects(maxRedirects - 1);
                                            });

                                    URI locationUrl;
                                    if (ABSOLUTE_PATTERN.matcher(locationValue).matches()) {
                                        locationUrl = new URI(locationValue);
                                    } else {
                                        locationUrl = new URI(uri.getScheme(), null, uri.getHost(),
                                                uri.getPort(), locationValue, null, null);
                                    }

                                    buildRedirectRequestAction(redirectRequestConfig, locationUrl)
                                            .execute(fulfiller);
                                } else {
                                    p.remove(this);
                                }
                            }

                            if (!redirecting.get()) {
                                ctx.fireChannelRead(msg);
                            }
                        }
                    });

                    addResponseHandlers(p, fulfiller);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    ctx.close();
                    error(fulfiller, cause);
                }
            });

    ChannelFuture connectFuture = b.connect(host, port);
    connectFuture.addListener(f1 -> {
        if (connectFuture.isSuccess()) {
            String fullPath = getFullPath(uri);
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(requestSpecBacking.getMethod()), fullPath, requestSpecBacking.getBody());
            if (headers.get(HttpHeaderConstants.HOST) == null) {
                headers.set(HttpHeaderConstants.HOST, host);
            }
            headers.set(HttpHeaderConstants.CONNECTION, HttpHeaderValues.CLOSE);
            int contentLength = request.content().readableBytes();
            if (contentLength > 0) {
                headers.set(HttpHeaderConstants.CONTENT_LENGTH, Integer.toString(contentLength, 10));
            }

            HttpHeaders requestHeaders = request.headers();

            for (String name : headers.getNames()) {
                requestHeaders.set(name, headers.getAll(name));
            }

            ChannelFuture writeFuture = connectFuture.channel().writeAndFlush(request);
            writeFuture.addListener(f2 -> {
                if (!writeFuture.isSuccess()) {
                    writeFuture.channel().close();
                    error(fulfiller, writeFuture.cause());
                }
            });
        } else {
            connectFuture.channel().close();
            error(fulfiller, connectFuture.cause());
        }
    });
}

From source file:reactor.io.net.impl.netty.http.NettyHttpServer.java

License:Open Source License

@Override
protected void onWebsocket(HttpChannel<IN, OUT> next) {
    ChannelPipeline pipeline = ((SocketChannel) next.delegate()).pipeline();
    pipeline.addLast(pipeline.remove(NettyHttpServerHandler.class).withWebsocketSupport(next.uri(), null));

}

From source file:sailfish.remoting.handler.NegotiateChannelHandler.java

License:Apache License

@SuppressWarnings("deprecation")
private void remove(ChannelHandlerContext ctx) {
    try {//from  www  .  j av  a 2  s  . com
        ctx.channel().attr(OneTime.channelConfig).remove();
        ChannelPipeline pipeline = ctx.pipeline();
        if (pipeline.context(this) != null) {
            pipeline.remove(this);
        }
    } finally {
        negotiateMap.remove(ctx);
    }
}

From source file:whitespell.net.websockets.socketio.transport.WebSocketTransport.java

License:Apache License

protected void removeHandler(ChannelPipeline pipeline) {
    pipeline.remove(SocketIOChannelInitializer.FLASH_SOCKET_TRANSPORT);
}