Example usage for io.netty.channel ChannelPipeline addLast

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

Introduction

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

Prototype

ChannelPipeline addLast(ChannelHandler... handlers);

Source Link

Document

Inserts ChannelHandler s at the last position of this pipeline.

Usage

From source file:com.lambdaworks.redis.server.RandomResponseServer.java

License:Apache License

public void initialize(int port) throws InterruptedException {

    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//  www  .j  av  a  2  s . c  om
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    // p.addLast(new LoggingHandler(LogLevel.INFO));
                    p.addLast(new RandomServerHandler());
                }
            });

    // Start the server.
    ChannelFuture f = b.bind(port).sync();

    channel = f.channel();
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerInitializer.java

License:Open Source License

@Override
public void initChannel(SocketChannel socketChannel) {
    ChannelPipeline channelPipeline = socketChannel.pipeline();

    if (_domainNameMapping != null) {
        channelPipeline.addLast(new SniHandler(_domainNameMapping));
    }/*from  w ww  .  j  a v a 2  s . c  om*/

    channelPipeline.addLast(new HttpServerCodec());
    channelPipeline.addLast(new HttpObjectAggregator(65536));
    channelPipeline.addLast(_syncTrafficShapingHandler);
    channelPipeline.addLast(new ChunkedWriteHandler());
    channelPipeline.addLast(new LanFileServerHandler(_syncTrafficShapingHandler));
}

From source file:com.lin.studytest.netty.server.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w w w .j av a2  s. c o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                //             .option(ChannelOption.SO_BACKLOG, 100)
                //             .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.linecorp.armeria.client.endpoint.dns.TestDnsServer.java

License:Apache License

TestDnsServer(Map<DnsQuestion, DnsResponse> responses) {
    this.responses = ImmutableMap.copyOf(responses);

    final Bootstrap b = new Bootstrap();
    b.channel(TransportType.datagramChannelType(CommonPools.workerGroup()));
    b.group(CommonPools.workerGroup());//from   w w w.j  a va 2  s . c o m
    b.handler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            final ChannelPipeline p = ch.pipeline();
            p.addLast(new DatagramDnsQueryDecoder());
            p.addLast(new DatagramDnsResponseEncoder());
            p.addLast(new DnsServerHandler());
        }
    });

    channel = b.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
}

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {

    // Remember the requested remote address for later use.
    this.remoteAddress = (InetSocketAddress) remoteAddress;

    // Configure the pipeline.
    final Channel ch = ctx.channel();

    final ChannelPipeline p = ch.pipeline();
    p.addLast(new FlushConsolidationHandler());
    p.addLast(ReadSuppressingHandler.INSTANCE);

    try {/*  ww  w.  j a  va  2s.  c  om*/
        if (sslCtx != null) {
            configureAsHttps(ch);
        } else {
            configureAsHttp(ch);
        }
    } catch (Throwable t) {
        promise.tryFailure(t);
        ctx.close();
    } finally {
        if (p.context(this) != null) {
            p.remove(this);
        }
    }

    ctx.connect(remoteAddress, localAddress, promise);
}

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

/**
 * @see <a href="https://http2.github.io/http2-spec/#discover-https">HTTP/2 specification</a>
 *///  w  w  w .jav  a 2  s .  c o  m
