Example usage for io.vertx.core Future succeededFuture

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

Introduction

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

Prototype

static <T> Future<T> succeededFuture(T result) 

Source Link

Document

Created a succeeded future with the specified result.

Usage

From source file:io.engagingspaces.graphql.query.QueryableVertxEBProxy.java

License:Apache License

public void queryWithVariables(String graphqlQuery, JsonObject variables,
        Handler<AsyncResult<QueryResult>> resultHandler) {
    if (closed) {
        resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
        return;/*from  w w  w  . j a v  a 2  s . c  o m*/
    }
    JsonObject _json = new JsonObject();
    _json.put("graphqlQuery", graphqlQuery);
    _json.put("variables", variables);
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options)
            : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "queryWithVariables");
    _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> {
        if (res.failed()) {
            resultHandler.handle(Future.failedFuture(res.cause()));
        } else {
            resultHandler.handle(Future.succeededFuture(
                    res.result().body() == null ? null : new QueryResult(res.result().body())));
        }
    });
}

From source file:io.engagingspaces.graphql.query.QueryableVertxEBProxy.java

License:Apache License

public void resolveType(String typeResolverId, JsonObject typeHolder,
        Handler<AsyncResult<JsonObject>> resultHandler) {
    if (closed) {
        resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
        return;/*www.  j av  a2  s.  c  om*/
    }
    JsonObject _json = new JsonObject();
    _json.put("typeResolverId", typeResolverId);
    _json.put("typeHolder", typeHolder);
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options)
            : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "resolveType");
    _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> {
        if (res.failed()) {
            resultHandler.handle(Future.failedFuture(res.cause()));
        } else {
            resultHandler.handle(Future.succeededFuture(res.result().body()));
        }
    });
}

From source file:io.engagingspaces.graphql.query.QueryableVertxEBProxy.java

License:Apache License

public void fetchData(String dataFetcherId, JsonObject dataFetchingEnvironment,
        Handler<AsyncResult<JsonObject>> resultHandler) {
    if (closed) {
        resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
        return;//from  ww w.ja  v  a 2s .c  om
    }
    JsonObject _json = new JsonObject();
    _json.put("dataFetcherId", dataFetcherId);
    _json.put("dataFetchingEnvironment", dataFetchingEnvironment);
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options)
            : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "fetchData");
    _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> {
        if (res.failed()) {
            resultHandler.handle(Future.failedFuture(res.cause()));
        } else {
            resultHandler.handle(Future.succeededFuture(res.result().body()));
        }
    });
}

From source file:io.engagingspaces.graphql.schema.SchemaDefinition.java

License:Open Source License

/**
 * Executes the GraphQL query on the GraphQL schema proxy using the provided variables.
 *
 * @param graphqlQuery  the graphql query
 * @param resultHandler the result handler with the graphql query result on success, or a failure
 *//*from  ww w  .  j  a  va  2 s . c  o m*/
@Override
default void queryWithVariables(String graphqlQuery, JsonObject variables,
        Handler<AsyncResult<QueryResult>> resultHandler) {
    try {
        QueryResult result = queryBlocking(graphqlQuery, variables);
        resultHandler.handle(Future.succeededFuture(result));
    } catch (RuntimeException ex) {
        resultHandler.handle(Future.failedFuture(ex));
    }
}

From source file:io.engagingspaces.graphql.servicediscovery.client.GraphQLClient.java

License:Open Source License

/**
 * Get the GraphQL service proxy that is associated with the provided service record.
 *
 * @param discovery     the service discovery instance
 * @param record        the service record of a published GraphQL service
 * @param resultHandler the result handler
 *///from www  . j  a v a2s. co m
static void getSchemaProxy(ServiceDiscovery discovery, Record record,
        Handler<AsyncResult<Queryable>> resultHandler) {
    Objects.requireNonNull(discovery, "Service discovery cannot be null");
    Objects.requireNonNull(record, "Record cannot be null");
    Objects.requireNonNull(resultHandler, "Schema proxy result handler cannot be null");

    if (!SERVICE_TYPE.equals(record.getType())) {
        resultHandler.handle(Future.failedFuture("Record '" + record.getName() + "' is of wrong type '"
                + record.getType() + "'. Expected: " + SERVICE_TYPE));
    } else if (!Status.UP.equals(record.getStatus())) {
        resultHandler.handle(Future.failedFuture("Record status indicates service '" + record.getName()
                + "' is: " + record.getStatus() + ". Expected: " + Status.UP));
    } else if (record.getRegistration() == null) {
        resultHandler.handle(
                Future.failedFuture("Record '" + record.getName() + "' has no service discovery registration"));
    } else {
        ServiceReference reference = discovery.getReference(record);
        Queryable queryable = reference.cached() == null ? reference.get() : reference.cached();
        reference.release();
        resultHandler.handle(Future.succeededFuture(queryable));
    }
}

