Search in sources :

Example 1 with Promise

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

the class Http2ConnectionBase method close.

@Override
public Future<Void> close() {
    PromiseInternal<Void> promise = context.promise();
    ChannelPromise pr = chctx.newPromise();
    ChannelPromise channelPromise = pr.addListener(promise);
    handlerContext.writeAndFlush(Unpooled.EMPTY_BUFFER, pr);
    channelPromise.addListener((ChannelFutureListener) future -> shutdown(0L));
    return promise.future();
}
Also used : VertxException(io.vertx.core.VertxException) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) ArrayList(java.util.ArrayList) VertxByteBufAllocator(io.vertx.core.buffer.impl.VertxByteBufAllocator) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) Http2Stream(io.netty.handler.codec.http2.Http2Stream) AsyncResult(io.vertx.core.AsyncResult) HttpConnection(io.vertx.core.http.HttpConnection) Logger(io.vertx.core.impl.logging.Logger) io.netty.buffer(io.netty.buffer) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Http2Flags(io.netty.handler.codec.http2.Http2Flags) StreamPriority(io.vertx.core.http.StreamPriority) Promise(io.vertx.core.Promise) GoAway(io.vertx.core.http.GoAway) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) Http2Settings(io.netty.handler.codec.http2.Http2Settings) Nullable(io.vertx.codegen.annotations.Nullable) Objects(java.util.Objects) EventLoopContext(io.vertx.core.impl.EventLoopContext) Http2Connection(io.netty.handler.codec.http2.Http2Connection) Buffer(io.vertx.core.buffer.Buffer) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Handler(io.vertx.core.Handler) ArrayDeque(java.util.ArrayDeque) ChannelPromise(io.netty.channel.ChannelPromise)

Example 2 with Promise

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

the class FaultToleranceVerticle method start.

@Override
public void start() throws Exception {
    JsonObject config = config();
    id = config.getInteger("id");
    numAddresses = config.getInteger("addressesCount");
    List<Future> registrationFutures = new ArrayList<>(numAddresses);
    for (int i = 0; i < numAddresses; i++) {
        Promise<Void> registrationFuture = Promise.promise();
        registrationFutures.add(registrationFuture.future());
        vertx.eventBus().consumer(createAddress(id, i), msg -> msg.reply("pong")).completionHandler(registrationFuture);
    }
    Promise<Void> registrationFuture = Promise.promise();
    registrationFutures.add(registrationFuture.future());
    vertx.eventBus().consumer("ping", this::ping).completionHandler(registrationFuture);
    CompositeFuture.all(registrationFutures).onSuccess(ar -> vertx.eventBus().send("control", "start"));
}
Also used : Logger(io.vertx.core.impl.logging.Logger) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) Promise(io.vertx.core.Promise) Message(io.vertx.core.eventbus.Message) Future(io.vertx.core.Future) ArrayList(java.util.ArrayList) CompositeFuture(io.vertx.core.CompositeFuture) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) AbstractVerticle(io.vertx.core.AbstractVerticle) ReplyFailure(io.vertx.core.eventbus.ReplyFailure) JsonObject(io.vertx.core.json.JsonObject) ReplyException(io.vertx.core.eventbus.ReplyException) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture)

Example 3 with Promise

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

the class Http2ServerTest method testUpgradeToClearText.

