Search in sources :

Example 6 with Promise

use of io.vertx.core.Promise in project vert.x by eclipse.

the class Http2Test method testConnectionCloseEvictsConnectionFromThePoolBeforeStreamsAreClosed.

/**
 * Test that socket close (without an HTTP/2 go away frame) removes the connection from the pool
 * before the streams are notified. Otherwise a notified stream might reuse a stale connection from
 * the pool.
 */
@Test
public void testConnectionCloseEvictsConnectionFromThePoolBeforeStreamsAreClosed() throws Exception {
    Set<HttpConnection> serverConnections = new HashSet<>();
    server.requestHandler(req -> {
        serverConnections.add(req.connection());
        switch(req.path()) {
            case "/1":
                req.response().end();
                break;
            case "/2":
                assertEquals(1, serverConnections.size());
                // Socket close without HTTP/2 go away
                Channel ch = ((ConnectionBase) req.connection()).channel();
                ChannelPromise promise = ch.newPromise();
                ch.unsafe().close(promise);
                break;
            case "/3":
                assertEquals(2, serverConnections.size());
                req.response().end();
                break;
        }
    });
    startServer(testAddress);
    Future<Buffer> f1 = client.request(new RequestOptions(requestOptions).setURI("/1")).compose(req -> req.send().compose(HttpClientResponse::body));
    f1.onComplete(onSuccess(v -> {
        Future<Buffer> f2 = client.request(new RequestOptions(requestOptions).setURI("/2")).compose(req -> {
            System.out.println(req.connection());
            return req.send().compose(HttpClientResponse::body);
        });
        f2.onComplete(onFailure(v2 -> {
            Future<Buffer> f3 = client.request(new RequestOptions(requestOptions).setURI("/3")).compose(req -> {
                System.out.println(req.connection());
                return req.send().compose(HttpClientResponse::body);
            });
            f3.onComplete(onSuccess(vvv -> {
                testComplete();
            }));
        }));
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) java.util(java.util) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) Context(io.vertx.core.Context) PfxOptions(io.vertx.core.net.PfxOptions) BooleanSupplier(java.util.function.BooleanSupplier) OpenSSLEngineOptions(io.vertx.core.net.OpenSSLEngineOptions) ChannelPromise(io.netty.channel.ChannelPromise) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DuplexChannel(io.netty.channel.socket.DuplexChannel) Http2ServerConnection(io.vertx.core.http.impl.Http2ServerConnection) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Promise(io.vertx.core.Promise) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) Test(org.junit.Test) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Repeat(io.vertx.test.core.Repeat) Stream(java.util.stream.Stream) Buffer(io.vertx.core.buffer.Buffer) Ignore(org.junit.Ignore) AsyncTestBase(io.vertx.test.core.AsyncTestBase) Cert(io.vertx.test.tls.Cert) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) DuplexChannel(io.netty.channel.socket.DuplexChannel) Channel(io.netty.channel.Channel) CompletableFuture(java.util.concurrent.CompletableFuture) Future(io.vertx.core.Future) ChannelPromise(io.netty.channel.ChannelPromise) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) Test(org.junit.Test)

Example 7 with Promise

use of io.vertx.core.Promise in project vert.x by eclipse.

the class ClusteredEventBus method start.

