Example usage for io.vertx.core Future result

List of usage examples for io.vertx.core Future result

Introduction

In this page you can find the example usage for io.vertx.core Future result.

Prototype

@Override
T result();

Source Link

Document

The result of the operation.

Usage

From source file:com.dinstone.vertx.web.core.AbstractRouteResolver.java

License:Apache License

private static Handler<RoutingContext> asyncHandler(final Object service, final RouteDefinition definition,
        RouterContext routerContext) {/*w  w  w  . j  av  a 2 s .  c  o m*/

    return context -> {
        try {
            Object[] args = prepareArguments(context, definition, routerContext);
            Object result = definition.getMethod().invoke(service, args);

            if (result instanceof Future) {
                Future<?> future = (Future<?>) result;
                // wait for future to complete ... don't block vertx event bus in the mean time
                future.setHandler(handler -> {
                    if (future.succeeded()) {
                        try {
                            Object futureResult = future.result();
                            handleResponse(futureResult, context, definition, routerContext);
                        } catch (Throwable e) {
                            handleException(e, context, definition, routerContext);
                        }
                    } else {
                        handleException(future.cause(), context, definition, routerContext);
                    }
                });
            }
        } catch (Throwable e) {
            handleException(e, context, definition, routerContext);
        }
    };
}

From source file:com.github.mcollovati.vertx.Sync.java

License:Open Source License

public static <T> T await(Consumer<Handler<AsyncResult<T>>> task) {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    try {//from www . j  a  va2  s.  c o  m
        Future<T> f = Future.<T>future().setHandler(ar -> {
            countDownLatch.countDown();
            if (ar.failed()) {
                throw new VertxException(ar.cause());
            }
        });
        task.accept(f.completer());
        countDownLatch.await();
        return f.result();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new VertxException(e);
    }

}

From source file:io.apiman.gateway.engine.vertx.shareddata.SharedGlobalDataRegistry.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*  w  w  w . j  ava  2 s . c o  m*/
public void getContract(String apiOrganizationId, String apiId, String apiVersion, String apiKey,
        IAsyncResultHandler<ApiContract> handler) {
    String apiIndex = getApiIndex(apiOrganizationId, apiId, apiVersion);

    Future apiFuture = Future.future();
    Future clientFuture = Future.future();

    objectMap.get(apiIndex, apiFuture.completer());
    objectMap.get(apiKey, clientFuture.completer());

    CompositeFuture.all(apiFuture, clientFuture).setHandler(compositeResult -> {
        if (compositeResult.succeeded()) {
            Api api = (Api) apiFuture.result();
            Client client = (Client) clientFuture.result();

            if (api == null) {
                Exception error = new InvalidContractException(
                        Messages.i18n.format("InMemoryRegistry.NoClientForAPIKey", apiKey));
                handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            } else if (client == null) {
                Exception error = new InvalidContractException(
                        Messages.i18n.format("InMemoryRegistry.ApiWasRetired", apiId, apiOrganizationId));
                handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            } else {
                Optional<Contract> matchedOpt = client.getContracts().stream()
                        .filter(contract -> contract.matches(apiOrganizationId, apiId, apiVersion)).findFirst();

                if (matchedOpt.isPresent()) {
                    Contract contract = matchedOpt.get();
                    ApiContract apiContract = new ApiContract(api, client, contract.getPlan(),
                            contract.getPolicies());
                    handler.handle(AsyncResultImpl.create(apiContract));
                } else {
                    Exception error = new InvalidContractException(
                            Messages.i18n.format("InMemoryRegistry.NoContractFound", //$NON-NLS-1$
                                    client.getClientId(), api.getApiId()));
                    handler.handle(AsyncResultImpl.create(error, ApiContract.class));
                }
            }
        } else {
            handler.handle(AsyncResultImpl.create(compositeResult.cause()));
        }
    });
}

From source file:io.gravitee.gateway.core.failover.FailoverInvoker.java

License:Apache License