From source file:io.engagingspaces.graphql.servicediscovery.publisher.SchemaPublisher.java

License:Open Source License

/**
 * Publishes the provided schema definitions to the specified service discovery.
 * <p>//w ww  .ja  v  a2  s.  com
 * Upon success a list of {@link SchemaRegistration}s is returned in the result handler.
 *
 * @param options       the service discovery options
 * @param resultHandler the result handler
 * @param schemas       the GraphQL schema's to publish
 */
default void publishAll(ServiceDiscoveryOptions options,
        Handler<AsyncResult<List<SchemaRegistration>>> resultHandler, GraphQLSchema... schemas) {

    Objects.requireNonNull(resultHandler, "Publication result handler cannot be null");
    if (schemas == null || schemas.length == 0) {
        resultHandler.handle(Future.failedFuture("Nothing to publish. No schema definitions provided"));
        return;
    }
    List<Future> futures = new ArrayList<>();
    Arrays.asList(schemas).forEach(schema -> publish(options, schema, rh -> futures
            .add(rh.succeeded() ? Future.succeededFuture(rh.result()) : Future.failedFuture(rh.cause()))));

    CompositeFuture.all(futures).setHandler(rh -> {
        if (rh.failed()) {
            resultHandler.handle(Future.failedFuture(rh.cause()));
            return;
        }
        CompositeFuture composite = rh.result();
        List<SchemaRegistration> published = composite.list();
        if (published.size() != schemas.length) {
            List<Throwable> errors = rh.result().<Future<Void>>list().stream().filter(Future::failed)
                    .map(Future::cause).collect(Collectors.toList());
            resultHandler.handle(Future.failedFuture(new PartialPublishException(errors)));
        } else {
            resultHandler.handle(Future.succeededFuture(published));
        }
    });
}

From source file:io.engagingspaces.graphql.servicediscovery.publisher.SchemaPublisher.java

License:Open Source License

/**
 * Publishes the schema definition and metadata to the service discovery indicated by
 * the provided schema publisher options.
 *
 * @param options       the service discovery options
 * @param schema        the GraphQL schema to publish
 * @param metadata      the metadata to pass to the published discovery record
 * @param resultHandler the result handler
 *///from  w  w  w  .j a va2 s. c  o m
default void publish(ServiceDiscoveryOptions options, GraphQLSchema schema, SchemaMetadata metadata,
        Handler<AsyncResult<SchemaRegistration>> resultHandler) {
    if (schema == null) {
        resultHandler.handle(Future.failedFuture("Nothing to publish. No schema definition provided"));
        return;
    }
    Objects.requireNonNull(schema, "GraphQL schema cannot be null");
    Objects.requireNonNull(options, "Schema discovery options cannot be null");
    Objects.requireNonNull(resultHandler, "Publication result handler cannot be null");

    SchemaDefinition definition = SchemaDefinition.createInstance(schema, metadata);
    if (schemaRegistrar().findRegistration(options.getName(), definition.schemaName()).isPresent()) {
        resultHandler.handle(Future.failedFuture(
                "Schema '" + definition.schemaName() + "' was already published to: " + options.getName()));
        return;
    }
    metadata.put("publisherId", schemaRegistrar().getPublisherId());
    ServiceDiscovery discovery = schemaRegistrar().getOrCreateDiscovery(options);

    GraphQLService.publish(schemaRegistrar().getVertx(), discovery, definition, rh -> {
        if (rh.succeeded()) {
            SchemaRegistration registration = schemaRegistrar().register(rh.result(), options, this, this);
            resultHandler.handle(Future.succeededFuture(registration));
        } else {
            resultHandler.handle(Future.failedFuture(rh.cause()));
        }
    });
}

From source file:io.engagingspaces.graphql.servicediscovery.service.GraphQLService.java

License:Open Source License

