Search in sources :

Example 76 with Promise

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

the class Http2Test method testNonUpgradedH2CConnectionIsEvictedFromThePool.

@Test
public void testNonUpgradedH2CConnectionIsEvictedFromThePool() throws Exception {
    client.close();
    client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2));
    server.close();
    System.setProperty("vertx.disableH2c", "true");
    server = vertx.createHttpServer();
    try {
        Promise<Void> p = Promise.promise();
        AtomicBoolean first = new AtomicBoolean(true);
        server.requestHandler(req -> {
            if (first.compareAndSet(true, false)) {
                HttpConnection conn = req.connection();
                p.future().onComplete(ar -> {
                    conn.close();
                });
            }
            req.response().end();
        });
        startServer(testAddress);
        client.request(requestOptions).compose(req1 -> {
            req1.connection().closeHandler(v1 -> {
                vertx.runOnContext(v2 -> {
                    client.request(requestOptions).compose(req2 -> req2.send().compose(HttpClientResponse::body)).onComplete(onSuccess(b2 -> {
                        testComplete();
                    }));
                });
            });
            return req1.send().compose(resp -> {
                assertEquals(HttpVersion.HTTP_1_1, resp.version());
                return resp.body();
            });
        }).onComplete(onSuccess(b -> {
            p.complete();
        }));
        await();
    } finally {
        System.clearProperty("vertx.disableH2c");
    }
}
Also used : 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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Example 77 with Promise

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

the class NetClientImpl method close.

@Override
public void close(Promise<Void> completion) {
    ChannelGroupFuture fut = channelGroup.close();
    if (metrics != null) {
        PromiseInternal<Void> p = (PromiseInternal) Promise.promise();
        fut.addListener(p);
        p.future().<Void>compose(v -> {
            metrics.close();
            return Future.succeededFuture();
        }).onComplete(completion);
    } else {
        fut.addListener((PromiseInternal) completion);
    }
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ContextInternal(io.vertx.core.impl.ContextInternal) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) Closeable(io.vertx.core.Closeable) ProxyOptions(io.vertx.core.net.ProxyOptions) ChannelGroup(io.netty.channel.group.ChannelGroup) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Predicate(java.util.function.Predicate) Promise(io.vertx.core.Promise) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) PartialPooledByteBufAllocator(io.vertx.core.buffer.impl.PartialPooledByteBufAllocator) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) NetClientOptions(io.vertx.core.net.NetClientOptions) Channel(io.netty.channel.Channel) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture)

Example 78 with Promise

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

the class NetClientImpl method connectInternal.

public void connectInternal(ProxyOptions proxyOptions, SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, boolean useAlpn, boolean registerWriteHandlers, Promise<NetSocket> connectHandler, ContextInternal context, int remainingAttempts) {
    checkClosed();
    EventLoop eventLoop = context.nettyEventLoop();
    if (eventLoop.inEventLoop()) {
        Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoop);
        bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
        vertx.transport().configure(options, remoteAddress.isDomainSocket(), bootstrap);
        ChannelProvider channelProvider = new ChannelProvider(bootstrap, sslHelper, context).proxyOptions(proxyOptions);
        channelProvider.handler(ch -> connected(context, ch, connectHandler, remoteAddress, channelProvider.applicationProtocol(), registerWriteHandlers));
        io.netty.util.concurrent.Future<Channel> fut = channelProvider.connect(remoteAddress, peerAddress, serverName, ssl, useAlpn);
        fut.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Channel>>) future -> {
            if (!future.isSuccess()) {
                Throwable cause = future.cause();
                boolean connectError = cause instanceof ConnectException || cause instanceof FileNotFoundException;
                if (connectError && (remainingAttempts > 0 || remainingAttempts == -1)) {
                    context.emit(v -> {
                        log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
                        vertx.setTimer(options.getReconnectInterval(), tid -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
                    });
                } else {
                    failed(context, null, cause, connectHandler);
                }
            }
        });
    } else {
        eventLoop.execute(() -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts));
    }
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ContextInternal(io.vertx.core.impl.ContextInternal) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) Closeable(io.vertx.core.Closeable) ProxyOptions(io.vertx.core.net.ProxyOptions) ChannelGroup(io.netty.channel.group.ChannelGroup) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Predicate(java.util.function.Predicate) Promise(io.vertx.core.Promise) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) PartialPooledByteBufAllocator(io.vertx.core.buffer.impl.PartialPooledByteBufAllocator) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) NetClientOptions(io.vertx.core.net.NetClientOptions) Channel(io.netty.channel.Channel) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) Channel(io.netty.channel.Channel) FileNotFoundException(java.io.FileNotFoundException) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) Future(io.vertx.core.Future) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) ConnectException(java.net.ConnectException)

