Search in sources :

Example 61 with AsyncResult

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

the class FakeStreamTest method testAsyncEndDeferred.

@Test
public void testAsyncEndDeferred() {
    Promise<Void> end = Promise.promise();
    AtomicInteger ended = new AtomicInteger();
    AtomicReference<AsyncResult> endRes = new AtomicReference<>();
    stream.setEnd(end.future());
    stream.pause();
    stream.emit(3);
    stream.endHandler(v -> ended.incrementAndGet());
    stream.end(endRes::set);
    assertEquals(0, ended.get());
    assertNull(endRes.get());
    end.complete();
    assertEquals(0, ended.get());
    assertNull(endRes.get());
    stream.fetch(1);
    assertEquals(0, ended.get());
    assertNull(endRes.get());
    stream.fetch(1);
    assertEquals(1, ended.get());
    assertTrue(endRes.get().succeeded());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.Test)

Example 62 with AsyncResult

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

the class WebSocketTest method testInvalidHandshake.

// Check client response with the ws handler
private void testInvalidHandshake(Consumer<Handler<AsyncResult<HttpClientResponse>>> requestProvider, boolean expectEvent, boolean upgradeRequest, int expectedStatus) {
    client = vertx.createHttpClient(new HttpClientOptions().setMaxPoolSize(1));
    if (upgradeRequest) {
        server = vertx.createHttpServer().webSocketHandler(ws -> {
            // Check we can get notified
            // handshake fails after this method returns and does not reject the ws
            assertTrue(expectEvent);
        }).requestHandler(req -> {
            req.response().end();
        });
    } else {
        AtomicBoolean first = new AtomicBoolean();
        server = vertx.createHttpServer().requestHandler(req -> {
            if (first.compareAndSet(false, true)) {
                try {
                    req.toWebSocket();
                } catch (Exception e) {
                // Expected
                }
            } else {
                req.response().end();
            }
        });
    }
    server.listen(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, onSuccess(s -> {
        requestProvider.accept(onSuccess(resp -> {
            assertEquals(expectedStatus, resp.statusCode());
            resp.endHandler(v1 -> {
                // Make another request to check the connection remains usable
                client.request(new RequestOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST)).onComplete(onSuccess(req2 -> {
                    req2.send(onSuccess(resp2 -> {
                        resp2.endHandler(v2 -> {
                            testComplete();
                        });
                    }));
                }));
            });
        }));
    }));
}
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) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) IOException(java.io.IOException) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException)

Example 63 with AsyncResult

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

the class WebSocketTest method testTLS.