@Override
public void invoke(ExecutionContext context, ReadStream<Buffer> stream,
        Handler<ProxyConnection> connectionHandler) {
    ((MutableExecutionContext) context).request(new FailoverRequest(context.request()));

    circuitBreaker.execute(new io.vertx.core.Handler<Future<ProxyConnection>>() {
        @Override//from   w w w  . ja  va  2s.c o m
        public void handle(Future<ProxyConnection> event) {
            FailoverInvoker.super.invoke(context, stream, proxyConnection -> {
                proxyConnection.exceptionHandler(event::fail);
                proxyConnection.responseHandler(
                        response -> event.complete(new FailoverProxyConnection(proxyConnection, response)));
            });
        }
    }).setHandler(new io.vertx.core.Handler<AsyncResult<ProxyConnection>>() {
        @Override
        public void handle(AsyncResult<ProxyConnection> event) {
            if (event.failed()) {
                FailoverConnection connection = new FailoverConnection();
                connectionHandler.handle(connection);
                connection.sendBadGatewayResponse();
            } else {
                FailoverProxyConnection proxyConnection = (FailoverProxyConnection) event.result();
                connectionHandler.handle(proxyConnection);
                proxyConnection.sendResponse();
            }
        }
    });
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

License:Open Source License

private void doUploadMessage(final RoutingContext ctx, final String tenant, final String deviceId,
        final Buffer payload, final String contentType, final Future<MessageSender> senderTracker,
        final String endpointName) {

    if (contentType == null) {
        badRequest(ctx.response(), String.format("%s header is missing", HttpHeaders.CONTENT_TYPE));
        metrics.incrementUndeliverableHttpMessages(endpointName, tenant);
    } else if (payload == null || payload.length() == 0) {
        badRequest(ctx.response(), "missing body");
        metrics.incrementUndeliverableHttpMessages(endpointName, tenant);
    } else {//w w w.  ja va 2 s . c o  m

        final Future<String> tokenTracker = getRegistrationAssertionHeader(ctx, tenant, deviceId);

        CompositeFuture.all(tokenTracker, senderTracker).setHandler(s -> {
            if (s.failed()) {
                if (tokenTracker.failed()) {
                    LOG.debug("could not get registration assertion [tenant: {}, device: {}]", tenant, deviceId,
                            s.cause());
                    endWithStatus(ctx.response(), HTTP_FORBIDDEN, null, null, null);
                } else {
                    serviceUnavailable(ctx.response(), 5);
                }
                metrics.incrementUndeliverableHttpMessages(endpointName, tenant);
            } else {
                sendToHono(ctx.response(), deviceId, payload, contentType, tokenTracker.result(),
                        senderTracker.result(), tenant, endpointName);
            }
        });
    }
}

From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java

License:Open Source License

private Future<Void> uploadMessage(final MqttContext ctx, final String tenant, final String deviceId,
        final Buffer payload, final Future<MessageSender> senderTracker, final String endpointName) {

    if (!isPayloadOfIndicatedType(payload, ctx.contentType())) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                String.format("Content-Type %s does not match with the payload", ctx.contentType())));
    } else {/*from w  w  w.j  a  v  a  2s .c  om*/

        final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId,
                ctx.authenticatedDevice());
        final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant);

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

            if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {

                final MessageSender sender = senderTracker.result();
                final Message downstreamMessage = newMessage(
                        ResourceIdentifier.from(endpointName, tenant, deviceId),
                        sender.isRegistrationAssertionRequired(), ctx.message().topicName(), ctx.contentType(),
                        payload, tokenTracker.result(), null);
                customizeDownstreamMessage(downstreamMessage, ctx);

                if (ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) {
                    return sender.sendAndWaitForOutcome(downstreamMessage);
                } else {
                    return sender.send(downstreamMessage);
                }
            } else {
                // this adapter is not enabled for the tenant
                return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
            }

        }).compose(delivery -> {

            LOG.trace(
                    "successfully processed message [topic: {}, QoS: {}] for device [tenantId: {}, deviceId: {}]",
                    ctx.message().topicName(), ctx.message().qosLevel(), tenant, deviceId);
            metrics.incrementProcessedMqttMessages(endpointName, tenant);
            onMessageSent(ctx);
            // check that the remote MQTT client is still connected before sending PUBACK
            if (ctx.deviceEndpoint().isConnected() && ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) {
                ctx.deviceEndpoint().publishAcknowledge(ctx.message().messageId());
            }
            return Future.<Void>succeededFuture();

        }).recover(t -> {

            if (ClientErrorException.class.isInstance(t)) {
                final ClientErrorException e = (ClientErrorException) t;
                LOG.debug(
                        "cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]: {} - {}",
                        tenant, deviceId, endpointName, e.getErrorCode(), e.getMessage());
            } else {
                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName, t);
                metrics.incrementUndeliverableMqttMessages(endpointName, tenant);
                onMessageUndeliverable(ctx);
            }
            return Future.failedFuture(t);
        });
    }
}

