Example usage for io.netty.channel ChannelPipeline addFirst

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

Introduction

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

Prototype

ChannelPipeline addFirst(ChannelHandler... handlers);

Source Link

Document

Inserts ChannelHandler s at the first position of this pipeline.

Usage

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

License:Apache License

void finishSuccessfully(ChannelPipeline pipeline, SessionProtocol protocol) {

    if (protocol == H1 || protocol == H1C) {
        addBeforeSessionHandler(pipeline, new Http1ResponseDecoder(pipeline.channel()));
    }//  w ww.ja v a  2 s.  c o m

    final long idleTimeoutMillis = options.idleTimeoutMillis();
    if (idleTimeoutMillis > 0) {
        pipeline.addFirst(new HttpClientIdleTimeoutHandler(idleTimeoutMillis));
    }

    pipeline.channel().eventLoop().execute(() -> pipeline.fireUserEventTriggered(protocol));
}

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

License:Apache License

void finishSuccessfully(ChannelPipeline pipeline, SessionProtocol protocol) {

    if (protocol == H1 || protocol == H1C) {
        addBeforeSessionHandler(pipeline, new Http1ResponseDecoder(pipeline.channel()));
    } else if (protocol == H2 || protocol == H2C) {
        final int initialWindow = clientFactory.initialHttp2ConnectionWindowSize();
        if (initialWindow > DEFAULT_WINDOW_SIZE) {
            incrementLocalWindowSize(pipeline, initialWindow - DEFAULT_WINDOW_SIZE);
        }/*from w  ww.  j av a 2  s .  c  o m*/
    }

    final long idleTimeoutMillis = clientFactory.idleTimeoutMillis();
    if (idleTimeoutMillis > 0) {
        pipeline.addFirst(new HttpClientIdleTimeoutHandler(idleTimeoutMillis));
    }

    pipeline.channel().eventLoop().execute(() -> pipeline.fireUserEventTriggered(protocol));
}

From source file:com.linecorp.armeria.server.http.HttpServerPipelineConfigurator.java

License:Apache License

private void configureRequestCountingHandlers(ChannelPipeline p) {
    if (config.idleTimeoutMillis() > 0) {
        p.addFirst(new HttpServerIdleTimeoutHandler(config.idleTimeoutMillis()));
    }//from   w w w. ja va  2s  . co  m
    gracefulShutdownHandler.ifPresent(h -> {
        h.reset();
        p.addLast(h);
    });
}

From source file:com.linecorp.armeria.server.HttpServerPipelineConfigurator.java

License:Apache License

private void configureIdleTimeoutHandler(ChannelPipeline p) {
    if (config.idleTimeoutMillis() > 0) {
        p.addFirst(new HttpServerIdleTimeoutHandler(config.idleTimeoutMillis()));
    }//from  w w w  . jav  a2 s  .  co  m
}

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

