Search in sources :

Example 86 with Promise

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

the class NodeInfoTest method testFailedFutureForUnknownNode.

@Test
public void testFailedFutureForUnknownNode() {
    startNodes(2);
    ClusterManager clusterManager = ((VertxInternal) vertices[0]).getClusterManager();
    // Create unknown node identifier
    String unknown = String.join("", clusterManager.getNodes());
    // Needed as callback might be done from non Vert.x thread
    disableThreadChecks();
    Promise<NodeInfo> promise = Promise.promise();
    clusterManager.getNodeInfo(unknown, promise);
    promise.future().onComplete(onFailure(t -> testComplete()));
    await();
}
Also used : VertxInternal(io.vertx.core.impl.VertxInternal) ClusterManager(io.vertx.core.spi.cluster.ClusterManager) Promise(io.vertx.core.Promise) Test(org.junit.Test) NodeInfo(io.vertx.core.spi.cluster.NodeInfo) FakeClusterManager(io.vertx.test.fakecluster.FakeClusterManager) VertxTestBase(io.vertx.test.core.VertxTestBase) VertxInternal(io.vertx.core.impl.VertxInternal) NodeInfo(io.vertx.core.spi.cluster.NodeInfo) ClusterManager(io.vertx.core.spi.cluster.ClusterManager) FakeClusterManager(io.vertx.test.fakecluster.FakeClusterManager) Test(org.junit.Test)

Example 87 with Promise

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

the class Http1xTLSTest method testSharedServer.

@Test
public void testSharedServer() throws Exception {
    int num = VertxOptions.DEFAULT_EVENT_LOOP_POOL_SIZE;
    Assume.assumeTrue(num > 1);
    List<String> expected = Arrays.asList("chunk-1", "chunk-2", "chunk-3");
    client = vertx.createHttpClient(new HttpClientOptions().setMaxPoolSize(num).setSsl(true).setTrustAll(true));
    AtomicInteger connCount = new AtomicInteger();
    List<String> sessionIds = Collections.synchronizedList(new ArrayList<>());
    client.connectionHandler(conn -> {
        sessionIds.add(ByteBufUtil.hexDump(conn.sslSession().getId()));
        connCount.incrementAndGet();
    });
    CountDownLatch listenLatch = new CountDownLatch(1);
    vertx.deployVerticle(() -> new AbstractVerticle() {

        HttpServer server;

        @Override
        public void start(Promise<Void> startPromise) {
            server = vertx.createHttpServer(new HttpServerOptions().setSsl(true).setKeyStoreOptions(Cert.SERVER_JKS.get()).setHost(DEFAULT_HTTPS_HOST).setPort(DEFAULT_HTTPS_PORT)).requestHandler(req -> {
                HttpServerResponse resp = req.response().setChunked(true);
                expected.forEach(resp::write);
                resp.end();
            });
            server.listen(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST).<Void>mapEmpty().onComplete(startPromise);
        }
    }, new DeploymentOptions().setInstances(num), onSuccess(v -> listenLatch.countDown()));
    awaitLatch(listenLatch);
    CountDownLatch connectionLatch = new CountDownLatch(num);
    for (int i = 0; i < num; i++) {
        client.request(HttpMethod.GET, DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, DEFAULT_TEST_URI).onComplete(onSuccess(request -> {
            connectionLatch.countDown();
        }));
        if (i == 0) {
            // Wait until the first connection is established to ensure other connections can reuse the session id
            waitUntil(() -> connectionLatch.getCount() == num - 1);
        }
    }
    awaitLatch(connectionLatch);
    assertEquals(num, sessionIds.size());
    assertEquals(1, new HashSet<>(sessionIds).size());
}
Also used : Arrays(java.util.Arrays) Promise(io.vertx.core.Promise) VertxOptions(io.vertx.core.VertxOptions) Trust(io.vertx.test.tls.Trust) Set(java.util.Set) Test(org.junit.Test) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBufUtil(io.netty.buffer.ByteBufUtil) NetServerOptions(io.vertx.core.net.NetServerOptions) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) Ignore(org.junit.Ignore) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractVerticle(io.vertx.core.AbstractVerticle) Cert(io.vertx.test.tls.Cert) Assume(org.junit.Assume) Collections(java.util.Collections) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractVerticle(io.vertx.core.AbstractVerticle) DeploymentOptions(io.vertx.core.DeploymentOptions) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 88 with Promise

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

the class Http1xClientConnectionTest method testResetStreamRequestSent.