private void testUpgradeToClearText(HttpMethod method, Buffer expected, Handler<HttpServerOptions> optionsConfig) throws Exception {
    server.close();
    AtomicInteger serverConnectionCount = new AtomicInteger();
    optionsConfig.handle(serverOptions);
    server = vertx.createHttpServer(serverOptions.setHost(DEFAULT_HTTP_HOST).setPort(DEFAULT_HTTP_PORT).setUseAlpn(false).setSsl(false).setInitialSettings(new io.vertx.core.http.Http2Settings().setMaxConcurrentStreams(20000))).connectionHandler(conn -> serverConnectionCount.incrementAndGet());
    server.requestHandler(req -> {
        assertEquals("http", req.scheme());
        assertEquals(method, req.method());
        assertEquals(HttpVersion.HTTP_2, req.version());
        assertEquals(10000, req.connection().remoteSettings().getMaxConcurrentStreams());
        assertFalse(req.isSSL());
        req.bodyHandler(body -> {
            assertEquals(expected, body);
            vertx.setTimer(10, id -> {
                req.response().end();
            });
        });
    }).connectionHandler(conn -> {
        assertNotNull(conn);
        serverConnectionCount.incrementAndGet();
    });
    startServer(testAddress);
    AtomicInteger clientConnectionCount = new AtomicInteger();
    client = vertx.createHttpClient(clientOptions.setUseAlpn(false).setSsl(false).setInitialSettings(new io.vertx.core.http.Http2Settings().setMaxConcurrentStreams(10000)));
    Promise<HttpClientResponse> p1 = Promise.promise();
    p1.future().onComplete(onSuccess(resp -> {
        assertEquals(HttpVersion.HTTP_2, resp.version());
        // assertEquals(20000, req.connection().remoteSettings().getMaxConcurrentStreams());
        assertEquals(1, serverConnectionCount.get());
        assertEquals(1, clientConnectionCount.get());
        Promise<HttpClientResponse> p2 = Promise.promise();
        p2.future().onComplete(onSuccess(resp2 -> {
            testComplete();
        }));
        doRequest(method, expected, null, p2);
    }));
    doRequest(method, expected, conn -> clientConnectionCount.incrementAndGet(), p1);
    await();
}
Also used : 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) Promise(io.vertx.core.Promise) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Settings(io.netty.handler.codec.http2.Http2Settings)

Example 4 with Promise

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

the class WebSocketTest method testAsyncAccept.

@Test
public void testAsyncAccept() {
    AtomicBoolean resolved = new AtomicBoolean();
    server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)).webSocketHandler(ws -> {
        Promise<Integer> promise = Promise.promise();
        ws.setHandshake(promise.future());
        try {
            ws.accept();
            fail();
        } catch (IllegalStateException ignore) {
        // Expected
        }
        try {
            ws.writeTextMessage("hello");
            fail();
        } catch (IllegalStateException ignore) {
        // Expected
        }
        vertx.setTimer(500, id -> {
            resolved.set(true);
            promise.complete(101);
        });
    });
    server.listen(onSuccess(s -> {
        client = vertx.createHttpClient();
        client.webSocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/some/path", onSuccess(ws -> {
            assertTrue(resolved.get());
            testComplete();
        }));
    }));
    await();
}
Also used : WebSocketInternal(io.vertx.core.http.impl.WebSocketInternal) MultiMap(io.vertx.core.MultiMap) Context(io.vertx.core.Context) Matcher(java.util.regex.Matcher) PlatformDependent(io.netty.util.internal.PlatformDependent) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DEFAULT_HTTP_HOST(io.vertx.core.http.HttpTestBase.DEFAULT_HTTP_HOST) ReadStream(io.vertx.core.streams.ReadStream) HAProxy(io.vertx.test.proxy.HAProxy) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) CheckingSender(io.vertx.test.core.CheckingSender) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) VertxOptions(io.vertx.core.VertxOptions) Trust(io.vertx.test.tls.Trust) BlockingQueue(java.util.concurrent.BlockingQueue) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) Certificate(java.security.cert.Certificate) Buffer(io.vertx.core.buffer.Buffer) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Cert(io.vertx.test.tls.Cert) Pattern(java.util.regex.Pattern) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) NetSocket(io.vertx.core.net.NetSocket) java.util(java.util) MessageDigest(java.security.MessageDigest) DEFAULT_HTTP_PORT(io.vertx.core.http.HttpTestBase.DEFAULT_HTTP_PORT) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) DEFAULT_HTTPS_HOST(io.vertx.core.http.HttpTestBase.DEFAULT_HTTPS_HOST) BiConsumer(java.util.function.BiConsumer) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocket13FrameDecoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) DEFAULT_TEST_URI(io.vertx.core.http.HttpTestBase.DEFAULT_TEST_URI) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) Promise(io.vertx.core.Promise) TestUtils.randomAlphaString(io.vertx.test.core.TestUtils.randomAlphaString) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) IOException(java.io.IOException) Http1xServerConnection(io.vertx.core.http.impl.Http1xServerConnection) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) WebSocket13FrameEncoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) DEFAULT_HTTPS_PORT(io.vertx.core.http.HttpTestBase.DEFAULT_HTTPS_PORT) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) Http1xClientConnection(io.vertx.core.http.impl.Http1xClientConnection) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Promise(io.vertx.core.Promise) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) Test(org.junit.Test)

