Search in sources :

Example 81 with Promise

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

the class AsyncMapTest method loadData.

protected void loadData(Map<JsonObject, Buffer> map, BiConsumer<Vertx, AsyncMap<JsonObject, Buffer>> test) {
    List<Future> futures = new ArrayList<>(map.size());
    map.forEach((key, value) -> {
        Promise future = Promise.promise();
        getVertx().sharedData().getAsyncMap("foo", onSuccess(asyncMap -> {
            asyncMap.put(key, value, future);
        }));
        futures.add(future.future());
    });
    CompositeFuture.all(futures).onComplete(onSuccess(cf -> {
        Vertx v = getVertx();
        v.sharedData().<JsonObject, Buffer>getAsyncMap("foo", onSuccess(asyncMap -> {
            test.accept(v, asyncMap);
        }));
    }));
}
Also used : java.util(java.util) Promise(io.vertx.core.Promise) ClusterSerializable(io.vertx.core.shareddata.impl.ClusterSerializable) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) Future(io.vertx.core.Future) VertxTestBase(io.vertx.test.core.VertxTestBase) Function(java.util.function.Function) Serializable(java.io.Serializable) CompositeFuture(io.vertx.core.CompositeFuture) JsonArray(io.vertx.core.json.JsonArray) Buffer(io.vertx.core.buffer.Buffer) TestUtils(io.vertx.test.core.TestUtils) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) Promise(io.vertx.core.Promise) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) Vertx(io.vertx.core.Vertx)

Example 82 with Promise

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

the class Http2ClientTest method testClientSettings.