protected ApnsClient(final SslContext sslContext, final EventLoopGroup eventLoopGroup) {
    this.bootstrap = new Bootstrap();

    if (eventLoopGroup != null) {
        this.bootstrap.group(eventLoopGroup);
        this.shouldShutDownEventLoopGroup = false;
    } else {/*from  w  ww.j ava2  s .c  om*/
        this.bootstrap.group(new NioEventLoopGroup(1));
        this.shouldShutDownEventLoopGroup = true;
    }

    this.bootstrap.channel(SocketChannelClassUtil.getSocketChannelClass(this.bootstrap.config().group()));
    this.bootstrap.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            final ProxyHandlerFactory proxyHandlerFactory = ApnsClient.this.proxyHandlerFactory;

            if (proxyHandlerFactory != null) {
                pipeline.addFirst(proxyHandlerFactory.createProxyHandler());
            }

            if (ApnsClient.this.writeTimeoutMillis > 0) {
                pipeline.addLast(
                        new WriteTimeoutHandler(ApnsClient.this.writeTimeoutMillis, TimeUnit.MILLISECONDS));
            }

            pipeline.addLast(sslContext.newHandler(channel.alloc()));
            pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
                @Override
                protected void configurePipeline(final ChannelHandlerContext context, final String protocol) {
                    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                        final ApnsClientHandler apnsClientHandler = new ApnsClientHandler.ApnsClientHandlerBuilder()
                                .server(false).apnsClient(ApnsClient.this)
                                .authority(
                                        ((InetSocketAddress) context.channel().remoteAddress()).getHostName())
                                .encoderEnforceMaxConcurrentStreams(true).build();

                        synchronized (ApnsClient.this.bootstrap) {
                            if (ApnsClient.this.gracefulShutdownTimeoutMillis != null) {
                                apnsClientHandler.gracefulShutdownTimeoutMillis(
                                        ApnsClient.this.gracefulShutdownTimeoutMillis);
                            }
                        }

                        context.pipeline().addLast(
                                new IdleStateHandler(0, 0, PING_IDLE_TIME_MILLIS, TimeUnit.MILLISECONDS));
                        context.pipeline().addLast(apnsClientHandler);

                        final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise;

                        if (connectionReadyPromise != null) {
                            connectionReadyPromise.trySuccess();
                        }
                    } else {
                        throw new IllegalArgumentException("Unexpected protocol: " + protocol);
                    }
                }
            });
        }
    });
}

From source file:com.turo.pushy.apns.ApnsChannelFactory.java

License:Open Source License

ApnsChannelFactory(final SslContext sslContext, final ApnsSigningKey signingKey,
        final ProxyHandlerFactory proxyHandlerFactory, final int connectTimeoutMillis,
        final long idlePingIntervalMillis, final long gracefulShutdownTimeoutMillis,
        final Http2FrameLogger frameLogger, final InetSocketAddress apnsServerAddress,
        final EventLoopGroup eventLoopGroup) {

    this.sslContext = sslContext;

    if (this.sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) this.sslContext).retain();
    }/*from  w  w w. j a va 2s .  c  o m*/

    this.addressResolverGroup = proxyHandlerFactory == null
            ? new RoundRobinDnsAddressResolverGroup(
                    ClientChannelClassUtil.getDatagramChannelClass(eventLoopGroup),
                    DefaultDnsServerAddressStreamProvider.INSTANCE)
            : NoopAddressResolverGroup.INSTANCE;

    this.bootstrapTemplate = new Bootstrap();
    this.bootstrapTemplate.group(eventLoopGroup);
    this.bootstrapTemplate.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrapTemplate.remoteAddress(apnsServerAddress);
    this.bootstrapTemplate.resolver(this.addressResolverGroup);

    if (connectTimeoutMillis > 0) {
        this.bootstrapTemplate.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }

    this.bootstrapTemplate.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final ChannelPipeline pipeline = channel.pipeline();

            if (proxyHandlerFactory != null) {
                pipeline.addFirst(proxyHandlerFactory.createProxyHandler());
            }

            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());

            sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(final Future<Channel> handshakeFuture) {
                    if (handshakeFuture.isSuccess()) {
                        final String authority = channel.remoteAddress().getHostName();

                        final ApnsClientHandler.ApnsClientHandlerBuilder clientHandlerBuilder;

                        if (signingKey != null) {
                            clientHandlerBuilder = new TokenAuthenticationApnsClientHandler.TokenAuthenticationApnsClientHandlerBuilder()
                                    .signingKey(signingKey).authority(authority)
                                    .idlePingIntervalMillis(idlePingIntervalMillis);
                        } else {
                            clientHandlerBuilder = new ApnsClientHandler.ApnsClientHandlerBuilder()
                                    .authority(authority).idlePingIntervalMillis(idlePingIntervalMillis);
                        }

                        if (frameLogger != null) {
                            clientHandlerBuilder.frameLogger(frameLogger);
                        }

                        final ApnsClientHandler apnsClientHandler = clientHandlerBuilder.build();

                        if (gracefulShutdownTimeoutMillis > 0) {
                            apnsClientHandler.gracefulShutdownTimeoutMillis(gracefulShutdownTimeoutMillis);
                        }

                        // TODO Use a named constant when https://github.com/netty/netty/pull/8683 is available
                        pipeline.addLast(new FlushConsolidationHandler(256, true));
                        pipeline.addLast(
                                new IdleStateHandler(idlePingIntervalMillis, 0, 0, TimeUnit.MILLISECONDS));
                        pipeline.addLast(apnsClientHandler);
                        pipeline.remove(ConnectionNegotiationErrorHandler.INSTANCE);

                        channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get().trySuccess(channel);
                    } else {
                        tryFailureAndLogRejectedCause(channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get(),
                                handshakeFuture.cause());
                    }
                }
            });

            pipeline.addLast(sslHandler);
            pipeline.addLast(ConnectionNegotiationErrorHandler.INSTANCE);
        }
    });
}