Example 5 with Promise

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

the class Http2Test method testClientStreamPausedWhenConnectionIsPaused.

@Test
public void testClientStreamPausedWhenConnectionIsPaused() throws Exception {
    waitFor(2);
    Buffer buffer = TestUtils.randomBuffer(512);
    CompletableFuture<Void> resumeLatch = new CompletableFuture<>();
    server.requestHandler(req -> {
        switch(req.path()) {
            case "/0":
                {
                    req.pause();
                    resumeLatch.thenAccept(v -> {
                        req.resume();
                    });
                    req.endHandler(v -> {
                        req.response().end();
                    });
                    break;
                }
            case "/1":
                {
                    req.bodyHandler(v -> {
                        assertEquals(v, buffer);
                        req.response().end();
                    });
                    break;
                }
        }
    });
    startServer(testAddress);
    Promise<Void> l = Promise.promise();
    client.request(new RequestOptions(requestOptions).setURI("/0")).onComplete(onSuccess(req1 -> {
        req1.response(resp -> {
            complete();
        }).setChunked(true).sendHead(onSuccess(v -> {
            vertx.setPeriodic(1, id -> {
                req1.write(Buffer.buffer(TestUtils.randomAlphaString(512)));
                if (req1.writeQueueFull()) {
                    req1.writeQueueFull();
                    vertx.cancelTimer(id);
                    l.complete();
                }
            });
        }));
        l.future().onComplete(onSuccess(v -> {
            client.request(new RequestOptions(requestOptions).setURI("/1")).onComplete(onSuccess(req2 -> {
                req2.response(onSuccess(resp -> {
                    complete();
                })).setChunked(true);
                assertFalse(req2.writeQueueFull());
                req2.sendHead();
                waitUntil(req2::writeQueueFull);
                resumeLatch.complete(null);
                waitUntil(() -> !req2.writeQueueFull(), () -> {
                    req1.end();
                    req2.end(buffer);
                });
            }));
        }));
    }));
    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) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.junit.Test)

Aggregations

Promise (io.vertx.core.Promise)135 Future (io.vertx.core.Future)112 Handler (io.vertx.core.Handler)87 Buffer (io.vertx.core.buffer.Buffer)81 Vertx (io.vertx.core.Vertx)78 TimeUnit (java.util.concurrent.TimeUnit)77 List (java.util.List)75 HttpURLConnection (java.net.HttpURLConnection)66 Logger (org.slf4j.Logger)63 LoggerFactory (org.slf4j.LoggerFactory)63 Optional (java.util.Optional)62 Truth.assertThat (com.google.common.truth.Truth.assertThat)60 VertxTestContext (io.vertx.junit5.VertxTestContext)59 Test (org.junit.jupiter.api.Test)58 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)56 AsyncResult (io.vertx.core.AsyncResult)53 Timeout (io.vertx.junit5.Timeout)50 Map (java.util.Map)49 AtomicReference (java.util.concurrent.atomic.AtomicReference)46 Context (io.vertx.core.Context)43