private void configureAsHttps(Channel ch) {
    final ChannelPipeline p = ch.pipeline();
    final SslHandler sslHandler = sslCtx.newHandler(ch.alloc());
    p.addLast(sslHandler);
    p.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!(evt instanceof SslHandshakeCompletionEvent)) {
                ctx.fireUserEventTriggered(evt);
                return;
            }

            final SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
            if (!handshakeEvent.isSuccess()) {
                // The connection will be closed automatically by SslHandler.
                return;
            }

            final SessionProtocol protocol;
            if (isHttp2Protocol(sslHandler)) {
                if (httpPreference == HttpPreference.HTTP1_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H1, H2, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(p, newHttp2ConnectionHandler(ch));
                protocol = H2;
            } else {
                if (httpPreference != HttpPreference.HTTP1_REQUIRED) {
                    SessionProtocolNegotiationCache.setUnsupported(ctx.channel().remoteAddress(), H2);
                }

                if (httpPreference == HttpPreference.HTTP2_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H2, H1, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(p, newHttp1Codec());
                protocol = H1;
            }
            finishSuccessfully(p, protocol);
            p.remove(this);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            Exceptions.logIfUnexpected(logger, ctx.channel(), cause);
            ctx.close();
        }
    });
}

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

private void configureAsHttp(Channel ch) {
    final ChannelPipeline pipeline = ch.pipeline();

    final boolean attemptUpgrade;
    switch (httpPreference) {
    case HTTP1_REQUIRED:
        attemptUpgrade = false;/*  w w  w. jav  a2s  .  c  o  m*/
        break;
    case HTTP2_PREFERRED:
        attemptUpgrade = !SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C);
        break;
    case HTTP2_REQUIRED:
        attemptUpgrade = true;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    if (attemptUpgrade) {
        final Http2ClientConnectionHandler http2Handler = newHttp2ConnectionHandler(ch);
        if (options.useHttp2Preface()) {
            pipeline.addLast(new DowngradeHandler());
            pipeline.addLast(http2Handler);
        } else {
            Http1ClientCodec http1Codec = newHttp1Codec();
            Http2ClientUpgradeCodec http2ClientUpgradeCodec = new Http2ClientUpgradeCodec(http2Handler);
            HttpClientUpgradeHandler http2UpgradeHandler = new HttpClientUpgradeHandler(http1Codec,
                    http2ClientUpgradeCodec, (int) Math.min(Integer.MAX_VALUE, UPGRADE_RESPONSE_MAX_LENGTH));

            pipeline.addLast(http1Codec);
            pipeline.addLast(new WorkaroundHandler());
            pipeline.addLast(http2UpgradeHandler);
            pipeline.addLast(new UpgradeRequestHandler(http2Handler.responseDecoder()));
        }
    } else {
        pipeline.addLast(newHttp1Codec());

        // NB: We do not call finishSuccessfully() immediately here
        //     because it assumes HttpSessionHandler to be in the pipeline,
        //     which is only true after the connection attempt is successful.
        pipeline.addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.pipeline().remove(this);
                finishSuccessfully(pipeline, H1C);
                ctx.fireChannelActive();
            }
        });
    }
}

From source file:com.linecorp.armeria.client.HttpClientPipelineConfigurator.java

License:Apache License

@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {

    // Remember the requested remote address for later use.
    final InetSocketAddress inetRemoteAddr = (InetSocketAddress) remoteAddress;
    this.remoteAddress = inetRemoteAddr;

    // Configure the pipeline.
    final Channel ch = ctx.channel();

    final ChannelPipeline p = ch.pipeline();
    p.addLast(new FlushConsolidationHandler());
    p.addLast(ReadSuppressingHandler.INSTANCE);

    try {//from w w  w .j a v a  2 s . c  o m
        if (sslCtx != null) {
            configureAsHttps(ch, inetRemoteAddr);
        } else {
            configureAsHttp(ch);
        }
    } catch (Throwable t) {
        promise.tryFailure(t);
        ctx.close();
    } finally {
        if (p.context(this) != null) {
            p.remove(this);
        }
    }

    ctx.connect(remoteAddress, localAddress, promise);
}

From source file:com.linecorp.armeria.client.HttpClientPipelineConfigurator.java

License:Apache License

/**
 * See <a href="https://http2.github.io/http2-spec/#discover-https">HTTP/2 specification</a>.
 *//*  w  w  w.j a  v  a 2 s.  co  m*/