From source file:de.jackwhite20.comix.handler.ComixChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();
    InetSocketAddress remoteAddress = ch.remoteAddress();

    // Simple IP-Blacklist
    if (comix.isIpBanned(remoteAddress.getAddress().getHostAddress())) {
        ch.close();/*from  w  w w .ja  v  a2  s .co  m*/
        return;
    }

    // Simple IP-Range-Blacklist
    if (comix.isIpRangeBanned(remoteAddress)) {
        ch.close();
        return;
    }

    HandshakeHandler handshakeHandler = new HandshakeHandler();
    p.addFirst(handshakeHandler);

    UpstreamHandler upstreamHandler = new UpstreamHandler(Comix.getInstance().getBalancingStrategy());
    p.addLast(upstreamHandler);

    handshakeHandler.setUpstreamHandler(upstreamHandler);

    Comix.getLogger().log(Level.INFO, "Comix",
            "[" + ch.remoteAddress().getAddress().getHostAddress() + "] -> InitialHandler has connected");
}

From source file:io.airlift.drift.transport.netty.ThriftClientInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel channel) {
    ChannelPipeline pipeline = channel.pipeline();

    messageFraming.addFrameHandlers(pipeline);

    pipeline.addLast(new ThriftClientHandler(requestTimeout, messageEncoding));

    sslContext.ifPresent(sslContext -> pipeline.addFirst(sslContext.newHandler(channel.alloc())));

    socksProxyAddress.ifPresent(socks -> pipeline
            .addFirst(new Socks4ProxyHandler(new InetSocketAddress(socks.getHost(), socks.getPort()))));
}

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

License:Apache License

@Override
public void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline p = socketChannel.pipeline();
    p.addFirst(new LoggingHandler(LogLevel.DEBUG));
    p.addLast(new SocksPortUnificationServerHandler());
}

From source file:io.atomix.catalyst.transport.netty.NettyClient.java

License:Apache License

@Override
public CompletableFuture<Connection> connect(Address address) {
    Assert.notNull(address, "address");
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<Connection> future = new ComposableFuture<>();

    LOGGER.info("Connecting to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   ww  w .  jav  a  2s  .co  m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (transport.properties().sslEnabled()) {
                        pipeline.addFirst(
                                new SslHandler(new NettyTls(transport.properties()).initSslEngine(true)));
                    }
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0,
                            4, 0, 4));
                    pipeline.addLast(
                            new NettyHandler(connections, future::complete, context, transport.properties()));
                }
            });

    bootstrap.option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transport.properties().connectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR);

    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    bootstrap.connect(address.socketAddress()).addListener(channelFuture -> {
        if (channelFuture.isSuccess()) {
            LOGGER.info("Connected to {}", address);
        } else {
            context.execute(() -> future.completeExceptionally(channelFuture.cause()));
        }
    });
    return future;
}