Search in sources :

Example 6 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project vert.x by eclipse.

the class HttpServerImpl method listen.

public synchronized HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestStream.handler() == null && wsStream.handler() == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }
    if (listening) {
        throw new IllegalStateException("Already listening");
    }
    listenContext = vertx.getOrCreateContext();
    listening = true;
    serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port;
    List<HttpVersion> applicationProtocols = options.getAlpnVersions();
    if (listenContext.isWorkerContext()) {
        applicationProtocols = applicationProtocols.stream().filter(v -> v != HttpVersion.HTTP_2).collect(Collectors.toList());
    }
    sslHelper.setApplicationProtocols(applicationProtocols);
    synchronized (vertx.sharedHttpServers()) {
        // Will be updated on bind for a wildcard port
        this.actualPort = port;
        id = new ServerID(port, host);
        HttpServerImpl shared = vertx.sharedHttpServers().get(id);
        if (shared == null || port == 0) {
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            applyConnectionOptions(bootstrap);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (requestStream.isPaused() || wsStream.isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    if (sslHelper.isSSL()) {
                        pipeline.addLast("ssl", sslHelper.createSslHandler(vertx));
                        if (options.isUseAlpn()) {
                            pipeline.addLast("alpn", new ApplicationProtocolNegotiationHandler("http/1.1") {

                                @Override
                                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
                                    if (protocol.equals("http/1.1")) {
                                        configureHttp1(pipeline);
                                    } else {
                                        handleHttp2(ch);
                                    }
                                }
                            });
                        } else {
                            configureHttp1(pipeline);
                        }
                    } else {
                        if (DISABLE_HC2) {
                            configureHttp1(pipeline);
                        } else {
                            pipeline.addLast(new Http1xOrHttp2Handler());
                        }
                    }
                }
            });
            addHandlers(this, listenContext);
            try {
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
                bindFuture.addListener(res -> {
                    if (res.failed()) {
                        vertx.sharedHttpServers().remove(id);
                    } else {
                        Channel serverChannel = res.result();
                        HttpServerImpl.this.actualPort = ((InetSocketAddress) serverChannel.localAddress()).getPort();
                        serverChannelGroup.add(serverChannel);
                        metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error(t);
                }
                listening = false;
                return this;
            }
            vertx.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort;
            addHandlers(actualServer, listenContext);
            metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
        }
        actualServer.bindFuture.addListener(future -> {
            if (listenHandler != null) {
                final AsyncResult<HttpServer> res;
                if (future.succeeded()) {
                    res = Future.succeededFuture(HttpServerImpl.this);
                } else {
                    res = Future.failedFuture(future.cause());
                    listening = false;
                }
                listenContext.runOnContext((v) -> listenHandler.handle(res));
            } else if (future.failed()) {
                listening = false;
                log.error(future.cause());
            }
        });
    }
    return this;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) VertxException(io.vertx.core.VertxException) HandlerManager(io.vertx.core.net.impl.HandlerManager) ServerWebSocket(io.vertx.core.http.ServerWebSocket) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) WebSocketServerHandshakerFactory(io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpServer(io.vertx.core.http.HttpServer) URISyntaxException(java.net.URISyntaxException) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) HttpServerMetrics(io.vertx.core.spi.metrics.HttpServerMetrics) HttpVersion(io.vertx.core.http.HttpVersion) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) CharsetUtil(io.netty.util.CharsetUtil) ReadStream(io.vertx.core.streams.ReadStream) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) URI(java.net.URI) Logger(io.vertx.core.logging.Logger) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) PartialPooledByteBufAllocator(io.vertx.core.net.impl.PartialPooledByteBufAllocator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Future(io.vertx.core.Future) ServerID(io.vertx.core.net.impl.ServerID) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) HandlerHolder(io.vertx.core.net.impl.HandlerHolder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) WebSocketFrameInternal(io.vertx.core.http.impl.ws.WebSocketFrameInternal) VertxEventLoopGroup(io.vertx.core.net.impl.VertxEventLoopGroup) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) ContextImpl(io.vertx.core.impl.ContextImpl) FlashPolicyHandler(io.vertx.core.http.impl.cgbystrom.FlashPolicyHandler) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) LoggerFactory(io.vertx.core.logging.LoggerFactory) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) WebSocketVersion(io.netty.handler.codec.http.websocketx.WebSocketVersion) ByteBuf(io.netty.buffer.ByteBuf) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) ChannelFutureListener(io.netty.channel.ChannelFutureListener) AsyncResult(io.vertx.core.AsyncResult) HttpConnection(io.vertx.core.http.HttpConnection) Metrics(io.vertx.core.spi.metrics.Metrics) HttpContent(io.netty.handler.codec.http.HttpContent) Closeable(io.vertx.core.Closeable) VertxInternal(io.vertx.core.impl.VertxInternal) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) AsyncResolveConnectHelper(io.vertx.core.net.impl.AsyncResolveConnectHelper) HttpMethod(io.netty.handler.codec.http.HttpMethod) SSLHelper(io.vertx.core.net.impl.SSLHelper) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) WebSocketServerHandshaker(io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ChannelHandler(io.netty.channel.ChannelHandler) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) VertxException(io.vertx.core.VertxException) URISyntaxException(java.net.URISyntaxException) Http2Exception(io.netty.handler.codec.http2.Http2Exception) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) ChannelPipeline(io.netty.channel.ChannelPipeline) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ServerID(io.vertx.core.net.impl.ServerID) HttpServer(io.vertx.core.http.HttpServer) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) HttpVersion(io.vertx.core.http.HttpVersion) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Example 7 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project vert.x by eclipse.

