Java Code Examples for io.vertx.core.CompositeFuture#all()

The following examples show how to use io.vertx.core.CompositeFuture#all() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Helps asserting device data.
 *
 * @param tenant The tenant.
 * @param deviceId The device ID.
 * @param gatewayId The optional gateway ID
 * @param managementAssertions assertions for the management data.
 * @param adapterAssertions assertions for the adapter data.
 * @return A new future that will succeed when the read/get operations succeed and the assertions are valid.
 *         Otherwise the future must fail.
 */
protected Future<?> assertDevice(final String tenant, final String deviceId, final Optional<String> gatewayId,
        final Handler<OperationResult<Device>> managementAssertions,
        final Handler<RegistrationResult> adapterAssertions) {

    // read management data

    final Future<OperationResult<Device>> f1 = getDeviceManagementService()
            .readDevice(tenant, deviceId, NoopSpan.INSTANCE);

    // read adapter data

    final Future<RegistrationResult> f2 = gatewayId
            .map(id -> getRegistrationService().assertRegistration(tenant, deviceId, id))
            .orElseGet(() -> getRegistrationService().assertRegistration(tenant, deviceId));
    return CompositeFuture.all(
            f1.map(r -> {
                managementAssertions.handle(r);
                return null;
            }),
            f2.map(r -> {
                adapterAssertions.handle(r);
                return null;
            }));
}
 
Example 2
Source File: AbstractApplication.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Deploys the service instances.
 *
 * @param maxInstances The number of instances to deploy.
 * @return A future indicating the outcome of the operation. The future will
 *         be succeeded if the service instances have been deployed successfully.
 */
private Future<?> deployServiceVerticles(final int maxInstances) {

    @SuppressWarnings("rawtypes")
    final List<Future> deploymentTracker = new ArrayList<>();

    for (final ObjectFactory<? extends AbstractServiceBase<?>> serviceFactory : serviceFactories) {

        for (int i = 1; i <= maxInstances; i++) {
            final Promise<String> deployPromise = Promise.promise();
            final AbstractServiceBase<?> serviceInstance = serviceFactory.getObject();
            preDeploy(serviceInstance);
            log.debug("deploying service instance #{} [type: {}]", i, serviceInstance.getClass().getName());
            getVertx().deployVerticle(serviceInstance, deployPromise);
            deploymentTracker.add(deployPromise.future().map(id -> {
                postDeploy(serviceInstance);
                return id;
            }));
        }
    }

    return CompositeFuture.all(deploymentTracker);
}
 
Example 3
Source File: RouteDefinitionTest.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Test
void isAsyncTest() {

	Future<String> out = Future.future();
	CompositeFuture out2 = CompositeFuture.all(out, out);

	CompletableFuture<String> complete = new CompletableFuture<>();

	assertTrue(RouteDefinition.isAsync(out.getClass()));
	assertTrue(RouteDefinition.isAsync(out2.getClass()));

	assertFalse(RouteDefinition.isAsync(complete.getClass()));
	assertFalse(RouteDefinition.isAsync(String.class));
}
 
Example 4
Source File: VertxHttp11ClientReconnectTest.java    From feign-vertx with Apache License 2.0 5 votes vote down vote up
/**
 * This issues ten requests to the server via a shared
 * long lived Feign Vertx client.
 * @return
 */
private CompositeFuture requestVolley() {
  List<Future> requests = new ArrayList<>(10);

  // Initiate 10 requests
  for( int i=0; i<10; i++ ) {
    Future<feign.Response> request = Future.future();
    client.hello().setHandler(request.completer());
    requests.add(request);
  }

  // Composite future for all of the requests
  return CompositeFuture.all(requests);
}
 