@Test
public void testResetStreamRequestSent() throws Exception {
    waitFor(1);
    Promise<Void> continuation = Promise.promise();
    server.requestHandler(req -> {
        continuation.complete();
    });
    startServer(testAddress);
    client.connect(testAddress).onComplete(onSuccess(conn -> {
        AtomicInteger evictions = new AtomicInteger();
        conn.evictionHandler(v -> {
            evictions.incrementAndGet();
        });
        conn.createStream((ContextInternal) vertx.getOrCreateContext(), onSuccess(stream -> {
            Exception cause = new Exception();
            stream.closeHandler(v -> {
                assertEquals(1, evictions.get());
                complete();
            });
            continuation.future().onSuccess(v -> {
                stream.reset(cause);
            });
            stream.writeHead(new HttpRequestHead(HttpMethod.GET, "/", MultiMap.caseInsensitiveMultiMap(), "localhost:8080", "", null), false, Unpooled.EMPTY_BUFFER, false, new StreamPriority(), false, null);
        }));
    }));
    await();
}
Also used : HttpRequestHead(io.vertx.core.http.impl.HttpRequestHead) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Promise(io.vertx.core.Promise) MultiMap(io.vertx.core.MultiMap) ContextInternal(io.vertx.core.impl.ContextInternal) Test(org.junit.Test) Unpooled(io.netty.buffer.Unpooled) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContextInternal(io.vertx.core.impl.ContextInternal) HttpRequestHead(io.vertx.core.http.impl.HttpRequestHead) Test(org.junit.Test)

Example 89 with Promise

use of io.vertx.core.Promise in project hono by eclipse.

the class KafkaBasedCommandSender method sendCommand.

/**
 * {@inheritDoc}
 *
 * <p>
 * The replyId is not used in the Kafka based implementation. It can be set to {@code null}.
 * If set it will be ignored.
 * <p>
 * If the timeout duration is {@code null} then the default timeout value of
 * {@value DEFAULT_COMMAND_TIMEOUT_IN_MS} ms is used.
 */