@Override
public void start(Promise<Void> promise) {
    NetServerOptions serverOptions = getServerOptions();
    server = vertx.createNetServer(serverOptions);
    server.connectHandler(getServerHandler());
    int port = getClusterPort();
    String host = getClusterHost();
    server.listen(port, host).flatMap(v -> {
        int publicPort = getClusterPublicPort(server.actualPort());
        String publicHost = getClusterPublicHost(host);
        nodeInfo = new NodeInfo(publicHost, publicPort, options.getClusterNodeMetadata());
        nodeId = clusterManager.getNodeId();
        Promise<Void> setPromise = Promise.promise();
        clusterManager.setNodeInfo(nodeInfo, setPromise);
        return setPromise.future();
    }).onSuccess(v -> {
        started = true;
        nodeSelector.eventBusStarted();
    }).onComplete(promise);
}
Also used : LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) MultiMap(io.vertx.core.MultiMap) ContextInternal(io.vertx.core.impl.ContextInternal) ConcurrentMap(java.util.concurrent.ConcurrentMap) RecordParser(io.vertx.core.parsetools.RecordParser) EventBusOptions(io.vertx.core.eventbus.EventBusOptions) NetClient(io.vertx.core.net.NetClient) Logger(io.vertx.core.impl.logging.Logger) VertxInternal(io.vertx.core.impl.VertxInternal) NodeSelector(io.vertx.core.spi.cluster.NodeSelector) ClusterManager(io.vertx.core.spi.cluster.ClusterManager) Promise(io.vertx.core.Promise) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) VertxOptions(io.vertx.core.VertxOptions) UUID(java.util.UUID) NetClientOptions(io.vertx.core.net.NetClientOptions) Objects(java.util.Objects) AtomicLong(java.util.concurrent.atomic.AtomicLong) NetServerOptions(io.vertx.core.net.NetServerOptions) MessageCodec(io.vertx.core.eventbus.MessageCodec) Buffer(io.vertx.core.buffer.Buffer) io.vertx.core.eventbus.impl(io.vertx.core.eventbus.impl) RegistrationInfo(io.vertx.core.spi.cluster.RegistrationInfo) AddressHelper(io.vertx.core.eventbus.AddressHelper) NetServer(io.vertx.core.net.NetServer) NodeInfo(io.vertx.core.spi.cluster.NodeInfo) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) NodeInfo(io.vertx.core.spi.cluster.NodeInfo) NetServerOptions(io.vertx.core.net.NetServerOptions)

Example 8 with Promise

use of io.vertx.core.Promise in project vert.x by eclipse.

the class Http2ServerTest method testClientSendGoAwayNoError.

@Test
public void testClientSendGoAwayNoError() throws Exception {
    Promise<Void> abc = Promise.promise();
    Context ctx = vertx.getOrCreateContext();
    Handler<HttpServerRequest> requestHandler = req -> {
        HttpConnection conn = req.connection();
        AtomicInteger numShutdown = new AtomicInteger();
        AtomicBoolean completed = new AtomicBoolean();
        conn.shutdownHandler(v -> {
            assertOnIOContext(ctx);
            numShutdown.getAndIncrement();
            vertx.setTimer(100, timerID -> {
                // Delay so we can check the connection is not closed
                completed.set(true);
                testComplete();
            });
        });
        conn.goAwayHandler(ga -> {
            assertOnIOContext(ctx);
            assertEquals(0, numShutdown.get());
            req.response().end();
        });
        conn.closeHandler(v -> {
            assertTrue(completed.get());
        });
        abc.complete();
    };
    server.requestHandler(requestHandler);
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        Http2ConnectionEncoder encoder = request.encoder;
        int id = request.nextStreamId();
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
        abc.future().onComplete(ar -> {
            encoder.writeGoAway(request.context, id, 0, Unpooled.EMPTY_BUFFER, request.context.newPromise());
            request.context.flush();
        });
    });
    fut.sync();
    await();
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) Context(io.vertx.core.Context) Utils(io.vertx.core.impl.Utils) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Trust(io.vertx.test.tls.Trust) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Http2Error(io.netty.handler.codec.http2.Http2Error) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) DetectFileDescriptorLeaks(io.vertx.test.core.DetectFileDescriptorLeaks) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) 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) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) ChannelFuture(io.netty.channel.ChannelFuture) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) Test(org.junit.Test)

Example 9 with Promise

use of io.vertx.core.Promise in project vert.x by eclipse.

the class Http2ClientTest method testServerResetClientStreamDuringResponse.