/**
 * Publish a GraphQL schema for querying.
 * <p>//from   ww  w.  j av  a2 s .  co m
 * On success a {@link SchemaRegistration} is returned. It contains the message consumer of the
 * {@link Queryable} service proxy that supplies the published {@link SchemaDefinition}, the published service
 * discovery record, and the {@link ServiceDiscovery} it was published to.
 * <p>
 * Note that unless invoked from a {@link SchemaPublisher} a
 * client needs to keep hold of the returned {@link Record} as long as it is published.
 *
 * @param vertx         the vert.x instance
 * @param discovery     the service discovery instance
 * @param definition    the service proxy instance exposing the graphql schema
 * @param resultHandler the result handler that returns the registration
 */
static void publish(Vertx vertx, ServiceDiscovery discovery, SchemaDefinition definition,
        Handler<AsyncResult<SchemaRegistration>> resultHandler) {

    Objects.requireNonNull(vertx, "Vertx cannot be null");
    Objects.requireNonNull(discovery, "Service discovery cannot be null");
    Objects.requireNonNull(definition, "GraphQL queryable cannot be null");
    Objects.requireNonNull(resultHandler, "Publication result handler cannot be null");

    // TODO Caching proxy ok?

    final MessageConsumer<JsonObject> serviceConsumer;
    if (definition.metadata().get("publisherId") == null) {
        serviceConsumer = ProxyHelper.registerService(Queryable.class, vertx, definition,
                definition.serviceAddress());
    } else {
        // Publisher handles service instantiation, manages consumer.
        serviceConsumer = null;
    }

    Record record = new Record().setType(SERVICE_TYPE).setName(definition.schemaName())
            .setMetadata(definition.metadata().toJson())
            .setLocation(new JsonObject().put(Record.ENDPOINT, definition.serviceAddress()));

    discovery.publish(record, rh -> {
        if (rh.succeeded()) {
            resultHandler.handle(Future.succeededFuture(
                    SchemaRegistration.create(discovery, null, rh.result(), definition, serviceConsumer)));
        } else {
            resultHandler.handle(Future.failedFuture(rh.cause()));
        }
    });
}

From source file:io.engagingspaces.vertx.dataloader.DataLoader.java

License:Open Source License

/**
 * Primes the cache with the given key and value.
 *
 * @param key   the key//  ww w  . j a  va 2 s  . co  m
 * @param value the value
 * @return the data loader for fluent coding
 */
public DataLoader<K, V> prime(K key, V value) {
    Object cacheKey = getCacheKey(key);
    if (!futureCache.containsKey(cacheKey)) {
        futureCache.set(cacheKey, Future.succeededFuture(value));
    }
    return this;
}

From source file:io.flowly.auth.ExtJwtAuthProvider.java

License:Open Source License

@Override
public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
    try {/* w w  w. j  a  v a  2 s . co  m*/
        final JsonObject payload = jwt.decode(authInfo.getString("jwt"));

        final JsonObject options = authInfo.getJsonObject("options", EMPTY_OBJECT);

        // All dates in JWT are of type NumericDate
        // a NumericDate is: numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until
        // the specified UTC date/time, ignoring leap seconds
        final long now = System.currentTimeMillis() / 1000;

        if (payload.containsKey("exp") && !options.getBoolean("ignoreExpiration", false)) {
            if (now >= payload.getLong("exp")) {
                resultHandler.handle(Future.failedFuture("Expired JWT token: exp <= now"));
                return;
            }
        }

        if (payload.containsKey("iat")) {
            Long iat = payload.getLong("iat");
            // issue at must be in the past
            if (iat > now) {
                resultHandler.handle(Future.failedFuture("Invalid JWT token: iat > now"));
                return;
            }
        }

        if (payload.containsKey("nbf")) {
            Long nbf = payload.getLong("nbf");
            // not before must be after now
            if (nbf > now) {
                resultHandler.handle(Future.failedFuture("Invalid JWT token: nbf > now"));
                return;
            }
        }

        if (options.containsKey("audience")) {
            JsonArray audiences = options.getJsonArray("audience", EMPTY_ARRAY);
            JsonArray target = payload.getJsonArray("aud", EMPTY_ARRAY);

            if (Collections.disjoint(audiences.getList(), target.getList())) {
                resultHandler
                        .handle(Future.failedFuture("Invalid JWT audience. expected: " + audiences.encode()));
                return;
            }
        }

        if (options.containsKey("issuer")) {
            if (!options.getString("issuer").equals(payload.getString("iss"))) {
                resultHandler.handle(Future.failedFuture("Invalid JWT issuer"));
                return;
            }
        }

        resultHandler.handle(Future.succeededFuture(new ExtJwtUser(payload, permissionsClaimKey)));

    } catch (RuntimeException e) {
        resultHandler.handle(Future.failedFuture(e));
    }
}