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));
}
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));
}
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();
}
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();
}
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();
}
});
}
Aggregations