Search in sources :

Example 61 with Promise

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

the class AbstractTenantManagementService method updateTenant.

@Override
public final Future<OperationResult<Void>> updateTenant(final String tenantId, final Tenant tenantObj, final Optional<String> resourceVersion, final Span span) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(tenantObj);
    Objects.requireNonNull(resourceVersion);
    Objects.requireNonNull(span);
    final Promise<Void> tenantCheck = Promise.promise();
    try {
        tenantObj.assertTrustAnchorIdUniquenessAndCreateMissingIds();
        tenantCheck.complete();
    } catch (final IllegalStateException e) {
        log.debug("error updating tenant", e);
        TracingHelper.logError(span, e);
        tenantCheck.fail(new ClientErrorException(tenantId, HttpURLConnection.HTTP_BAD_REQUEST, e.getMessage()));
    }
    return tenantCheck.future().compose(ok -> processUpdateTenant(tenantId, tenantObj, resourceVersion, span)).onSuccess(result -> NotificationEventBusSupport.sendNotification(vertx, new TenantChangeNotification(LifecycleChange.UPDATE, tenantId, Instant.now(), tenantObj.isEnabled()))).recover(t -> DeviceRegistryUtils.mapError(t, tenantId));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Sort(org.eclipse.hono.service.management.Sort) SearchResult(org.eclipse.hono.service.management.SearchResult) TenantManagementService(org.eclipse.hono.service.management.tenant.TenantManagementService) TracingHelper(org.eclipse.hono.tracing.TracingHelper) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) Logger(org.slf4j.Logger) Promise(io.vertx.core.Promise) TenantWithId(org.eclipse.hono.service.management.tenant.TenantWithId) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Instant(java.time.Instant) Result(org.eclipse.hono.service.management.Result) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Id(org.eclipse.hono.service.management.Id) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification)

Example 62 with Promise

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

the class KafkaBasedInternalCommandConsumer method createTopic.

private Future<Void> createTopic() {
    final Promise<Void> promise = Promise.promise();
    final String topicName = getTopicName();
    // create topic with unspecified replication factor - broker "default.replication.factor" should be used
    final NewTopic newTopic = new NewTopic(topicName, Optional.of(NUM_PARTITIONS), Optional.empty());
    adminClient.createTopics(List.of(newTopic)).all().whenComplete((v, ex) -> {
        context.runOnContext(v1 -> Optional.ofNullable(ex).filter(e -> !(e instanceof TopicExistsException)).ifPresentOrElse(promise::fail, promise::complete));
    });
    return promise.future().onSuccess(v -> LOG.debug("created topic [{}]", topicName)).onFailure(thr -> LOG.error("error creating topic [{}]", topicName, thr));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) MessagingKafkaConsumerConfigProperties(org.eclipse.hono.client.kafka.consumer.MessagingKafkaConsumerConfigProperties) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CommandHandlerWrapper(org.eclipse.hono.client.command.CommandHandlerWrapper) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Supplier(java.util.function.Supplier) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) KafkaClientFactory(org.eclipse.hono.client.kafka.KafkaClientFactory) Context(io.vertx.core.Context) NoConsumerException(org.eclipse.hono.client.NoConsumerException) CompositeFuture(io.vertx.core.CompositeFuture) Status(io.vertx.ext.healthchecks.Status) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) KafkaClientMetricsSupport(org.eclipse.hono.client.kafka.metrics.KafkaClientMetricsSupport) Map(java.util.Map) KafkaAdminClientConfigProperties(org.eclipse.hono.client.kafka.KafkaAdminClientConfigProperties) Admin(org.apache.kafka.clients.admin.Admin) CommandHandlers(org.eclipse.hono.client.command.CommandHandlers) KafkaTracingHelper(org.eclipse.hono.client.kafka.tracing.KafkaTracingHelper) CommonClientConfigs(org.apache.kafka.clients.CommonClientConfigs) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) NewTopic(org.apache.kafka.clients.admin.NewTopic) CommandContext(org.eclipse.hono.client.command.CommandContext) Vertx(io.vertx.core.Vertx) Set(java.util.Set) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) KafkaRecordHelper(org.eclipse.hono.client.kafka.KafkaRecordHelper) TenantClient(org.eclipse.hono.client.registry.TenantClient) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) InternalCommandConsumer(org.eclipse.hono.client.command.InternalCommandConsumer) SpanContext(io.opentracing.SpanContext) TopicPartition(io.vertx.kafka.client.common.TopicPartition) Objects(java.util.Objects) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) List(java.util.List) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) Buffer(io.vertx.core.buffer.Buffer) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) Optional(java.util.Optional) Span(io.opentracing.Span) KafkaConsumer(io.vertx.kafka.client.consumer.KafkaConsumer) NewTopic(org.apache.kafka.clients.admin.NewTopic) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException)

