Example usage for io.netty.channel ChannelHandlerContext pipeline

List of usage examples for io.netty.channel ChannelHandlerContext pipeline

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext pipeline.

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:io.aos.netty5.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final SocksRequest message) throws Exception {
    if (message instanceof Socks4CmdRequest) {
        final Socks4CmdRequest request = (Socks4CmdRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new GenericFutureListener<Future<Channel>>() {
            @Override//from  w  w w  .  ja va2  s . co m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.SUCCESS))
                            .addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture channelFuture) {
                                    ctx.pipeline().remove(SocksServerConnectHandler.this);
                                    outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                    ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                                }
                            });
                } else {
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CmdRequest) {
        final Socks5CmdRequest request = (Socks5CmdRequest) message;
        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()) {
                    ctx.channel()
                            .writeAndFlush(
                                    new Socks5CmdResponse(Socks5CmdStatus.SUCCESS, request.addressType()))
                            .addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture channelFuture) {
                                    ctx.pipeline().remove(SocksServerConnectHandler.this);
                                    outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                    ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                                }
                            });
                } else {
                    ctx.channel().writeAndFlush(
                            new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:io.aos.netty5.socksproxy.SocksServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception {
    switch (socksRequest.protocolVersion()) {
    case SOCKS4a:
        Socks4CmdRequest socksV4CmdRequest = (Socks4CmdRequest) socksRequest;
        if (socksV4CmdRequest.cmdType() == Socks4CmdType.CONNECT) {
            ctx.pipeline().addLast(new SocksServerConnectHandler());
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(socksRequest);
        } else {/*ww w.  j a v  a2  s. c o m*/
            ctx.close();
        }
        break;
    case SOCKS5:
        switch (((Socks5Request) socksRequest).requestType()) {
        case INIT: {
            // auth support example
            //ctx.pipeline().addFirst(new SocksV5AuthRequestDecoder());
            //ctx.write(new SocksV5InitResponse(SocksV5AuthScheme.AUTH_PASSWORD));
            ctx.pipeline().addFirst(new Socks5CmdRequestDecoder());
            ctx.write(new Socks5InitResponse(Socks5AuthScheme.NO_AUTH));
            break;
        }
        case AUTH:
            ctx.pipeline().addFirst(new Socks5CmdRequestDecoder());
            ctx.write(new Socks5AuthResponse(Socks5AuthStatus.SUCCESS));
            break;
        case CMD:
            Socks5CmdRequest socks5CmdRequest = (Socks5CmdRequest) socksRequest;
            if (socks5CmdRequest.cmdType() == Socks5CmdType.CONNECT) {
                ctx.pipeline().addLast(new SocksServerConnectHandler());
                ctx.pipeline().remove(this);
                ctx.fireChannelRead(socksRequest);
            } else {
                ctx.close();
            }
            break;
        case UNKNOWN:
            ctx.close();
            break;
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}

From source file:io.blobkeeper.server.handler.FileDeleteHandler.java

License:Apache License

private void addWriterBack(ChannelHandlerContext ctx) {
    ctx.pipeline().remove("aggregator");
    ctx.pipeline().addBefore("reader", "writer", fileWriterHandlerProvider.get());
}

From source file:io.blobkeeper.server.handler.FileWriterHandler.java

License:Apache License

private void jumpToDeleter(ChannelHandlerContext context, HttpObject object) {
    context.pipeline().addBefore("deleter", "aggregator", new HttpObjectAggregator(65536));
    context.pipeline().remove(FileWriterHandler.class);
    context.fireChannelRead(object);// w w w .j  a va  2s . c o  m
}

From source file:io.blobkeeper.server.handler.FileWriterHandler.java

License:Apache License

private void jumpToReader(ChannelHandlerContext context, HttpObject object) {
    context.pipeline().addBefore("reader", "aggregator", new HttpObjectAggregator(65536));
    context.pipeline().remove(this);
    context.fireChannelRead(object);//  ww  w  .jav a 2  s. c  o  m
}

From source file:io.bsoa.rpc.grpc.client12.Http2SettingsHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Settings msg) throws Exception {
    promise.setSuccess();/*  w  w  w . j a  v  a  2s .c  om*/

    // Only care about the first settings message
    ctx.pipeline().remove(this);

    System.out.println("=======3======>" + ctx.pipeline().names() + "<=========" + ctx.pipeline().toMap());
}

From source file:io.bsoa.rpc.grpc.client12.HttpResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    System.out.println("=======4======>" + ctx.pipeline().names() + "<=========" + ctx.pipeline().toMap());
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;/*  ww w . j  a  v  a  2 s. co m*/
    }

    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    if (entry == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        entry.getValue().setSuccess();
    }
}

From source file:io.cettia.asity.bridge.netty4.AsityServerCodec.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        if (!accept(req)) {
            ctx.fireChannelRead(msg);/*from  w ww  . j  av a  2s .c  o  m*/
            return;
        }
        if (req.getMethod() == HttpMethod.GET
                && req.headers().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true)) {
            // Because WebSocketServerHandshaker requires FullHttpRequest
            FullHttpRequest wsRequest = new DefaultFullHttpRequest(req.getProtocolVersion(), req.getMethod(),
                    req.getUri());
            wsRequest.headers().set(req.headers());
            wsReqMap.put(ctx.channel(), wsRequest);
            // Set timeout to avoid memory leak
            ctx.pipeline().addFirst(new ReadTimeoutHandler(5));
        } else {
            NettyServerHttpExchange http = new NettyServerHttpExchange(ctx, req);
            httpMap.put(ctx.channel(), http);
            httpActions.fire(http);
        }
    } else if (msg instanceof HttpContent) {
        FullHttpRequest wsReq = wsReqMap.get(ctx.channel());
        if (wsReq != null) {
            wsReq.content().writeBytes(((HttpContent) msg).content());
            if (msg instanceof LastHttpContent) {
                wsReqMap.remove(ctx.channel());
                // Cancel timeout
                ctx.pipeline().remove(ReadTimeoutHandler.class);
                WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(
                        getWebSocketLocation(ctx.pipeline(), wsReq), null, true);
                WebSocketServerHandshaker handshaker = factory.newHandshaker(wsReq);
                if (handshaker == null) {
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                } else {
                    handshaker.handshake(ctx.channel(), wsReq);
                    NettyServerWebSocket ws = new NettyServerWebSocket(ctx, wsReq, handshaker);
                    wsMap.put(ctx.channel(), ws);
                    wsActions.fire(ws);
                }
            }
        } else {
            NettyServerHttpExchange http = httpMap.get(ctx.channel());
            if (http != null) {
                http.handleChunk((HttpContent) msg);
            }
        }
    } else if (msg instanceof WebSocketFrame) {
        NettyServerWebSocket ws = wsMap.get(ctx.channel());
        if (ws != null) {
            ws.handleFrame((WebSocketFrame) msg);
        }
    }
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    this.ctx = ctx;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        this.sslEnabled = false;
        this.activeScheme = SCHEME_HTTP;
    } else {// ww w. j a  v a  2s . c o m
        this.sslEnabled = true;
        this.activeScheme = SCHEME_HTTPS;
    }
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private Future<Channel> installHttp2Handler(HttpTx tx, Channel channel, ChannelPool channelPool) {

    Promise<Channel> whenAlpn = channel.eventLoop().newPromise();

    channel.pipeline().addAfter(SSL_HANDLER, ALPN_HANDLER,
            new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
                @Override/*from   w ww.ja  v  a  2  s .c om*/
                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {

                    switch (protocol) {
                    case ApplicationProtocolNames.HTTP_2:
                        LOGGER.debug("ALPN led to HTTP/2 with remote {}", tx.request.getUri().getHost());
                        tx.listener.onProtocolAwareness(true);
                        Http2Connection connection = new DefaultHttp2Connection(false);

                        HttpToHttp2ConnectionHandler http2Handler = new HttpToHttp2ConnectionHandlerBuilder()
                                .initialSettings(Http2Settings.defaultSettings()) // FIXME override?
                                .connection(connection)
                                .frameListener(new DelegatingDecompressorFrameListener(connection,
                                        new ChunkedInboundHttp2ToHttpAdapter(connection, false, true,
                                                whenAlpn)))
                                .build();

                        ctx.pipeline().addLast(HTTP2_HANDLER, http2Handler).addLast(APP_HTTP2_HANDLER,
                                new Http2AppHandler(connection, http2Handler, channelPool, config));

                        channelPool.offer(channel);

                        SslHandler sslHandler = (SslHandler) ctx.pipeline().get(SSL_HANDLER);
                        Set<String> subjectAlternativeNames = Tls
                                .extractSubjectAlternativeNames(sslHandler.engine());
                        if (!subjectAlternativeNames.isEmpty()) {
                            channelPool.addCoalescedChannel(subjectAlternativeNames,
                                    (InetSocketAddress) channel.remoteAddress(), channel, tx.key);
                        }
                        break;

                    case ApplicationProtocolNames.HTTP_1_1:
                        LOGGER.debug("ALPN led to HTTP/1 with remote {}", tx.request.getUri().getHost());
                        if (tx.request.isHttp2PriorKnowledge()) {
                            IllegalStateException e = new IllegalStateException(
                                    "HTTP/2 Prior knowledge was set on host " + tx.request.getUri().getHost()
                                            + " but it only supports HTTP/1");
                            whenAlpn.setFailure(e);
                            throw e;
                        }
                        tx.listener.onProtocolAwareness(false);
                        ctx.pipeline()
                                .addBefore(CHUNKED_WRITER_HANDLER, HTTP_CLIENT_CODEC, newHttpClientCodec())
                                .addBefore(CHUNKED_WRITER_HANDLER, INFLATER_HANDLER,
                                        newHttpContentDecompressor())
                                .addAfter(CHUNKED_WRITER_HANDLER, APP_HTTP_HANDLER,
                                        new HttpAppHandler(DefaultHttpClient.this, channelPool, config));
                        whenAlpn.setSuccess(ctx.channel());
                        break;

                    default:
                        IllegalStateException e = new IllegalStateException("Unknown protocol: " + protocol);
                        whenAlpn.setFailure(e);
                        ctx.close();
                        // FIXME do we really need to throw?
                        throw e;
                    }
                }
            });

    whenAlpn.addListener(f -> {
        if (!f.isSuccess()) {
            tx.listener.onThrowable(f.cause());
        }
    });

    return whenAlpn;
}