@Test
public void testServerResetClientStreamDuringResponse() throws Exception {
    waitFor(2);
    String chunk = TestUtils.randomAlphaString(1024);
    Promise<Void> doReset = Promise.promise();
    server.requestHandler(req -> {
        doReset.future().onComplete(onSuccess(v -> {
            req.response().reset(8);
        }));
        req.response().setChunked(true).write(Buffer.buffer(chunk));
    });
    startServer(testAddress);
    Context ctx = vertx.getOrCreateContext();
    Handler<Throwable> resetHandler = err -> {
        assertOnIOContext(ctx);
        if (err instanceof StreamResetException) {
            StreamResetException reset = (StreamResetException) err;
            assertEquals(8, reset.getCode());
            complete();
        }
    };
    client.close();
    ctx.runOnContext(v -> {
        client = vertx.createHttpClient(createBaseClientOptions());
        client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.POST)).onComplete(onSuccess(req -> {
            req.response(onSuccess(resp -> {
                resp.exceptionHandler(resetHandler);
                resp.handler(buff -> {
                    doReset.complete();
                });
            })).exceptionHandler(resetHandler).setChunked(true).write(chunk);
        }));
    });
    await();
}
Also used : Arrays(java.util.Arrays) io.netty.handler.codec.http2(io.netty.handler.codec.http2) BiFunction(java.util.function.BiFunction) MultiMap(io.vertx.core.MultiMap) AsciiString(io.netty.util.AsciiString) Context(io.vertx.core.Context) HttpClientConnection(io.vertx.core.http.impl.HttpClientConnection) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) 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) Cert(io.vertx.test.tls.Cert) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) 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) ByteBuf(io.netty.buffer.ByteBuf) Assume(org.junit.Assume) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) VertxInternal(io.vertx.core.impl.VertxInternal) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) 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) AtomicLong(java.util.concurrent.atomic.AtomicLong) Ignore(org.junit.Ignore) AsyncTestBase(io.vertx.test.core.AsyncTestBase) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AsciiString(io.netty.util.AsciiString) Test(org.junit.Test)

Example 10 with Promise

use of io.vertx.core.Promise in project vert.x by eclipse.

the class DatagramTest method testWorker.

@Test
public void testWorker() {
    waitFor(2);
    Buffer expected = TestUtils.randomBuffer(128);
    vertx.deployVerticle(new AbstractVerticle() {

        @Override
        public void start(Promise<Void> startPromise) {
            peer2 = vertx.createDatagramSocket(new DatagramSocketOptions());
            peer2.exceptionHandler(t -> fail(t.getMessage()));
            peer2.handler(packet -> {
                assertTrue(Context.isOnWorkerThread());
                assertSame(context, Vertx.currentContext());
                complete();
            });
            peer2.listen(1234, "127.0.0.1").<Void>mapEmpty().onComplete(startPromise);
        }
    }, new DeploymentOptions().setWorker(true), onSuccess(id -> {
        peer1 = vertx.createDatagramSocket(new DatagramSocketOptions());
        peer1.send(expected, 1234, "127.0.0.1", onSuccess(s -> {
            complete();
        }));
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) NetworkOptions(io.vertx.core.net.NetworkOptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Random(java.util.Random) Context(io.vertx.core.Context) VertxTestBase(io.vertx.test.core.VertxTestBase) Utils(io.vertx.core.impl.Utils) InetAddress(java.net.InetAddress) ByteBuf(io.netty.buffer.ByteBuf) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteStream(io.vertx.core.streams.WriteStream) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) NetworkInterface(java.net.NetworkInterface) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) AbstractVerticle(io.vertx.core.AbstractVerticle) Handler(io.vertx.core.Handler) UnpooledHeapByteBuf(io.netty.buffer.UnpooledHeapByteBuf) DeploymentOptions(io.vertx.core.DeploymentOptions) AbstractVerticle(io.vertx.core.AbstractVerticle) Test(org.junit.Test)

Aggregations

Promise (io.vertx.core.Promise)155 Future (io.vertx.core.Future)122 Handler (io.vertx.core.Handler)95 List (java.util.List)86 Vertx (io.vertx.core.Vertx)85 Buffer (io.vertx.core.buffer.Buffer)83 TimeUnit (java.util.concurrent.TimeUnit)79 HttpURLConnection (java.net.HttpURLConnection)66 Logger (org.slf4j.Logger)63 LoggerFactory (org.slf4j.LoggerFactory)63 Optional (java.util.Optional)62 AsyncResult (io.vertx.core.AsyncResult)61 Truth.assertThat (com.google.common.truth.Truth.assertThat)60 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)60 VertxTestContext (io.vertx.junit5.VertxTestContext)59 Test (org.junit.jupiter.api.Test)58 Map (java.util.Map)54 UUID (java.util.UUID)52 ArrayList (java.util.ArrayList)51 JsonObject (io.vertx.core.json.JsonObject)50