Search in sources :

Example 26 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project netty by netty.

the class SniHandlerTest method testSniWithApnHandler.

@Test
public void testSniWithApnHandler() throws Exception {
    SslContext nettyContext = makeSslContext(provider, true);
    SslContext sniContext = makeSslContext(provider, true);
    final SslContext clientContext = makeSslClientContext(provider, true);
    try {
        final CountDownLatch serverApnDoneLatch = new CountDownLatch(1);
        final CountDownLatch clientApnDoneLatch = new CountDownLatch(1);
        final DomainNameMapping<SslContext> mapping = new DomainNameMappingBuilder<SslContext>(nettyContext).add("*.netty.io", nettyContext).add("sni.fake.site", sniContext).build();
        final SniHandler handler = new SniHandler(mapping);
        EventLoopGroup group = new NioEventLoopGroup(2);
        Channel serverChannel = null;
        Channel clientChannel = null;
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(group);
            sb.channel(NioServerSocketChannel.class);
            sb.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    // Server side SNI.
                    p.addLast(handler);
                    // Catch the notification event that APN has completed successfully.
                    p.addLast(new ApplicationProtocolNegotiationHandler("foo") {

                        @Override
                        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                            serverApnDoneLatch.countDown();
                        }
                    });
                }
            });
            Bootstrap cb = new Bootstrap();
            cb.group(group);
            cb.channel(NioSocketChannel.class);
            cb.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new SslHandler(clientContext.newEngine(ch.alloc(), "sni.fake.site", -1)));
                    // Catch the notification event that APN has completed successfully.
                    ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("foo") {

                        @Override
                        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                            clientApnDoneLatch.countDown();
                        }
                    });
                }
            });
            serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
            ChannelFuture ccf = cb.connect(serverChannel.localAddress());
            assertTrue(ccf.awaitUninterruptibly().isSuccess());
            clientChannel = ccf.channel();
            assertTrue(serverApnDoneLatch.await(5, TimeUnit.SECONDS));
            assertTrue(clientApnDoneLatch.await(5, TimeUnit.SECONDS));
            assertThat(handler.hostname(), is("sni.fake.site"));
            assertThat(handler.sslContext(), is(sniContext));
        } finally {
            if (serverChannel != null) {
                serverChannel.close().sync();
            }
            if (clientChannel != null) {
                clientChannel.close().sync();
            }
            group.shutdownGracefully(0, 0, TimeUnit.MICROSECONDS);
        }
    } finally {
        releaseAll(clientContext, nettyContext, sniContext);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DecoderException(io.netty.handler.codec.DecoderException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 27 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project camel by apache.

the class HttpServerSharedInitializerFactory method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    // create a new pipeline
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = configureServerSSLOnDemand();
    if (sslHandler != null) {
        LOG.debug("Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler);
        pipeline.addLast("ssl", sslHandler);
    }
    pipeline.addLast("decoder", new HttpRequestDecoder(409, configuration.getMaxHeaderSize(), 8192));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    if (configuration.isChunked()) {
        pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
    }
    if (configuration.isCompression()) {
        pipeline.addLast("deflater", new HttpContentCompressor());
    }
    pipeline.addLast("handler", channelFactory.getChannelHandler());
}
Also used : HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpContentCompressor(io.netty.handler.codec.http.HttpContentCompressor) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Example 28 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project java-in-action by xinghalo.

the class ChatServerInitializer method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new HttpObjectAggregator(60 * 1024));
    pipeline.addLast(new HttpRequestHandler("/ws"));
    pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
    pipeline.addLast(new TextWebSocketFrameHandler(group));
}
Also used : HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) WebSocketServerProtocolHandler(io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 29 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project geode by apache.

the class GeodeRedisServer method startRedisServer.

/**
   * Helper method to start the server listening for connections. The server is bound to the port
   * specified by {@link GeodeRedisServer#serverPort}
   * 
   * @throws IOException
   * @throws InterruptedException
   */
private void startRedisServer() throws IOException, InterruptedException {
    ThreadFactory selectorThreadFactory = new ThreadFactory() {

        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GeodeRedisServer-SelectorThread-" + counter.incrementAndGet());
            t.setDaemon(true);
            return t;
        }
    };
    ThreadFactory workerThreadFactory = new ThreadFactory() {

        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GeodeRedisServer-WorkerThread-" + counter.incrementAndGet());
            return t;
        }
    };
    bossGroup = null;
    workerGroup = null;
    Class<? extends ServerChannel> socketClass = null;
    if (singleThreadPerConnection) {
        bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory);
        workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory);
        socketClass = OioServerSocketChannel.class;
    } else {
        bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory);
        workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory);
        socketClass = NioServerSocketChannel.class;
    }
    InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem();
    String pwd = system.getConfig().getRedisPassword();
    final byte[] pwdB = Coder.stringToBytes(pwd);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (logger.fineEnabled())
                logger.fine("GeodeRedisServer-Connection established with " + ch.remoteAddress());
            ChannelPipeline p = ch.pipeline();
            p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder());
            p.addLast(ExecutionHandlerContext.class.getSimpleName(), new ExecutionHandlerContext(ch, cache, regionCache, GeodeRedisServer.this, pwdB));
        }
    }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize()).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GeodeRedisServer.connectTimeoutMillis).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync();
    if (this.logger.infoEnabled()) {
        String logMessage = "GeodeRedisServer started {" + getBindAddress() + ":" + serverPort + "}, Selector threads: " + this.numSelectorThreads;
        if (this.singleThreadPerConnection)
            logMessage += ", One worker thread per connection";
        else
            logMessage += ", Worker threads: " + this.numWorkerThreads;
        this.logger.info(logMessage);
    }
    this.serverChannel = f.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ThreadFactory(java.util.concurrent.ThreadFactory) OioServerSocketChannel(io.netty.channel.socket.oio.OioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) OioEventLoopGroup(io.netty.channel.oio.OioEventLoopGroup) ByteToCommandDecoder(org.apache.geode.redis.internal.ByteToCommandDecoder) InetSocketAddress(java.net.InetSocketAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutionHandlerContext(org.apache.geode.redis.internal.ExecutionHandlerContext) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 30 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project aerospike-client-java by aerospike.

the class NettyCommand method executeCommand.

private void executeCommand() {
    state = AsyncCommand.CONNECT;
    try {
        Node node = command.getNode(cluster);
        conn = (NettyConnection) node.getAsyncConnection(eventState.index, null);
        if (conn != null) {
            InboundHandler handler = (InboundHandler) conn.channel.pipeline().last();
            handler.command = this;
            writeCommand();
            return;
        }
        try {
            final InboundHandler handler = new InboundHandler();
            handler.command = this;
            Bootstrap b = new Bootstrap();
            b.group(eventLoop.eventLoop);
            if (eventLoop.parent.isEpoll) {
                b.channel(EpollSocketChannel.class);
            } else {
                b.channel(NioSocketChannel.class);
            }
            b.option(ChannelOption.TCP_NODELAY, true);
            b.option(ChannelOption.AUTO_READ, false);
            b.handler(new ChannelInitializer<SocketChannel>() {

                @Override
                public void initChannel(SocketChannel ch) {
                    conn = new NettyConnection(ch, cluster.maxSocketIdleNanos);
                    ChannelPipeline p = ch.pipeline();
                    if (eventLoop.parent.sslContext != null) {
                        // InetSocketAddress address = node.getAddress();
                        // p.addLast(eventLoop.parent.sslContext.newHandler(ch.alloc(), address.getHostString(), address.getPort()));
                        p.addLast(eventLoop.parent.sslContext.newHandler(ch.alloc()));
                    }
                    p.addLast(handler);
                }
            });
            b.connect(node.getAddress());
        } catch (Exception e) {
            node.decrAsyncConnection(eventState.index);
            throw e;
        }
        eventState.errors = 0;
    } catch (AerospikeException.Connection ac) {
        eventState.errors++;
        onNetworkError(ac);
    } catch (Exception e) {
        // Fail without retry on unknown errors.
        eventState.errors++;
        fail();
        notifyFailure(new AerospikeException(e));
        tryDelayQueue();
    }
}
Also used : AerospikeException(com.aerospike.client.AerospikeException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Node(com.aerospike.client.cluster.Node) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) AerospikeException(com.aerospike.client.AerospikeException) IOException(java.io.IOException)

Aggregations

ChannelPipeline (io.netty.channel.ChannelPipeline)370 SocketChannel (io.netty.channel.socket.SocketChannel)107 Channel (io.netty.channel.Channel)90 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)90 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)80 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)78 Bootstrap (io.netty.bootstrap.Bootstrap)77 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)69 ChannelFuture (io.netty.channel.ChannelFuture)68 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)62 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)62 EventLoopGroup (io.netty.channel.EventLoopGroup)54 SslHandler (io.netty.handler.ssl.SslHandler)52 InetSocketAddress (java.net.InetSocketAddress)49 HttpServerCodec (io.netty.handler.codec.http.HttpServerCodec)43 LoggingHandler (io.netty.handler.logging.LoggingHandler)37 IOException (java.io.IOException)37 StringDecoder (io.netty.handler.codec.string.StringDecoder)36 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)36 StringEncoder (io.netty.handler.codec.string.StringEncoder)33