Example 79 with Promise

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

the class WebSocketTest method testWorker.

@Test
public void testWorker() {
    waitFor(2);
    DeploymentOptions deploymentOptions = new DeploymentOptions().setWorker(true);
    vertx.deployVerticle(() -> new AbstractVerticle() {

        @Override
        public void start(Promise<Void> startPromise) {
            server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT));
            server.webSocketHandler(ws -> {
                assertTrue(Context.isOnWorkerThread());
                ws.handler(msg -> {
                    assertTrue(Context.isOnWorkerThread());
                    ws.write(Buffer.buffer("pong"));
                });
                ws.endHandler(v -> {
                    assertTrue(Context.isOnWorkerThread());
                    complete();
                });
            });
            server.listen().<Void>mapEmpty().onComplete(startPromise);
        }
    }, deploymentOptions, onSuccess(serverID -> {
        vertx.deployVerticle(() -> new AbstractVerticle() {

            @Override
            public void start() {
                client = vertx.createHttpClient();
                client.webSocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", onSuccess(ws -> {
                    assertTrue(Context.isOnWorkerThread());
                    ws.write(Buffer.buffer("ping"));
                    ws.handler(buf -> {
                        assertTrue(Context.isOnWorkerThread());
                        ws.end();
                    });
                    ws.endHandler(v -> {
                        assertTrue(Context.isOnWorkerThread());
                        complete();
                    });
                }));
            }
        }, deploymentOptions, onSuccess(id -> {
        }));
    }));
    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) DeploymentOptions(io.vertx.core.DeploymentOptions) AbstractVerticle(io.vertx.core.AbstractVerticle) Test(org.junit.Test)

Example 80 with Promise

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

the class ConnectionPoolTest method testRecycleRemovedConnection.

@Test
public void testRecycleRemovedConnection() throws Exception {
    EventLoopContext context = vertx.createEventLoopContext();
    ConnectionManager mgr = new ConnectionManager();
    ConnectionPool<Connection> pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10);
    Connection expected1 = new Connection();
    Promise<Lease<Connection>> promise = Promise.promise();
    pool.acquire(context, 0, promise);
    ConnectionRequest request1 = mgr.assertRequest();
    request1.connect(expected1, 0);
    CountDownLatch latch = new CountDownLatch(1);
    promise.future().onComplete(onSuccess(lease -> {
        request1.listener.onRemove();
        lease.recycle();
        latch.countDown();
    }));
    awaitLatch(latch);
    Connection expected2 = new Connection();
    pool.acquire(context, 0, onSuccess(lease -> {
        assertSame(expected2, lease.get());
        assertSame(context, Vertx.currentContext());
        testComplete();
    }));
    ConnectionRequest request2 = mgr.assertRequest();
    request2.connect(expected2, 0);
    await();
}
Also used : Arrays(java.util.Arrays) VertxInternal(io.vertx.core.impl.VertxInternal) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ConnectionPoolTooBusyException(io.vertx.core.http.ConnectionPoolTooBusyException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) CompletableFuture(java.util.concurrent.CompletableFuture) Future(io.vertx.core.Future) VertxTestBase(io.vertx.test.core.VertxTestBase) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) EventLoopContext(io.vertx.core.impl.EventLoopContext) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Ignore(org.junit.Ignore) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WorkerContext(io.vertx.core.impl.WorkerContext) AsyncResult(io.vertx.core.AsyncResult) Queue(java.util.Queue) Handler(io.vertx.core.Handler) CountDownLatch(java.util.concurrent.CountDownLatch) EventLoopContext(io.vertx.core.impl.EventLoopContext) 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