@Override
public Future<DownstreamMessage<KafkaMessageContext>> sendCommand(final String tenantId, final String deviceId, final String command, final String contentType, final Buffer data, final String replyId, final Map<String, Object> properties, final Duration timeout, final SpanContext context) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(command);
    final long timeoutInMs = Optional.ofNullable(timeout).map(t -> {
        if (t.isNegative()) {
            throw new IllegalArgumentException("command timeout duration must be >= 0");
        }
        return t.toMillis();
    }).orElse(DEFAULT_COMMAND_TIMEOUT_IN_MS);
    final String correlationId = correlationIdSupplier.get();
    final Span span = TracingHelper.buildChildSpan(tracer, context, "send command and receive response", getClass().getSimpleName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(TracingHelper.TAG_TENANT_ID, tenantId).withTag(TracingHelper.TAG_DEVICE_ID, deviceId).withTag(TracingHelper.TAG_CORRELATION_ID, correlationId).start();
    final ExpiringCommandPromise expiringCommandPromise = new ExpiringCommandPromise(correlationId, timeoutInMs, // Remove the corresponding pending response entry if times out
    x -> removePendingCommandResponse(tenantId, correlationId), span);
    subscribeForCommandResponse(tenantId, span).compose(ok -> {
        // Store the correlation id and the expiring command promise
        pendingCommandResponses.computeIfAbsent(tenantId, k -> new ConcurrentHashMap<>()).put(correlationId, expiringCommandPromise);
        return sendCommand(tenantId, deviceId, command, contentType, data, correlationId, properties, true, "send command", span.context()).onSuccess(sent -> {
            LOGGER.debug("sent command [correlation-id: {}], waiting for response", correlationId);
            span.log("sent command, waiting for response");
        }).onFailure(error -> {
            LOGGER.debug("error sending command", error);
            // To ensure that the span is not already finished.
            if (!expiringCommandPromise.future().isComplete()) {
                TracingHelper.logError(span, "error sending command", error);
            }
            removePendingCommandResponse(tenantId, correlationId);
            expiringCommandPromise.tryCompleteAndCancelTimer(Future.failedFuture(error));
        });
    });
    return expiringCommandPromise.future().onComplete(o -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) MessagingKafkaConsumerConfigProperties(org.eclipse.hono.client.kafka.consumer.MessagingKafkaConsumerConfigProperties) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) MessagingKafkaProducerConfigProperties(org.eclipse.hono.client.kafka.producer.MessagingKafkaProducerConfigProperties) HonoKafkaConsumer(org.eclipse.hono.client.kafka.consumer.HonoKafkaConsumer) KafkaMessageContext(org.eclipse.hono.application.client.kafka.KafkaMessageContext) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Supplier(java.util.function.Supplier) Tags(io.opentracing.tag.Tags) CompositeFuture(io.vertx.core.CompositeFuture) StatusCodeMapper(org.eclipse.hono.client.StatusCodeMapper) Duration(java.time.Duration) Map(java.util.Map) TracingHelper(org.eclipse.hono.tracing.TracingHelper) AsyncResult(io.vertx.core.AsyncResult) AbstractKafkaBasedMessageSender(org.eclipse.hono.client.kafka.producer.AbstractKafkaBasedMessageSender) Consumer(org.apache.kafka.clients.consumer.Consumer) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Vertx(io.vertx.core.Vertx) Set(java.util.Set) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) UUID(java.util.UUID) KafkaRecordHelper(org.eclipse.hono.client.kafka.KafkaRecordHelper) MessageHelper(org.eclipse.hono.util.MessageHelper) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) List(java.util.List) KafkaProducerFactory(org.eclipse.hono.client.kafka.producer.KafkaProducerFactory) Buffer(io.vertx.core.buffer.Buffer) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) CommandSender(org.eclipse.hono.application.client.CommandSender) Optional(java.util.Optional) SendMessageTimeoutException(org.eclipse.hono.client.SendMessageTimeoutException) Span(io.opentracing.Span) Handler(io.vertx.core.Handler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Span(io.opentracing.Span)

Example 90 with Promise

use of io.vertx.core.Promise in project hono by eclipse.

the class AmqpServiceBase method startInsecureServer.

private Future<Void> startInsecureServer() {
    if (isInsecurePortEnabled()) {
        final int insecurePort = determineInsecurePort();
        final Promise<Void> result = Promise.promise();
        final ProtonServerOptions options = createInsecureServerOptions();
        insecureServer = createProtonServer(options).connectHandler(this::onRemoteConnectionOpenInsecurePort).listen(insecurePort, getConfig().getInsecurePortBindAddress(), bindAttempt -> {
            if (bindAttempt.succeeded()) {
                if (getInsecurePort() == getInsecurePortDefaultValue()) {
                    log.info("server listens on standard insecure port [{}:{}]", getInsecurePortBindAddress(), getInsecurePort());
                } else {
                    log.warn("server listens on non-standard insecure port [{}:{}], default is {}", getInsecurePortBindAddress(), getInsecurePort(), getInsecurePortDefaultValue());
                }
                result.complete();
            } else {
                log.error("cannot bind to insecure port", bindAttempt.cause());
                result.fail(bindAttempt.cause());
            }
        });
        return result.future();
    } else {
        log.info("insecure port is not enabled");
        return Future.succeededFuture();
    }
}
Also used : ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) ProtonServerOptions(io.vertx.proton.ProtonServerOptions) HashMap(java.util.HashMap) HonoUser(org.eclipse.hono.auth.HonoUser) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) Constants(org.eclipse.hono.util.Constants) ProtonServer(io.vertx.proton.ProtonServer) HonoProtonHelper(org.eclipse.hono.util.HonoProtonHelper) ArrayList(java.util.ArrayList) CompositeFuture(io.vertx.core.CompositeFuture) ProtonSession(io.vertx.proton.ProtonSession) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) Symbol(org.apache.qpid.proton.amqp.Symbol) Duration(java.time.Duration) Map(java.util.Map) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) AsyncResult(io.vertx.core.AsyncResult) WeakReference(java.lang.ref.WeakReference) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) Strings(org.eclipse.hono.util.Strings) Promise(io.vertx.core.Promise) ProtonHelper(io.vertx.proton.ProtonHelper) Instant(java.time.Instant) Activity(org.eclipse.hono.auth.Activity) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) Source(org.apache.qpid.proton.amqp.transport.Source) AbstractServiceBase(org.eclipse.hono.service.AbstractServiceBase) ProtonSender(io.vertx.proton.ProtonSender) ClaimsBasedAuthorizationService(org.eclipse.hono.service.auth.ClaimsBasedAuthorizationService) ProtonLink(io.vertx.proton.ProtonLink) AuthorizationService(org.eclipse.hono.service.auth.AuthorizationService) ProtonServerOptions(io.vertx.proton.ProtonServerOptions)

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