Example 63 with Promise

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

the class HonoKafkaConsumer method start.

@Override
public Future<Void> start() {
    context = vertx.getOrCreateContext();
    final Promise<Void> startPromise = Promise.promise();
    runOnContext(v -> {
        // create KafkaConsumer here so that it is created in the Vert.x context of the start() method (KafkaConsumer uses vertx.getOrCreateContext())
        Optional.ofNullable(kafkaConsumerSupplier).map(supplier -> Future.succeededFuture(KafkaConsumer.create(vertx, supplier.get()))).orElseGet(() -> {
            final KafkaClientFactory kafkaClientFactory = new KafkaClientFactory(vertx);
            return kafkaClientFactory.createKafkaConsumerWithRetries(consumerConfig, String.class, Buffer.class, consumerCreationRetriesTimeout);
        }).onFailure(thr -> {
            log.error("error creating consumer [client-id: {}]", getClientId(), thr);
            startPromise.fail(thr);
        }).onSuccess(consumer -> {
            kafkaConsumer = consumer;
            Optional.ofNullable(metricsSupport).ifPresent(ms -> ms.registerKafkaConsumer(kafkaConsumer.unwrap()));
            kafkaConsumer.handler(record -> {
                if (!startPromise.future().isComplete()) {
                    log.debug("postponing record handling until start() is completed [topic: {}, partition: {}, offset: {}]", record.topic(), record.partition(), record.offset());
                }
                startPromise.future().onSuccess(v2 -> {
                    if (respectTtl && KafkaRecordHelper.isTtlElapsed(record.headers())) {
                        onRecordHandlerSkippedForExpiredRecord(record);
                    } else {
                        try {
                            recordHandler.handle(record);
                        } catch (final Exception e) {
                            log.warn("error handling record [topic: {}, partition: {}, offset: {}, headers: {}]", record.topic(), record.partition(), record.offset(), record.headers(), e);
                        }
                    }
                });
            });
            kafkaConsumer.batchHandler(this::onBatchOfRecordsReceived);
            kafkaConsumer.exceptionHandler(error -> log.error("consumer error occurred [client-id: {}]", getClientId(), error));
            installRebalanceListeners();
            // subscribe and wait for rebalance to make sure that when start() completes,
            // the consumer is actually ready to receive records already
            // let polls finish quickly until start() is completed
            kafkaConsumer.asStream().pollTimeout(Duration.ofMillis(10));
            subscribeAndWaitForRebalance().onSuccess(v2 -> {
                kafkaConsumer.asStream().pollTimeout(pollTimeout);
                logSubscribedTopicsOnStartComplete();
            }).onComplete(startPromise);
        });
    });
    return startPromise.future();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Lifecycle(org.eclipse.hono.util.Lifecycle) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RegisterForReflection(io.quarkus.runtime.annotations.RegisterForReflection) KafkaConsumerRecords(io.vertx.kafka.client.consumer.KafkaConsumerRecords) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) KafkaClientFactory(org.eclipse.hono.client.kafka.KafkaClientFactory) Context(io.vertx.core.Context) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) Helper(io.vertx.kafka.client.common.impl.Helper) KafkaClientMetricsSupport(org.eclipse.hono.client.kafka.metrics.KafkaClientMetricsSupport) Duration(java.time.Duration) Map(java.util.Map) Pair(org.eclipse.hono.util.Pair) KafkaReadStreamImpl(io.vertx.kafka.client.consumer.impl.KafkaReadStreamImpl) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) Consumer(org.apache.kafka.clients.consumer.Consumer) Futures(org.eclipse.hono.util.Futures) Logger(org.slf4j.Logger) Collection(java.util.Collection) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Set(java.util.Set) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) UUID(java.util.UUID) KafkaRecordHelper(org.eclipse.hono.client.kafka.KafkaRecordHelper) Field(java.lang.reflect.Field) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) TopicPartition(io.vertx.kafka.client.common.TopicPartition) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) ConsumerRebalanceListener(org.apache.kafka.clients.consumer.ConsumerRebalanceListener) List(java.util.List) Stream(java.util.stream.Stream) Metrics(org.apache.kafka.common.metrics.Metrics) Buffer(io.vertx.core.buffer.Buffer) CooperativeStickyAssignor(org.apache.kafka.clients.consumer.CooperativeStickyAssignor) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) Optional(java.util.Optional) KafkaConsumer(io.vertx.kafka.client.consumer.KafkaConsumer) Pattern(java.util.regex.Pattern) Handler(io.vertx.core.Handler) KafkaClientFactory(org.eclipse.hono.client.kafka.KafkaClientFactory) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Example 64 with Promise

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

