Example usage for io.vertx.core Future failedFuture

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

Introduction

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

Prototype

static <T> Future<T> failedFuture(String failureMessage) 

Source Link

Document

Create a failed future with the specified failure message.

Usage

From source file:io.engagingspaces.graphql.servicediscovery.consumer.SchemaConsumer.java

License:Open Source License

/**
 * Executes the parametrized GraphQL query and its variables against the specified schema definition
 * (aka the graphql service name) that is published to the service discovery with the specified name.
 * <p>//  w ww  . j a  va  2s  .  c  om
 * On success a {@link QueryResult} is returned. Note that at this point the GraphQL query may still have failed,
 * so be sure to check the {@link QueryResult#getErrors()} property afterwards.
 * <p>
 * The top-level keys in the `variables` json represent the variable names that are used in the query string, and
 * are passed with their corresponding values to the query executor.
 *
 * @param discoveryName the name of the service discovery
 * @param schemaName    the name of the schema definition to query
 * @param query         the GraphQL query
 * @param variables     the variables to pass to the query executor
 * @param resultHandler the result handler
 */
default void executeQuery(String discoveryName, String schemaName, String query, JsonObject variables,
        Handler<AsyncResult<QueryResult>> resultHandler) {
    Objects.requireNonNull(schemaName, "Schema definition name cannot be null");
    Objects.requireNonNull(query, "GraphQL query cannot be null");
    Objects.requireNonNull(resultHandler, "Query result handler cannot be null");

    if (!managedDiscoveries().contains(discoveryName)) {
        resultHandler.handle(Future.failedFuture(
                "Service discovery with name '" + discoveryName + "' is not managed by this schema consumer"));
        return;
    }
    ServiceDiscovery discovery = discoveryRegistrar().getDiscovery(discoveryName);
    discovery.getRecord(record -> schemaName.equals(record.getName()), rh -> {
        if (rh.succeeded() && rh.result() != null) {
            GraphQLClient.executeQuery(discovery, rh.result(), query, variables, resultHandler);
        } else {
            resultHandler.handle(Future.failedFuture(
                    "Failed to find published schema '" + schemaName + "' in repository: " + discoveryName));
        }
    });
}

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>/*  ww  w  .ja va2  s  .c o m*/
 * 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 av a  2s .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.publisher.SchemaPublisher.java

License:Open Source License

/**
 * Un-publishes the schema definition given its schema registration.
 *
 * @param registration  the schema registration
 * @param resultHandler the result handler
 *//* w  ww  .  ja  v a  2s  .  c om*/
default void unpublish(SchemaRegistration registration, Handler<AsyncResult<Void>> resultHandler) {
    Objects.requireNonNull(resultHandler, "Un-publication result handler cannot be null");
    GraphQLService.unpublish(registration, rh -> {
        if (rh.succeeded()) {
            schemaRegistrar().unregister(registration);
            resultHandler.handle(Future.succeededFuture());
        } else {
            resultHandler.handle(Future.failedFuture(rh.cause()));
        }
    });
}

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

License:Open Source License

/**
 * Closes the registrar and releases all its resources.
 *
 * @param closeAction  the action to perform for closing registered schema's
 * @param closeHandler the close handler
 *///from  w  w w . jav a  2  s  .  c  o  m
protected void close(BiConsumer<SchemaRegistration, Handler<AsyncResult<Void>>> closeAction,
        Handler<AsyncResult<Void>> closeHandler) {
    Objects.requireNonNull(closeHandler, "Schema registrar close handler cannot be null");
    if (!registrations().isEmpty()) {
        // Execute the close action against each of the published schema's (e.g. un-publishing)
        List<Future> futures = new ArrayList<>();
        registrations().forEach(registration -> closeAction.accept(registration, rh -> futures
                .add(rh.succeeded() ? Future.succeededFuture() : Future.failedFuture(rh.cause()))));

        handleCloseCompletion(closeHandler, futures);
    } else {
        doClose(closeHandler);
    }
}

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

License:Open Source License

private void handleCloseCompletion(Handler<AsyncResult<Void>> closeHandler, List<Future> futures) {
    CompositeFuture.all(futures).setHandler(rh -> {
        if (rh.succeeded()) {
            CompositeFuture composite = rh.result();
            for (int index = 0; index < composite.size(); index++) {
                if (composite.succeeded(index) && composite.resultAt(index) != null) {
                    composite.<SchemaRegistration>resultAt(index).unregisterServiceProxy();
                }//ww  w . j a v a2s.  co m
            }
            doClose(closeHandler);
        } else {
            closeHandler.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>/*  ww  w. ja v  a  2  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.graphql.servicediscovery.service.GraphQLService.java

License:Open Source License

/**
 * Unpublish a GraphQL schema that was previously published.
 *
 * @param registration the information of the schema to unpublish
 * @param resultHandler      the result handler
 *///from w  w w .  ja v  a2 s  .com
static void unpublish(SchemaRegistration registration, Handler<AsyncResult<Void>> resultHandler) {
    Objects.requireNonNull(registration, "Schema registration cannot be null");
    Objects.requireNonNull(resultHandler, "Un-publication result handler cannot be null");

    registration.getDiscovery().unpublish(registration.getRecord().getRegistration(), rh -> {
        if (rh.succeeded()) {
            registration.unregisterServiceProxy();
            resultHandler.handle(Future.succeededFuture());
        } 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 error.
 *
 * @param key   the key//from w  w w.jav a  2 s. c  om
 * @param error the exception to prime instead of a value
 * @return the data loader for fluent coding
 */
public DataLoader<K, V> prime(K key, Exception error) {
    Object cacheKey = getCacheKey(key);
    if (!futureCache.containsKey(cacheKey)) {
        futureCache.set(cacheKey, Future.failedFuture(error));
    }
    return this;
}

From source file:io.eventuate.javaclient.stompclient.MyStompClientImpl.java

License:Open Source License

@Override
public synchronized StompClient connect(int port, String host, NetClient net,
        Handler<AsyncResult<StompClientConnection>> resultHandler) {
    client = net.connect(port, host, ar -> {
        if (ar.failed()) {
            if (resultHandler != null) {
                resultHandler.handle(Future.failedFuture(ar.cause()));
            } else {
                log.error(ar.cause());/*from   ww w .ja  va 2s.  c o  m*/
            }
        } else {
            // Create the connection, the connection attach a handler on the socket.
            StompClientConnectionImpl scci = new StompClientConnectionImpl(vertx, ar.result(), this,
                    resultHandler);
            scci.errorHandler(frame -> {
                resultHandler.handle(Future.failedFuture(new RuntimeException("Error")));
            });
            scci.closeHandler(connection -> {
                handleClose();
            });
            // Socket connected - send "CONNECT" Frame
            ar.result().write(getConnectFrame(host));
        }
    });
    return this;
}