the class EventLoopGroupTest method testNettyServerUsesContextEventLoop.

@Test
public void testNettyServerUsesContextEventLoop() throws Exception {
    ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
    AtomicReference<Thread> contextThread = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    context.runOnContext(v -> {
        contextThread.set(Thread.currentThread());
        latch.countDown();
    });
    awaitLatch(latch);
    ServerBootstrap bs = new ServerBootstrap();
    bs.group(context.nettyEventLoop());
    bs.channel(NioServerSocketChannel.class);
    bs.option(ChannelOption.SO_BACKLOG, 100);
    bs.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            assertSame(contextThread.get(), Thread.currentThread());
            context.executeFromIO(() -> {
                assertSame(contextThread.get(), Thread.currentThread());
                assertSame(context, Vertx.currentContext());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf buf = (ByteBuf) msg;
                        assertEquals("hello", buf.toString(StandardCharsets.UTF_8));
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        });
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            testComplete();
                        });
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        fail(cause.getMessage());
                    }
                });
            });
        }
    });
    bs.bind("localhost", 1234).sync();
    vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> {
        assertTrue(ar.succeeded());
        NetSocket so = ar.result();
        so.write(Buffer.buffer("hello"));
    });
    await();
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NetClientOptions(io.vertx.core.net.NetClientOptions) ContextInternal(io.vertx.core.impl.ContextInternal) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 8 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project vert.x by eclipse.

the class Http2ClientTest method testClearText.

private void testClearText(boolean upgrade) throws Exception {
    ServerBootstrap bootstrap = createH2CServer((dec, enc) -> new Http2EventAdapter() {

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true, ctx.newPromise());
            ctx.flush();
        }
    }, upgrade);
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT).sync();
    try {
        client.close();
        client = vertx.createHttpClient(clientOptions.setUseAlpn(false).setSsl(false).setHttp2ClearTextUpgrade(upgrade));
        client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
            assertEquals(HttpVersion.HTTP_2, resp.version());
            testComplete();
        }).exceptionHandler(this::fail).end();
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 9 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project vert.x by eclipse.

the class Http2ClientTest method testGet.