the class Application method doStart.

@Override
protected void doStart() {
    if (!(authenticationService instanceof Verticle)) {
        throw new IllegalStateException("Authentication service must be a vert.x Verticle");
    }
    LOG.info("adding common tags to meter registry");
    meterRegistry.config().commonTags(MetricsTags.forService(Constants.SERVICE_NAME_DEVICE_REGISTRY));
    LOG.info("deploying {} {} instances ...", appConfig.getMaxInstances(), getComponentName());
    final CompletableFuture<Void> startup = new CompletableFuture<>();
    // deploy authentication service (once only)
    final Promise<String> authServiceDeploymentTracker = Promise.promise();
    vertx.deployVerticle((Verticle) authenticationService, authServiceDeploymentTracker);
    // deploy notification sender (once only)
    final Promise<String> notificationSenderDeploymentTracker = Promise.promise();
    vertx.deployVerticle(new WrappedLifecycleComponentVerticle(notificationSender), notificationSenderDeploymentTracker);
    // deploy AMQP 1.0 server
    final Promise<String> amqpServerDeploymentTracker = Promise.promise();
    vertx.deployVerticle(() -> amqpServerFactory.newServer(), new DeploymentOptions().setInstances(appConfig.getMaxInstances()), amqpServerDeploymentTracker);
    // deploy HTTP server
    final Promise<String> httpServerDeploymentTracker = Promise.promise();
    vertx.deployVerticle(() -> httpServerFactory.newServer(), new DeploymentOptions().setInstances(appConfig.getMaxInstances()), httpServerDeploymentTracker);
    CompositeFuture.all(authServiceDeploymentTracker.future(), notificationSenderDeploymentTracker.future(), amqpServerDeploymentTracker.future(), httpServerDeploymentTracker.future()).onSuccess(ok -> registerHealthCheckProvider(authenticationService)).compose(s -> healthCheckServer.start()).onSuccess(ok -> startup.complete(null)).onFailure(t -> startup.completeExceptionally(t));
    startup.join();
}
Also used : NotificationSender(org.eclipse.hono.notification.NotificationSender) Logger(org.slf4j.Logger) Promise(io.vertx.core.Promise) AuthenticationService(org.eclipse.hono.service.auth.AuthenticationService) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) Verticle(io.vertx.core.Verticle) Constants(org.eclipse.hono.util.Constants) Inject(javax.inject.Inject) AbstractServiceApplication(org.eclipse.hono.service.quarkus.AbstractServiceApplication) CompositeFuture(io.vertx.core.CompositeFuture) DeploymentOptions(io.vertx.core.DeploymentOptions) ApplicationScoped(javax.enterprise.context.ApplicationScoped) WrappedLifecycleComponentVerticle(org.eclipse.hono.util.WrappedLifecycleComponentVerticle) Verticle(io.vertx.core.Verticle) WrappedLifecycleComponentVerticle(org.eclipse.hono.util.WrappedLifecycleComponentVerticle) CompletableFuture(java.util.concurrent.CompletableFuture) WrappedLifecycleComponentVerticle(org.eclipse.hono.util.WrappedLifecycleComponentVerticle) DeploymentOptions(io.vertx.core.DeploymentOptions)

Example 65 with Promise

use of io.vertx.core.Promise in project vertx-examples by vert-x3.

the class Server method start.

@Override
public void start() throws Exception {
    // The rcp service
    EmptyPingPongServiceGrpc.EmptyPingPongServiceVertxImplBase service = new EmptyPingPongServiceGrpc.EmptyPingPongServiceVertxImplBase() {

        @Override
        public void emptyCall(EmptyProtos.Empty request, Promise<EmptyProtos.Empty> future) {
            future.complete(EmptyProtos.Empty.newBuilder().build());
        }
    };
    // Create the server
    VertxServer rpcServer = VertxServerBuilder.forPort(vertx, 8080).addService(service).build();
    // start the server
    rpcServer.start(ar -> {
        if (ar.failed()) {
            ar.cause().printStackTrace();
        }
    });
}
Also used : Promise(io.vertx.core.Promise) EmptyPingPongServiceGrpc(io.vertx.example.grpc.EmptyPingPongServiceGrpc) VertxServer(io.vertx.grpc.VertxServer) EmptyProtos(io.vertx.example.grpc.EmptyProtos)

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