Search in sources :

Example 21 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project cdap by caskdata.

the class NettyRouterPipelineTest method testHttpPipelining.

@Test
public void testHttpPipelining() throws Exception {
    final BlockingQueue<HttpResponseStatus> responseStatuses = new LinkedBlockingQueue<>();
    EventLoopGroup eventGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventGroup).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
            pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof HttpResponse) {
                        responseStatuses.add(((HttpResponse) msg).status());
                    }
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    // Create a connection and make five consecutive HTTP call without waiting for the first to respond
    Channel channel = bootstrap.connect(HOSTNAME, ROUTER.getServiceMap().get(GATEWAY_NAME)).sync().channel();
    for (int i = 0; i < 5; i++) {
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v1/sleep?sleepMillis=3000");
        request.headers().set(HttpHeaderNames.HOST, HOSTNAME);
        channel.writeAndFlush(request);
    }
    // Should get the first response as normal one
    HttpResponseStatus status = responseStatuses.poll(5, TimeUnit.SECONDS);
    Assert.assertEquals(HttpResponseStatus.OK, status);
    // The rest four should be failure responses
    for (int i = 0; i < 4; i++) {
        Assert.assertEquals(HttpResponseStatus.NOT_IMPLEMENTED, responseStatuses.poll(1, TimeUnit.SECONDS));
    }
    eventGroup.shutdownGracefully();
    channel.close();
    Assert.assertTrue(responseStatuses.isEmpty());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 22 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project bgpcep by opendaylight.

the class PCCDispatcherImpl method createClient.

@Override
@SuppressWarnings("unchecked")
public Future<PCEPSession> createClient(final InetSocketAddress remoteAddress, final long reconnectTime, final PCEPSessionListenerFactory listenerFactory, final PCEPSessionNegotiatorFactory negotiatorFactory, final KeyMapping keys, final InetSocketAddress localAddress, final BigInteger dbVersion) {
    final Bootstrap b = new Bootstrap();
    b.group(this.workerGroup);
    b.localAddress(localAddress);
    setChannelFactory(b, keys);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.RCVBUF_ALLOCATOR, new io.netty.channel.FixedRecvByteBufAllocator(1));
    final long retryTimer = reconnectTime == -1 ? 0 : reconnectTime;
    final PCCReconnectPromise promise = new PCCReconnectPromise(remoteAddress, (int) retryTimer, CONNECT_TIMEOUT, b);
    final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel ch) {
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
            ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(new PCEPSessionNegotiatorFactoryDependencies() {

                @Override
                public PCEPSessionListenerFactory getListenerFactory() {
                    return listenerFactory;
                }

                @Override
                public PCEPPeerProposal getPeerProposal() {
                    return new PCCPeerProposal(dbVersion);
                }
            }, ch, promise));
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelInactive(final ChannelHandlerContext ctx) {
                    if (promise.isCancelled()) {
                        return;
                    }
                    if (!promise.isInitialConnectFinished()) {
                        LOG.debug("Connection to {} was dropped during negotiation, reattempting", remoteAddress);
                        return;
                    }
                    LOG.debug("Reconnecting after connection to {} was dropped", remoteAddress);
                    PCCDispatcherImpl.this.createClient(remoteAddress, reconnectTime, listenerFactory, negotiatorFactory, keys, localAddress, dbVersion);
                }
            });
        }
    };
    b.handler(channelInitializer);
    promise.connect();
    return promise;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) PCEPSessionNegotiatorFactoryDependencies(org.opendaylight.protocol.pcep.PCEPSessionNegotiatorFactoryDependencies) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 23 with ChannelInboundHandlerAdapter

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

the class NettyStreamChannelInitializer method initChannel.

@Override
protected void initChannel(Channel channel) {
    ChannelPipeline pipeline = channel.pipeline();
    // contexs contexts contexs
    channel.pipeline().addLast(channelContextHandler);
    // frame codecs
    pipeline.addLast(new LengthFieldPrepender(LENGTH_FIELD_LENGTH));
    pipeline.addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, 0, LENGTH_FIELD_LENGTH, 0, LENGTH_FIELD_LENGTH));
    // message acceptor
    pipeline.addLast(messageHandler);
    // at-least-something exception handler
    pipeline.addLast(new ChannelInboundHandlerAdapter() {

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
            // Hint: at this point one can look at throwable, make some exception translation, and via channelContext post
            // ChannelContextError event, and hence give business layer ability to react on low level system error events
            LOGGER.warn("Exception caught for channel {}, {}", ctx.channel(), throwable);
        }
    });
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 24 with ChannelInboundHandlerAdapter

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