@Test
public void testClientSettings() throws Exception {
    waitFor(2);
    io.vertx.core.http.Http2Settings initialSettings = TestUtils.randomHttp2Settings();
    io.vertx.core.http.Http2Settings updatedSettings = TestUtils.randomHttp2Settings();
    // Otherwise it raise "invalid max dynamic table size" in Netty
    updatedSettings.setHeaderTableSize(initialSettings.getHeaderTableSize());
    AtomicInteger count = new AtomicInteger();
    Promise<Void> end = Promise.promise();
    server.requestHandler(req -> {
        end.future().onComplete(v -> {
            req.response().end();
        });
    }).connectionHandler(conn -> {
        io.vertx.core.http.Http2Settings initialRemoteSettings = conn.remoteSettings();
        assertEquals(initialSettings.isPushEnabled(), initialRemoteSettings.isPushEnabled());
        assertEquals(initialSettings.getMaxHeaderListSize(), initialRemoteSettings.getMaxHeaderListSize());
        assertEquals(initialSettings.getMaxFrameSize(), initialRemoteSettings.getMaxFrameSize());
        assertEquals(initialSettings.getInitialWindowSize(), initialRemoteSettings.getInitialWindowSize());
        // assertEquals(Math.min(initialSettings.getMaxConcurrentStreams(), Integer.MAX_VALUE), settings.getMaxConcurrentStreams());
        assertEquals(initialSettings.getHeaderTableSize(), initialRemoteSettings.getHeaderTableSize());
        assertEquals(initialSettings.get('\u0007'), initialRemoteSettings.get(7));
        Context ctx = Vertx.currentContext();
        conn.remoteSettingsHandler(settings -> {
            assertOnIOContext(ctx);
            switch(count.getAndIncrement()) {
                case 0:
                    // find out why it fails sometimes ...
                    // assertEquals(updatedSettings.pushEnabled(), settings.getEnablePush());
                    assertEquals(updatedSettings.getMaxHeaderListSize(), settings.getMaxHeaderListSize());
                    assertEquals(updatedSettings.getMaxFrameSize(), settings.getMaxFrameSize());
                    assertEquals(updatedSettings.getInitialWindowSize(), settings.getInitialWindowSize());
                    // find out why it fails sometimes ...
                    // assertEquals(Math.min(updatedSettings.maxConcurrentStreams(), Integer.MAX_VALUE), settings.getMaxConcurrentStreams());
                    assertEquals(updatedSettings.getHeaderTableSize(), settings.getHeaderTableSize());
                    assertEquals(updatedSettings.get('\u0007'), settings.get(7));
                    complete();
                    break;
                default:
                    fail();
            }
        });
    });
    startServer();
    client.close();
    client = vertx.createHttpClient(clientOptions.setInitialSettings(initialSettings));
    client.connectionHandler(conn -> {
        vertx.runOnContext(v -> {
            conn.updateSettings(updatedSettings, ar -> {
                end.complete();
            });
        });
    });
    client.request(requestOptions).onComplete(onSuccess(req -> {
        req.send(onSuccess(resp -> complete()));
    }));
    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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 83 with Promise

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

the class Http2ClientTest method testClientResetServerStreamDuringRequest.

@Test
public void testClientResetServerStreamDuringRequest() throws Exception {
    waitFor(2);
    Promise<Void> bufReceived = Promise.promise();
    server.requestHandler(req -> {
        req.handler(buf -> {
            bufReceived.complete();
        });
        AtomicBoolean errored = new AtomicBoolean();
        req.exceptionHandler(err -> {
            if (errored.compareAndSet(false, true)) {
                assertEquals(err.getClass(), StreamResetException.class);
            }
        });
        AtomicLong reset = new AtomicLong();
        req.response().exceptionHandler(err -> {
            if (err instanceof StreamResetException) {
                reset.set(((StreamResetException) err).getCode());
            }
        });
        req.response().closeHandler(v -> {
            assertEquals(10L, reset.get());
            complete();
        });
    });
    startServer(testAddress);
    client.request(requestOptions).onComplete(onSuccess(req -> {
        req.response(onFailure(err -> {
            complete();
        })).setChunked(true);
        req.write(Buffer.buffer("hello"));
        bufReceived.future().onComplete(ar -> {
            req.reset(10);
        });
    }));
    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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.junit.Test)

Example 84 with Promise

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

the class Http2ClientTest method testClientResponsePauseResume.

@Test
public void testClientResponsePauseResume() throws Exception {
    String content = TestUtils.randomAlphaString(1024);
    Buffer expected = Buffer.buffer();
    Promise<Void> whenFull = Promise.promise();
    AtomicBoolean drain = new AtomicBoolean();
    server.requestHandler(req -> {
        HttpServerResponse resp = req.response();
        resp.putHeader("content-type", "text/plain");
        resp.setChunked(true);
        vertx.setPeriodic(1, timerID -> {
            if (resp.writeQueueFull()) {
                resp.drainHandler(v -> {
                    Buffer last = Buffer.buffer("last");
                    expected.appendBuffer(last);
                    resp.end(last);
                    assertEquals(expected.toString().getBytes().length, resp.bytesWritten());
                });
                vertx.cancelTimer(timerID);
                drain.set(true);
                whenFull.complete();
            } else {
                Buffer chunk = Buffer.buffer(content);
                expected.appendBuffer(chunk);
                resp.write(chunk);
            }
        });
    });
    startServer();
    client.request(requestOptions).onComplete(onSuccess(req -> {
        req.send(onSuccess(resp -> {
            Context ctx = vertx.getOrCreateContext();
            Buffer received = Buffer.buffer();
            resp.pause();
            resp.handler(buff -> {
                if (whenFull.future().isComplete()) {
                    assertSame(ctx, Vertx.currentContext());
                } else {
                    assertOnIOContext(ctx);
                }
                received.appendBuffer(buff);
            });
            resp.endHandler(v -> {
                assertEquals(expected.toString().length(), received.toString().length());
                testComplete();
            });
            whenFull.future().onComplete(v -> {
                resp.resume();
            });
        }));
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) 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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AsciiString(io.netty.util.AsciiString) Test(org.junit.Test)

Example 85 with Promise

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

the class Http2ClientTest method testClientStreamPriorityNoChange.

@Ignore("Cannot pass reliably for now (https://github.com/netty/netty/issues/9842)")
@Test
public void testClientStreamPriorityNoChange() throws Exception {
    StreamPriority streamPriority = new StreamPriority().setDependency(123).setWeight((short) 45).setExclusive(true);
    waitFor(2);
    Promise<Void> latch = Promise.promise();
    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 -> {
                assertEquals(streamPriority.getDependency(), streamDependency);
                assertEquals(streamPriority.getWeight(), weight);
                assertEquals(streamPriority.isExclusive(), exclusive);
                assertFalse(endStream);
                latch.complete();
            });
            encoder.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true, ctx.newPromise());
            ctx.flush();
        }

        @Override
        public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight, boolean exclusive) throws Http2Exception {
            fail("Priority frame should not be sent");
        }

        @Override
        public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
            if (endOfStream) {
                vertx.runOnContext(v -> {
                    complete();
                });
            }
            return super.onDataRead(ctx, streamId, data, padding, endOfStream);
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        client.request(new RequestOptions().setHost(DEFAULT_HTTPS_HOST).setPort(DEFAULT_HTTPS_PORT).setURI("/somepath")).onComplete(onSuccess(req -> {
            req.response(onSuccess(resp -> {
                resp.endHandler(v -> {
                    complete();
                });
            })).setStreamPriority(streamPriority);
            req.sendHead();
            latch.future().onComplete(onSuccess(v -> {
                req.setStreamPriority(streamPriority);
                req.end();
            }));
        }));
        await();
    } finally {
        s.channel().close().sync();
    }
}
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) ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Ignore(org.junit.Ignore) 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