Example 5
Source File: MongoDbBasedCredentialsService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private CompositeFuture createIndices() {
    final String authIdKey = String.format("%s.%s", MongoDbDeviceRegistryUtils.FIELD_CREDENTIALS,
            RegistryManagementConstants.FIELD_AUTH_ID);
    final String credentialsTypeKey = String.format("%s.%s", MongoDbDeviceRegistryUtils.FIELD_CREDENTIALS,
            RegistryManagementConstants.FIELD_TYPE);

    return CompositeFuture.all(
            // index based on tenantId & deviceId
            mongoDbCallExecutor.createCollectionIndex(
                    config.getCollectionName(),
                    new JsonObject()
                            .put(RegistryManagementConstants.FIELD_PAYLOAD_TENANT_ID, 1)
                            .put(RegistryManagementConstants.FIELD_PAYLOAD_DEVICE_ID, 1),
                    new IndexOptions().unique(true),
                    INDEX_CREATION_MAX_RETRIES),
            // index based on tenantId, authId & type
            mongoDbCallExecutor.createCollectionIndex(
                    config.getCollectionName(),
                    new JsonObject()
                            .put(RegistryManagementConstants.FIELD_PAYLOAD_TENANT_ID, 1)
                            .put(authIdKey, 1)
                            .put(credentialsTypeKey, 1),
                    new IndexOptions().unique(true)
                            .partialFilterExpression(new JsonObject()
                                    .put(authIdKey, new JsonObject().put("$exists", true))
                                    .put(credentialsTypeKey, new JsonObject().put("$exists", true))),
                    INDEX_CREATION_MAX_RETRIES));
}
 
Example 6
Source File: AbstractProtocolAdapterBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<?> closeServiceClients() {

        @SuppressWarnings("rawtypes")
        final List<Future> results = new ArrayList<>();
        results.add(disconnectFromService(downstreamSenderFactory));
        results.add(disconnectFromService(tenantClientFactory));
        results.add(disconnectFromService(registrationClientFactory));
        results.add(disconnectFromService(credentialsClientFactory));
        results.add(disconnectFromService(commandConsumerFactory));
        if (deviceConnectionClientFactory instanceof ConnectionLifecycle) {
            results.add(disconnectFromService((ConnectionLifecycle<?>) deviceConnectionClientFactory));
        }
        return CompositeFuture.all(results);
    }
 
Example 7
Source File: Receiver.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private CompositeFuture createConsumer(final HonoConnection connection) {

        final Handler<Void> closeHandler = closeHook -> {
            log.info("close handler of consumer is called");
            vertx.setTimer(connectionRetryInterval, reconnect -> {
                log.info("attempting to re-open the consumer link ...");
                createConsumer(connection);
            });
        };

        @SuppressWarnings("rawtypes")
        final List<Future> consumerFutures = new ArrayList<>();
        if (messageType.equals(TYPE_EVENT) || messageType.equals(TYPE_ALL)) {
            consumerFutures.add(
                    clientFactory.createEventConsumer(tenantId, msg -> {
                        messageHandler.accept(TYPE_EVENT, msg);
                    }, closeHandler));
        }

        if (messageType.equals(TYPE_TELEMETRY) || messageType.equals(TYPE_ALL)) {
            consumerFutures.add(
                    clientFactory.createTelemetryConsumer(tenantId, msg -> {
                        messageHandler.accept(TYPE_TELEMETRY, msg);
                    }, closeHandler));
        }

        if (consumerFutures.isEmpty()) {
            consumerFutures.add(Future.failedFuture(
                    String.format(
                            "Invalid message type [\"%s\"]. Valid types are \"telemetry\", \"event\" or \"all\"",
                            messageType)));
        }
        return CompositeFuture.all(consumerFutures);
    }
 
Example 8
Source File: RuntimeVerticle.java    From kiqr with Apache License 2.0 4 votes vote down vote up
private Future deployVerticles(AbstractVerticle... verticles) {


        Stream<AbstractVerticle> stream = Arrays.stream(verticles);

        List<Future> futures = stream
                .map(verticle -> {

                    Future<String> future = Future.<String>future();

                    vertx.deployVerticle(verticle, future.completer());

                    return future;
                })
                .map(future -> (Future) future)
                .collect(toList());

        return CompositeFuture.all(futures);

    }
 
