Search in sources :

Example 51 with ChannelInitializer

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

the class LumberjackUtil method sendMessages.

static List<Integer> sendMessages(int port, SSLContextParameters sslContextParameters) throws InterruptedException {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {
        // This list will hold the acknowledgment response sequence numbers
        List<Integer> responses = new ArrayList<>();
        // This initializer configures the SSL and an acknowledgment recorder
        ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (sslContextParameters != null) {
                    SSLEngine sslEngine = sslContextParameters.createSSLContext(null).createSSLEngine();
                    sslEngine.setUseClientMode(true);
                    pipeline.addLast(new SslHandler(sslEngine));
                }
                // Add the response recorder
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        assertEquals(msg.readUnsignedByte(), (short) '2');
                        assertEquals(msg.readUnsignedByte(), (short) 'A');
                        synchronized (responses) {
                            responses.add(msg.readInt());
                        }
                    }
                });
            }
        };
        // Connect to the server
        Channel channel = //
        new Bootstrap().group(//
        eventLoopGroup).channel(//
        NioSocketChannel.class).handler(//
        initializer).connect("127.0.0.1", port).sync().channel();
        // Send the 2 window frames
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("io/window10"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("io/window15"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.close();
        synchronized (responses) {
            return responses;
        }
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) IOException(java.io.IOException) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 52 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project xian by happyyangyuan.

the class OAuthServer method startServer.

public void startServer() {
    synchronized (LOCK) {
        if (started.get()) {
            LOG.warn("已启动,不允许重复启动");
            return;
        }
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() {

                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast("encoder", new HttpResponseEncoder()).addLast("decoder", new HttpRequestDecoder()).addLast("aggregator", new HttpObjectAggregator(4096)).addLast("handler", new OAuth20Handler());
                }
            }).option(ChannelOption.SO_BACKLOG, 10240).option(ChannelOption.SO_REUSEADDR, true);
            LOG.info(String.format("[OAuth] oauth server is about to start on port {%s} ", PORT));
            parentChannel = b.bind(PORT).sync().channel();
            LOG.info(String.format("[OAuth] oauth server started on port {%s} ", PORT));
            ThreadPoolManager.execute(() -> {
                try {
                    LOG.debug("[OAuth] Wait until the server socket is closed.");
                    parentChannel.closeFuture().sync();
                } catch (Throwable ee) {
                    LOG.error(ee);
                } finally {
                    LOG.info("[OAuth] 准备shutdown oauth server");
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                    LOG.info("[OAuth] oauth server shutdown完毕!");
                }
            });
            started.set(true);
        } catch (Throwable e) {
            LOG.error("[OAuth] oauth server 启动失败", e);
            started.set(false);
        }
    }
}
Also used : HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 53 with ChannelInitializer

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

the class BGPReconnectPromise method connectSessionPromise.

private BGPProtocolSessionPromise<S> connectSessionPromise(final InetSocketAddress address, final int retryTimer, final Bootstrap bootstrap, final BGPPeerRegistry peerRegistry, final ChannelPipelineInitializer<S> initializer) {
    final BGPProtocolSessionPromise<S> sessionPromise = new BGPProtocolSessionPromise<>(address, retryTimer, bootstrap, peerRegistry);
    final ChannelHandler chInit = new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            initializer.initializeChannel(channel, sessionPromise);
        }
    };
    bootstrap.handler(chInit);
    sessionPromise.connect();
    LOG.debug("Client created.");
    return sessionPromise;
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ChannelHandler(io.netty.channel.ChannelHandler) ChannelInitializer(io.netty.channel.ChannelInitializer)

Example 54 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project activemq-artemis by apache.

the class WebServerComponentTest method simpleServer.