From source file:org.eclipse.hono.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

private void publishMessage(final MqttEndpoint endpoint, final String tenantId, final String logicalDeviceId,
        final MqttPublishMessage message, final ResourceIdentifier resource) {
    LOG.trace("received message [client ID: {}, topic: {}, QoS: {}, payload {}]", endpoint.clientIdentifier(),
            message.topicName(), message.qosLevel(), message.payload().toString(Charset.defaultCharset()));

    try {/*from  w  w  w .  ja v a 2  s. co  m*/
        Future<Void> messageTracker = Future.future();
        messageTracker.setHandler(s -> {
            if (s.failed()) {
                LOG.debug("cannot process message [client ID: {}, deviceId: {}, topic: {}, QoS: {}]: {}",
                        endpoint.clientIdentifier(), logicalDeviceId, resource, message.qosLevel(),
                        s.cause().getMessage());
                metrics.incrementUndeliverableMqttMessages(resource.getEndpoint(), tenantId);
                close(endpoint);
            } else {
                LOG.trace("successfully processed message [client ID: {}, deviceId: {}, topic: {}, QoS: {}]",
                        endpoint.clientIdentifier(), logicalDeviceId, resource, message.qosLevel());
                metrics.incrementProcessedMqttMessages(resource.getEndpoint(), tenantId);
            }
        });

        // check that MQTT client tries to publish on topic with device_id same as on connection
        if (!getConfig().isAuthenticationRequired()
                && !resource.getResourceId().equals(endpoint.clientIdentifier())) {
            // MQTT client is trying to publish on a different device_id used on connection (MQTT has no way for
            // errors)
            messageTracker.fail("client not authorized");
        } else {
            Future<String> assertionTracker = getRegistrationAssertion(endpoint, tenantId, logicalDeviceId);
            Future<MessageSender> senderTracker = getSenderTracker(message, resource, tenantId);

            CompositeFuture.all(assertionTracker, senderTracker).compose(ok -> {
                doUploadMessage(logicalDeviceId, assertionTracker.result(), endpoint, message,
                        senderTracker.result(), messageTracker);
            }, messageTracker);
        }

    } catch (IllegalArgumentException e) {

        // MQTT client is trying to publish on invalid topic; it does not contain at least two segments
        LOG.debug("client [ID: {}] tries to publish on unsupported topic", endpoint.clientIdentifier());
        close(endpoint);
    }
}

From source file:org.eclipse.hono.service.monitoring.AbstractMessageSenderConnectionEventProducer.java

License:Open Source License

private Future<?> sendNotificationEvent(final Device authenticatedDevice, final String protocolAdapter,
        final String remoteId, final String cause, final JsonObject data) {

    if (authenticatedDevice == null) {
        // we only handle authenticated devices
        return Future.succeededFuture();
    }//from   w ww . j a  v  a  2s.c o  m

    // get an assertion

    final Future<String> assertionFuture = this.deviceRegistryClient
            .getOrCreateRegistrationClient(authenticatedDevice.getTenantId()).compose(registrationClient -> {
                return registrationClient.assertRegistration(authenticatedDevice.getDeviceId())
                        .map(registration -> {
                            return registration.getString(RegistrationConstants.FIELD_ASSERTION);
                        });
            });

    // get a sender

    final Future<MessageSender> senderFuture = getOrCreateSender(authenticatedDevice);

    // send message with assertion and sender

    return CompositeFuture.all(assertionFuture, senderFuture).compose(f -> {
        final String deviceId = authenticatedDevice.getDeviceId();

        final JsonObject payload = new JsonObject();
        payload.put("cause", cause);
        payload.put("remote-id", remoteId);
        payload.put("source", protocolAdapter);

        if (data != null) {
            payload.put("data", data);
        }

        return senderFuture.result().send(deviceId, payload.encode().getBytes(StandardCharsets.UTF_8),
                EventConstants.EVENT_CONNECTION_NOTIFICATION_CONTENT_TYPE, assertionFuture.result(), v -> {
                });
    });
}