@Test
public void testGet() throws Exception {
    ServerBootstrap bootstrap = createH2Server((decoder, encoder) -> new Http2EventAdapter() {

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
            vertx.runOnContext(v -> {
                assertTrue(endStream);
                encoder.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true, ctx.newPromise());
                ctx.flush();
            });
        }

        @Override
        public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData) throws Http2Exception {
            vertx.runOnContext(v -> {
                testComplete();
            });
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        HttpClientRequest req = client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath");
        req.handler(resp -> {
            Context ctx = vertx.getOrCreateContext();
            assertOnIOContext(ctx);
            resp.endHandler(v -> {
                assertOnIOContext(ctx);
                req.connection().close();
            });
        }).end();
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : Arrays(java.util.Arrays) JksOptions(io.vertx.core.net.JksOptions) BiFunction(java.util.function.BiFunction) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsciiString(io.netty.util.AsciiString) Cert(io.vertx.test.core.tls.Cert) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) StreamResetException(io.vertx.core.http.StreamResetException) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) io.vertx.core(io.vertx.core) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) ConnectException(java.net.ConnectException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) SocketAddress(io.vertx.core.net.SocketAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2ServerUpgradeCodec(io.netty.handler.codec.http2.Http2ServerUpgradeCodec) HttpMethod(io.vertx.core.http.HttpMethod) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) Test(org.junit.Test)

Example 10 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project vert.x by eclipse.

the class Http2ClientTest method testStreamError.

@Test
public void testStreamError() throws Exception {
    waitFor(3);
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, false, ctx.newPromise());
            // Send a corrupted frame on purpose to check we get the corresponding error in the request exception handler
            // the error is : greater padding value 0c -> 1F
            // ChannelFuture a = encoder.frameWriter().writeData(request.context, id, Buffer.buffer("hello").getByteBuf(), 12, false, request.context.newPromise());
            // normal frame    : 00 00 12 00 08 00 00 00 03 0c 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 00
            // corrupted frame : 00 00 12 00 08 00 00 00 03 1F 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 00
            ctx.channel().write(Buffer.buffer(new byte[] { 0x00, 0x00, 0x12, 0x00, 0x08, 0x00, 0x00, 0x00, (byte) (streamId & 0xFF), 0x1F, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }).getByteBuf());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        ctx.runOnContext(v -> {
            client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
                resp.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).connectionHandler(conn -> {
                conn.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).exceptionHandler(err -> {
                assertOnIOContext(ctx);
                if (err instanceof Http2Exception) {
                    complete();
                }
            }).sendHead();
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Arrays(java.util.Arrays) JksOptions(io.vertx.core.net.JksOptions) BiFunction(java.util.function.BiFunction) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsciiString(io.netty.util.AsciiString) Cert(io.vertx.test.core.tls.Cert) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) StreamResetException(io.vertx.core.http.StreamResetException) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) io.vertx.core(io.vertx.core) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) ConnectException(java.net.ConnectException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) SocketAddress(io.vertx.core.net.SocketAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2ServerUpgradeCodec(io.netty.handler.codec.http2.Http2ServerUpgradeCodec) HttpMethod(io.vertx.core.http.HttpMethod) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) Test(org.junit.Test)

Aggregations

ServerBootstrap (io.netty.bootstrap.ServerBootstrap)166 Channel (io.netty.channel.Channel)81 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)78 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)72 EventLoopGroup (io.netty.channel.EventLoopGroup)70 Bootstrap (io.netty.bootstrap.Bootstrap)62 Test (org.junit.Test)59 ChannelFuture (io.netty.channel.ChannelFuture)58 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)48 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)45 InetSocketAddress (java.net.InetSocketAddress)38 SocketChannel (io.netty.channel.socket.SocketChannel)33 LoggingHandler (io.netty.handler.logging.LoggingHandler)33 ChannelPipeline (io.netty.channel.ChannelPipeline)31 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)29 CountDownLatch (java.util.concurrent.CountDownLatch)28 ClosedChannelException (java.nio.channels.ClosedChannelException)27 LocalAddress (io.netty.channel.local.LocalAddress)25 LocalChannel (io.netty.channel.local.LocalChannel)23 ByteBuf (io.netty.buffer.ByteBuf)22