@Test
public void simpleServer() throws Exception {
    WebServerDTO webServerDTO = new WebServerDTO();
    webServerDTO.bind = "http://localhost:0";
    webServerDTO.path = "webapps";
    WebServerComponent webServerComponent = new WebServerComponent();
    Assert.assertFalse(webServerComponent.isStarted());
    webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/");
    testedComponents.add(webServerComponent);
    webServerComponent.start();
    final int port = webServerComponent.getPort();
    // Make the connection attempt.
    CountDownLatch latch = new CountDownLatch(1);
    final ClientHandler clientHandler = new ClientHandler(latch);
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(clientHandler);
        }
    });
    Channel ch = bootstrap.connect("localhost", port).sync().channel();
    URI uri = new URI(URL);
    // Prepare the HTTP request.
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.headers().set(HttpHeaderNames.HOST, "localhost");
    // Send the HTTP request.
    ch.writeAndFlush(request);
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(clientHandler.body, "12345");
    // Wait for the server to close the connection.
    ch.close();
    Assert.assertTrue(webServerComponent.isStarted());
    webServerComponent.stop(true);
    Assert.assertFalse(webServerComponent.isStarted());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) WebServerDTO(org.apache.activemq.artemis.dto.WebServerDTO) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) WebServerComponent(org.apache.activemq.artemis.component.WebServerComponent) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.Test)

Example 55 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project activemq-artemis by apache.

the class WebServerComponentTest method simpleSecureServerWithClientAuth.

@Test
public void simpleSecureServerWithClientAuth() throws Exception {
    WebServerDTO webServerDTO = new WebServerDTO();
    webServerDTO.bind = "https://localhost:0";
    webServerDTO.path = "webapps";
    webServerDTO.keyStorePath = "./src/test/resources/server.keystore";
    webServerDTO.setKeyStorePassword("password");
    webServerDTO.clientAuth = true;
    webServerDTO.trustStorePath = "./src/test/resources/server.keystore";
    webServerDTO.setTrustStorePassword("password");
    WebServerComponent webServerComponent = new WebServerComponent();
    Assert.assertFalse(webServerComponent.isStarted());
    webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/");
    testedComponents.add(webServerComponent);
    webServerComponent.start();
    final int port = webServerComponent.getPort();
    // Make the connection attempt.
    String keyStoreProvider = "JKS";
    SSLContext context = SSLSupport.createContext(keyStoreProvider, webServerDTO.keyStorePath, webServerDTO.getKeyStorePassword(), keyStoreProvider, webServerDTO.trustStorePath, webServerDTO.getTrustStorePassword());
    SSLEngine engine = context.createSSLEngine();
    engine.setUseClientMode(true);
    engine.setWantClientAuth(true);
    final SslHandler sslHandler = new SslHandler(engine);
    CountDownLatch latch = new CountDownLatch(1);
    final ClientHandler clientHandler = new ClientHandler(latch);
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(sslHandler);
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(clientHandler);
        }
    });
    Channel ch = bootstrap.connect("localhost", port).sync().channel();
    URI uri = new URI(SECURE_URL);
    // Prepare the HTTP request.
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.headers().set(HttpHeaderNames.HOST, "localhost");
    // Send the HTTP request.
    ch.writeAndFlush(request);
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(clientHandler.body, "12345");
    // Wait for the server to close the connection.
    ch.close();
    Assert.assertTrue(webServerComponent.isStarted());
    webServerComponent.stop(true);
    Assert.assertFalse(webServerComponent.isStarted());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) SSLEngine(javax.net.ssl.SSLEngine) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SSLContext(javax.net.ssl.SSLContext) WebServerDTO(org.apache.activemq.artemis.dto.WebServerDTO) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) SslHandler(io.netty.handler.ssl.SslHandler) URISyntaxException(java.net.URISyntaxException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) WebServerComponent(org.apache.activemq.artemis.component.WebServerComponent) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.Test)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)83 Channel (io.netty.channel.Channel)58 Bootstrap (io.netty.bootstrap.Bootstrap)42 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)39 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)32 InetSocketAddress (java.net.InetSocketAddress)32 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)31 ChannelFuture (io.netty.channel.ChannelFuture)29 EventLoopGroup (io.netty.channel.EventLoopGroup)26 ChannelPipeline (io.netty.channel.ChannelPipeline)25 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LocalChannel (io.netty.channel.local.LocalChannel)20 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)17 SslHandler (io.netty.handler.ssl.SslHandler)17 SocketChannel (io.netty.channel.socket.SocketChannel)16 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)14 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)12 CountDownLatch (java.util.concurrent.CountDownLatch)12