the class RedisChannelInitializer method initSsl.

private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException {
    if (!config.getAddress().isSsl()) {
        return;
    }
    io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK;
    if (config.getSslProvider() == SslProvider.OPENSSL) {
        provided = io.netty.handler.ssl.SslProvider.OPENSSL;
    }
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided);
    sslContextBuilder.protocols(config.getSslProtocols());
    if (config.getSslTruststore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream stream = config.getSslTruststore().openStream();
        try {
            char[] password = null;
            if (config.getSslTruststorePassword() != null) {
                password = config.getSslTruststorePassword().toCharArray();
            }
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContextBuilder.trustManager(trustManagerFactory);
    }
    if (config.getSslKeystore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream stream = config.getSslKeystore().openStream();
        char[] password = null;
        if (config.getSslKeystorePassword() != null) {
            password = config.getSslKeystorePassword().toCharArray();
        }
        try {
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        sslContextBuilder.keyManager(keyManagerFactory);
    }
    SSLParameters sslParams = new SSLParameters();
    if (config.isSslEnableEndpointIdentification()) {
        sslParams.setEndpointIdentificationAlgorithm("HTTPS");
    } else {
        if (config.getSslTruststore() == null) {
            sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        }
    }
    SslContext sslContext = sslContextBuilder.build();
    String hostname = config.getSslHostname();
    if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) {
        hostname = config.getAddress().getHost();
    }
    SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort());
    sslEngine.setSSLParameters(sslParams);
    SslHandler sslHandler = new SslHandler(sslEngine);
    ch.pipeline().addLast(sslHandler);
    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

        volatile boolean sslInitDone;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            if (sslInitDone) {
                super.channelActive(ctx);
            }
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) {
                SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt;
                if (e.isSuccess()) {
                    sslInitDone = true;
                    ctx.fireChannelActive();
                } else {
                    RedisConnection connection = RedisConnection.getFrom(ctx.channel());
                    connection.closeAsync();
                    connection.getConnectionPromise().completeExceptionally(e.cause());
                }
            }
            super.userEventTriggered(ctx, evt);
        }
    });
}
Also used : SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) InputStream(java.io.InputStream) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) javax.net.ssl(javax.net.ssl) KeyStore(java.security.KeyStore) SslHandler(io.netty.handler.ssl.SslHandler) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SslContext(io.netty.handler.ssl.SslContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) RedisConnection(org.redisson.client.RedisConnection)

Example 25 with ChannelInboundHandlerAdapter

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

the class Prio0InboundChannelHandlerFactory method createHandler.

@Override
public Optional<ChannelHandler> createHandler(Configuration configuration, Map<String, String> responseHeaders) throws ConfigurationException {
    String redirectFromUrl = configuration.getString(REDIRECT_FROM_URL);
    String redirectToUrl = configuration.getString(REDIRECT_TO_URL);
    if (!redirectFromUrl.isEmpty() && !redirectToUrl.isEmpty()) {
        return Optional.of(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                if (msg instanceof HttpRequest) {
                    HttpRequest httpRequest = (HttpRequest) msg;
                    if (httpRequest.uri().equals(redirectFromUrl)) {
                        httpRequest.setUri(redirectToUrl);
                    }
                }
                ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
            }
        });
    }
    return Optional.empty();
}
Also used : HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) ChannelHandlerContext(org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext) ChannelInboundHandlerAdapter(org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter)

Aggregations

ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)248 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)192 Channel (io.netty.channel.Channel)132 Bootstrap (io.netty.bootstrap.Bootstrap)109 Test (org.junit.jupiter.api.Test)102 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)99 ChannelFuture (io.netty.channel.ChannelFuture)71 CountDownLatch (java.util.concurrent.CountDownLatch)70 InetSocketAddress (java.net.InetSocketAddress)66 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)54 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)53 EventLoopGroup (io.netty.channel.EventLoopGroup)52 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)51 ByteBuf (io.netty.buffer.ByteBuf)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)46 ClosedChannelException (java.nio.channels.ClosedChannelException)46 LocalServerChannel (io.netty.channel.local.LocalServerChannel)44 LocalChannel (io.netty.channel.local.LocalChannel)42 SocketChannel (io.netty.channel.socket.SocketChannel)39