private void configureAsHttps(Channel ch, InetSocketAddress remoteAddr) {
    assert sslCtx != null;

    final ChannelPipeline p = ch.pipeline();
    final SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), remoteAddr.getHostString(),
            remoteAddr.getPort());
    p.addLast(sslHandler);
    p.addLast(TrafficLoggingHandler.CLIENT);
    p.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!(evt instanceof SslHandshakeCompletionEvent)) {
                ctx.fireUserEventTriggered(evt);
                return;
            }

            final SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
            if (!handshakeEvent.isSuccess()) {
                // The connection will be closed automatically by SslHandler.
                return;
            }

            final SessionProtocol protocol;
            if (isHttp2Protocol(sslHandler)) {
                if (httpPreference == HttpPreference.HTTP1_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H1, H2, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(p, newHttp2ConnectionHandler(ch));
                protocol = H2;
            } else {
                if (httpPreference != HttpPreference.HTTP1_REQUIRED) {
                    SessionProtocolNegotiationCache.setUnsupported(ctx.channel().remoteAddress(), H2);
                }

                if (httpPreference == HttpPreference.HTTP2_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H2, H1, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(p, newHttp1Codec(clientFactory.maxHttp1InitialLineLength(),
                        clientFactory.maxHttp1HeaderSize(), clientFactory.maxHttp1ChunkSize()));
                protocol = H1;
            }
            finishSuccessfully(p, protocol);
            p.remove(this);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            Exceptions.logIfUnexpected(logger, ctx.channel(), cause);
            ctx.close();
        }
    });
}

From source file:com.linecorp.armeria.client.HttpClientPipelineConfigurator.java

License:Apache License

private void configureAsHttp(Channel ch) {
    final ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(TrafficLoggingHandler.CLIENT);

    final boolean attemptUpgrade;
    switch (httpPreference) {
    case HTTP1_REQUIRED:
        attemptUpgrade = false;/*w  w w.ja v  a 2s.c  om*/
        break;
    case HTTP2_PREFERRED:
        assert remoteAddress != null;
        attemptUpgrade = !SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C);
        break;
    case HTTP2_REQUIRED:
        attemptUpgrade = true;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    if (attemptUpgrade) {
        final Http2ClientConnectionHandler http2Handler = newHttp2ConnectionHandler(ch);
        if (clientFactory.useHttp2Preface()) {
            pipeline.addLast(new DowngradeHandler());
            pipeline.addLast(http2Handler);
        } else {
            final Http1ClientCodec http1Codec = newHttp1Codec(clientFactory.maxHttp1InitialLineLength(),
                    clientFactory.maxHttp1HeaderSize(), clientFactory.maxHttp1ChunkSize());
            final Http2ClientUpgradeCodec http2ClientUpgradeCodec = new Http2ClientUpgradeCodec(http2Handler);
            final HttpClientUpgradeHandler http2UpgradeHandler = new HttpClientUpgradeHandler(http1Codec,
                    http2ClientUpgradeCodec, (int) Math.min(Integer.MAX_VALUE, UPGRADE_RESPONSE_MAX_LENGTH));

            pipeline.addLast(http1Codec);
            pipeline.addLast(new WorkaroundHandler());
            pipeline.addLast(http2UpgradeHandler);
            pipeline.addLast(new UpgradeRequestHandler(http2Handler.responseDecoder()));
        }
    } else {
        pipeline.addLast(newHttp1Codec(clientFactory.maxHttp1InitialLineLength(),
                clientFactory.maxHttp1HeaderSize(), clientFactory.maxHttp1ChunkSize()));

        // NB: We do not call finishSuccessfully() immediately here
        //     because it assumes HttpSessionHandler to be in the pipeline,
        //     which is only true after the connection attempt is successful.
        pipeline.addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.pipeline().remove(this);
                finishSuccessfully(pipeline, H1C);
                ctx.fireChannelActive();
            }
        });
    }
}