private void testTLS(Cert<?> clientCert, Trust<?> clientTrust, Cert<?> serverCert, Trust<?> serverTrust, boolean requireClientAuth, boolean serverUsesCrl, boolean clientTrustAll, boolean clientUsesCrl, boolean shouldPass, boolean clientSsl, boolean serverSsl, boolean sni, String[] enabledCipherSuites, BiConsumer<HttpClient, Handler<AsyncResult<WebSocket>>> wsProvider) throws Exception {
    HttpClientOptions options = new HttpClientOptions();
    options.setSsl(clientSsl);
    options.setTrustAll(clientTrustAll);
    if (clientUsesCrl) {
        options.addCrlPath("tls/root-ca/crl.pem");
    }
    options.setTrustOptions(clientTrust.get());
    options.setKeyCertOptions(clientCert.get());
    for (String suite : enabledCipherSuites) {
        options.addEnabledCipherSuite(suite);
    }
    client = vertx.createHttpClient(options);
    HttpServerOptions serverOptions = new HttpServerOptions();
    serverOptions.setSsl(serverSsl);
    serverOptions.setSni(sni);
    serverOptions.setTrustOptions(serverTrust.get());
    serverOptions.setKeyCertOptions(serverCert.get());
    if (requireClientAuth) {
        serverOptions.setClientAuth(ClientAuth.REQUIRED);
    }
    if (serverUsesCrl) {
        serverOptions.addCrlPath("tls/root-ca/crl.pem");
    }
    for (String suite : enabledCipherSuites) {
        serverOptions.addEnabledCipherSuite(suite);
    }
    server = vertx.createHttpServer(serverOptions.setPort(4043));
    server.webSocketHandler(ws -> {
        ws.handler(ws::write);
    });
    try {
        server.listen(ar -> {
            assertTrue(ar.succeeded());
            Handler<AsyncResult<WebSocket>> handler = ar2 -> {
                if (ar2.succeeded()) {
                    WebSocket ws = ar2.result();
                    if (clientSsl && sni) {
                        try {
                            Certificate clientPeerCert = ws.peerCertificates().get(0);
                            assertEquals("host2.com", TestUtils.cnOf(clientPeerCert));
                        } catch (Exception err) {
                            fail(err);
                        }
                    }
                    int size = 100;
                    Buffer received = Buffer.buffer();
                    ws.handler(data -> {
                        received.appendBuffer(data);
                        if (received.length() == size) {
                            ws.close();
                            testComplete();
                        }
                    });
                    Buffer buff = Buffer.buffer(TestUtils.randomByteArray(size));
                    ws.writeFrame(WebSocketFrame.binaryFrame(buff, true));
                } else {
                    if (shouldPass) {
                        ar2.cause().printStackTrace();
                        fail("Should not throw exception");
                    } else {
                        testComplete();
                    }
                }
            };
            wsProvider.accept(client, handler);
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    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) Buffer(io.vertx.core.buffer.Buffer) TestUtils.randomAlphaString(io.vertx.test.core.TestUtils.randomAlphaString) AsyncResult(io.vertx.core.AsyncResult) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) IOException(java.io.IOException) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) Certificate(java.security.cert.Certificate)

Example 64 with AsyncResult

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

the class Http2ServerTest method testPushPromise.

private void testPushPromise(Http2Headers requestHeaders, BiConsumer<HttpServerResponse, Handler<AsyncResult<HttpServerResponse>>> pusher, Consumer<Http2Headers> headerChecker) throws Exception {
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {
        Handler<AsyncResult<HttpServerResponse>> handler = ar -> {
            assertSameEventLoop(ctx, Vertx.currentContext());
            assertTrue(ar.succeeded());
            HttpServerResponse response = ar.result();
            response.end("the_content");
            assertIllegalStateException(() -> response.push(HttpMethod.GET, "/wibble2", resp -> {
            }));
        };
        pusher.accept(req.response(), handler);
    });
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        Http2ConnectionEncoder encoder = request.encoder;
        encoder.writeHeaders(request.context, id, requestHeaders, 0, true, request.context.newPromise());
        Map<Integer, Http2Headers> pushed = new HashMap<>();
        request.decoder.frameListener(new Http2FrameAdapter() {

            @Override
            public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception {
                pushed.put(promisedStreamId, headers);
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
                int delta = super.onDataRead(ctx, streamId, data, padding, endOfStream);
                String content = data.toString(StandardCharsets.UTF_8);
                vertx.runOnContext(v -> {
                    assertEquals(Collections.singleton(streamId), pushed.keySet());
                    assertEquals("the_content", content);
                    Http2Headers pushedHeaders = pushed.get(streamId);
                    headerChecker.accept(pushedHeaders);
                    testComplete();
                });
                return delta;
            }
        });
    });
    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) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) HashMap(java.util.HashMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsyncResult(io.vertx.core.AsyncResult)

Example 65 with AsyncResult

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

the class BareCommand method startVertx.

/**
 * Starts the vert.x instance.
 *
 * @return the created instance of vert.x
 */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
protected Vertx startVertx() {
    JsonObject optionsJson = getJsonFromFileOrString(vertxOptions, "options");
    EventBusOptions eventBusOptions;
    VertxBuilder builder;
    if (optionsJson == null) {
        eventBusOptions = getEventBusOptions();
        builder = new VertxBuilder();
    } else {
        eventBusOptions = getEventBusOptions(optionsJson.getJsonObject("eventBusOptions"));
        builder = new VertxBuilder(optionsJson);
    }
    options = builder.options();
    options.setEventBusOptions(eventBusOptions);
    beforeStartingVertx(options);
    configureFromSystemProperties.set(log);
    try {
        configureFromSystemProperties(options, VERTX_OPTIONS_PROP_PREFIX);
        if (options.getMetricsOptions() != null) {
            configureFromSystemProperties(options.getMetricsOptions(), METRICS_OPTIONS_PROP_PREFIX);
        }
        builder.init();
    } finally {
        configureFromSystemProperties.set(null);
    }
    Vertx instance;
    if (isClustered()) {
        log.info("Starting clustering...");
        eventBusOptions = options.getEventBusOptions();
        if (!Objects.equals(eventBusOptions.getHost(), EventBusOptions.DEFAULT_CLUSTER_HOST)) {
            clusterHost = eventBusOptions.getHost();
        }
        if (eventBusOptions.getPort() != EventBusOptions.DEFAULT_CLUSTER_PORT) {
            clusterPort = eventBusOptions.getPort();
        }
        if (!Objects.equals(eventBusOptions.getClusterPublicHost(), EventBusOptions.DEFAULT_CLUSTER_PUBLIC_HOST)) {
            clusterPublicHost = eventBusOptions.getClusterPublicHost();
        }
        if (eventBusOptions.getClusterPublicPort() != EventBusOptions.DEFAULT_CLUSTER_PUBLIC_PORT) {
            clusterPublicPort = eventBusOptions.getClusterPublicPort();
        }
        eventBusOptions.setHost(clusterHost).setPort(clusterPort).setClusterPublicHost(clusterPublicHost);
        if (clusterPublicPort != -1) {
            eventBusOptions.setClusterPublicPort(clusterPublicPort);
        }
        if (getHA()) {
            options.setHAEnabled(true);
            if (haGroup != null) {
                options.setHAGroup(haGroup);
            }
            if (quorum != -1) {
                options.setQuorumSize(quorum);
            }
        }
        CountDownLatch latch = new CountDownLatch(1);
        AtomicReference<AsyncResult<Vertx>> result = new AtomicReference<>();
        create(builder, ar -> {
            result.set(ar);
            latch.countDown();
        });
        try {
            if (!latch.await(2, TimeUnit.MINUTES)) {
                log.error("Timed out in starting clustered Vert.x");
                return null;
            }
        } catch (InterruptedException e) {
            log.error("Thread interrupted in startup");
            Thread.currentThread().interrupt();
            return null;
        }
        if (result.get().failed()) {
            log.error("Failed to form cluster", result.get().cause());
            return null;
        }
        instance = result.get().result();
    } else {
        instance = create(builder);
    }
    addShutdownHook(instance, log, finalAction);
    afterStartingVertx(instance);
    return instance;
}
Also used : JsonObject(io.vertx.core.json.JsonObject) EventBusOptions(io.vertx.core.eventbus.EventBusOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) VertxBuilder(io.vertx.core.impl.VertxBuilder) Vertx(io.vertx.core.Vertx) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncResult(io.vertx.core.AsyncResult)

Aggregations

AsyncResult (io.vertx.core.AsyncResult)162 Handler (io.vertx.core.Handler)106 Test (org.junit.Test)72 JsonObject (io.vertx.core.json.JsonObject)68 CountDownLatch (java.util.concurrent.CountDownLatch)62 Future (io.vertx.core.Future)59 List (java.util.List)49 RequestParameter (io.vertx.ext.web.api.RequestParameter)48 RequestParameters (io.vertx.ext.web.api.RequestParameters)48 HashMap (java.util.HashMap)45 Map (java.util.Map)42 IOException (java.io.IOException)41 ArrayList (java.util.ArrayList)40 Vertx (io.vertx.core.Vertx)35 Collectors (java.util.stream.Collectors)35 RoutingContext (io.vertx.ext.web.RoutingContext)28 Buffer (io.vertx.core.buffer.Buffer)24 StandardCharsets (java.nio.charset.StandardCharsets)23 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)23 Consumer (java.util.function.Consumer)23