Example 9
Source File: FileBasedDeviceBackend.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
Future<?> saveToFile() {
    return CompositeFuture.all(
            this.registrationService.saveToFile(),
            this.credentialsService.saveToFile());
}
 
Example 10
Source File: FileBasedDeviceBackend.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
Future<?> loadFromFile() {
    return CompositeFuture.all(
            this.registrationService.loadRegistrationData(),
            this.credentialsService.loadCredentials());
}
 
Example 11
Source File: Application.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Future<?> deployRequiredVerticles(final int maxInstances) {

    return CompositeFuture.all(deployVerticle(serviceImplementation), deployVerticle(authService));
}
 
Example 12
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Future<Void> uploadMessage(
        final MqttContext ctx,
        final TenantObject tenantObject,
        final String deviceId,
        final Buffer payload,
        final Future<DownstreamSender> senderTracker,
        final MetricsTags.EndpointType endpoint) {

    if (!isPayloadOfIndicatedType(payload, ctx.contentType())) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                String.format("Content-Type %s does not match payload", ctx.contentType())));
    }

    final Span currentSpan = TracingHelper.buildChildSpan(tracer, ctx.getTracingContext(),
            "upload " + endpoint, getTypeName())
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
            .withTag(TracingHelper.TAG_TENANT_ID, tenantObject.getTenantId())
            .withTag(TracingHelper.TAG_DEVICE_ID, deviceId)
            .withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), ctx.authenticatedDevice() != null)
            .start();

    final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenantObject.getTenantId(), deviceId,
            ctx.authenticatedDevice(), currentSpan.context());
    final Future<?> tenantValidationTracker = CompositeFuture.all(
            isAdapterEnabled(tenantObject),
            checkMessageLimit(tenantObject, payload.length(), currentSpan.context()));

    return CompositeFuture.all(tokenTracker, tenantValidationTracker, senderTracker).compose(ok -> {

        final DownstreamSender sender = senderTracker.result();
        final Message downstreamMessage = newMessage(
                ResourceIdentifier.from(endpoint.getCanonicalName(), tenantObject.getTenantId(), deviceId),
                ctx.message().topicName(),
                ctx.contentType(),
                payload,
                tenantObject,
                tokenTracker.result(),
                null,
                EndpointType.EVENT.equals(endpoint) ? getTimeToLive(ctx.propertyBag()) : null);

        addRetainAnnotation(ctx, downstreamMessage, currentSpan);
        customizeDownstreamMessage(downstreamMessage, ctx);

        if (ctx.isAtLeastOnce()) {
            return sender.sendAndWaitForOutcome(downstreamMessage, currentSpan.context());
        } else {
            return sender.send(downstreamMessage, currentSpan.context());
        }
    }).compose(delivery -> {

        log.trace("successfully processed message [topic: {}, QoS: {}] from device [tenantId: {}, deviceId: {}]",
                ctx.message().topicName(), ctx.message().qosLevel(), tenantObject.getTenantId(), deviceId);
        // check that the remote MQTT client is still connected before sending PUBACK
        if (ctx.isAtLeastOnce() && ctx.deviceEndpoint().isConnected()) {
            currentSpan.log("sending PUBACK");
            ctx.acknowledge();
        }
        currentSpan.finish();
        return Future.<Void> succeededFuture();

    }).recover(t -> {

        if (ClientErrorException.class.isInstance(t)) {
            final ClientErrorException e = (ClientErrorException) t;
            log.debug("cannot process message [endpoint: {}] from device [tenantId: {}, deviceId: {}]: {} - {}",
                    endpoint, tenantObject.getTenantId(), deviceId, e.getErrorCode(), e.getMessage());
        } else {
            log.debug("cannot process message [endpoint: {}] from device [tenantId: {}, deviceId: {}]",
                    endpoint, tenantObject.getTenantId(), deviceId, t);
        }
        TracingHelper.logError(currentSpan, t);
        currentSpan.finish();
        return Future.failedFuture(t);
    });
}