From source file:org.eclipse.hono.vertx.example.base.HonoSenderBase.java

License:Open Source License

/**
 * Get both Hono clients and connect them to Hono's microservices.
 *
 * @return The result of the creation and connection of the Hono clients.
 *///from  ww w  . j a  v a2 s  .c om
private Future<Void> getHonoClients() {
    // we need two clients to get it working, define futures for them
    final Future<RegistrationClient> registrationClientTracker = getRegistrationClient();
    final Future<MessageSender> messageSenderTracker = getMessageSender();

    final Future<Void> result = Future.future();

    CompositeFuture.all(registrationClientTracker, messageSenderTracker).setHandler(compositeResult -> {
        if (compositeResult.failed()) {
            System.err.println("hono clients could not be created : " + compositeResult.cause().getMessage());
            result.fail(compositeResult.cause());
        } else {
            registrationClient = registrationClientTracker.result();
            messageSender = messageSenderTracker.result();
            result.complete();
        }
    });

    return result;
}

From source file:org.folio.auth.permissions_module.impl.MongoPermissionsStore.java

@Override
public Future<JsonArray> getExpandedPermissions(String permission, String tenant) {
    //System.out.println("Permissions> Expanding permission '"+ permission + "' on tenant '"+
    //        tenant + "'");
    JsonObject query = new JsonObject().put("permission_name", permission).put("tenant", tenant);
    JsonArray permList = new JsonArray();
    Future<JsonArray> future = Future.future();
    mongoClient.find("permissions", query, res -> {
        if (res.succeeded() && res.result().size() > 0) {
            //System.out.println("Permissions> Successfully queried mongo for '"+ permission + "' on tenant '"+
            //    tenant + "'");
            /*//from   w  w w .ja  va  2 s. co  m
            If there are no subpermissions, go ahead and complete the future with the
            given value of the JsonArray
                    
            If there are subpermissions, create a list of new futures, by calling
            walkPerms for each sub permission, then create a composite future from
            these new futures, with a handler that completes the original
            future when they return
            */
            JsonObject permObj = res.result().get(0);
            permList.add(permission);
            JsonArray subPerms = permObj.getJsonArray("sub_permissions");
            LinkedList<Future> futureList = new LinkedList<>();
            if (subPerms != null && !subPerms.isEmpty()) {
                logger.debug("Permissions> " + subPerms.size() + " subs to process for '" + permission + "'");
                for (Object o : subPerms) {
                    String sub = (String) o;
                    Future<JsonArray> newFuture = getExpandedPermissions(sub, tenant);
                    futureList.add(newFuture);
                }
                logger.debug("Permissions> Creating CompositeFuture to expand " + permission + " into "
                        + futureList.size() + " subs: " + subPerms.encode());
                CompositeFuture compositeFuture = CompositeFuture.all(futureList);
                compositeFuture.setHandler(res2 -> {
                    if (res2.succeeded()) {
                        //Get output of contained futures and complete the future here
                        for (Future f : futureList) {
                            JsonArray arr = (JsonArray) f.result();
                            for (Object o : arr) {
                                permList.add(o);
                            }
                        }
                        future.complete(permList);
                    } else {
                        future.fail("Unable to populate permissions: " + res2.cause().getMessage());
                    }
                });
            } else {
                //System.out.println("Permissions> No sub-permissions found for '" + permission + "'");
                future.complete(permList);
            }
        } else {
            future.fail("No permission '" + permission + "' found for tenant '" + tenant + "'");
        }
    });
    return future;
}