Example usage for io.vertx.core Future setHandler

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

Introduction

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

Prototype

@Fluent
default Future<T> setHandler(Handler<AsyncResult<T>> handler) 

Source Link

Document

Like #onComplete(Handler) .

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) {// www .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.englishtown.vertx.hk2.HK2VerticleLoader.java

License:Open Source License

/**
 * Vert.x calls the stop method when the verticle is undeployed.
 * Put any cleanup code for your verticle in here
 *
 * @throws Exception/*from w w  w  .j av  a  2 s. c om*/
 */
@Override
public void stop(Future<Void> stopFuture) throws Exception {

    classLoader = null;
    parent = null;

    Future<Void> future = Future.future();
    future.setHandler(result -> {
        // Destroy the service locator
        ServiceLocatorFactory.getInstance().destroy(locator);
        locator = null;

        // Pass result to the stop future
        if (result.succeeded()) {
            stopFuture.complete();
        } else {
            stopFuture.fail(future.cause());
        }
    });

    try {
        // Stop the real verticle
        if (realVerticle != null) {
            realVerticle.stop(future);
        } else {
            future.complete();
        }
    } catch (Throwable t) {
        future.fail(t);
    }

}

From source file:com.github.ithildir.airbot.BaseServiceVerticle.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {
    ConfigRetriever configRetriever = ConfigRetriever.create(vertx);

    configRetriever.getConfig(asyncResult -> {
        if (asyncResult.failed()) {
            startFuture.fail(asyncResult.cause());

            return;
        }//from ww  w.  j  a  va 2  s  . co m

        JsonObject configJsonObject = asyncResult.result();

        Future<Void> future = start(configJsonObject);

        future.setHandler(startFuture);
    });
}

From source file:com.github.ithildir.airbot.server.api.ai.ApiAiHandler.java

License:Open Source License

@Override
public void handle(RoutingContext routingContext) {
    String json = routingContext.getBodyAsString();

    JsonObject responseJsonObject = (JsonObject) _jsonParser.parse(json);

    AIResponse aiResponse = _gson.fromJson(json, AIResponse.class);

    Result result = aiResponse.getResult();

    String action = result.getAction();

    ApiAiFulfillmentBuilder apiAiFulfillmentBuilder = _apiAiFulfillmentBuilders.get(action);

    Future<Fulfillment> future = apiAiFulfillmentBuilder.build(aiResponse, responseJsonObject);

    HttpServerResponse httpServerResponse = routingContext.response();

    future.setHandler(asyncResult -> {
        if (asyncResult.failed()) {
            _logger.error("Unable to handle API.AI request {0}", asyncResult.cause(), aiResponse);

            routingContext.fail(HttpURLConnection.HTTP_INTERNAL_ERROR);

            return;
        }//from  www  .j  av a2 s .co m

        httpServerResponse.end(_gson.toJson(asyncResult.result()));
    });
}

From source file:com.groupon.vertx.redis.RedisCommandHandler.java

License:Apache License

private void setCommandResponseHandler(final List<RedisCommand> redisCommands,
        final Message<JsonObject> command, final boolean isMulti) {
    for (final RedisCommand redisCommand : redisCommands) {
        final Future<JsonObject> finalResult = Future.future();
        finalResult.setHandler(new Handler<AsyncResult<JsonObject>>() {
            public void handle(AsyncResult<JsonObject> commandResponse) {
                log.trace("handleCommand", "reply", new String[] { "command", "response", "isMulti" },
                        redisCommand.toString(), commandResponse, isMulti);
                if (commandResponse.succeeded()) {
                    command.reply(commandResponse.result());
                } else {
                    String cause = commandResponse.cause() != null ? commandResponse.cause().getMessage()
                            : "unknown";
                    command.reply(buildReply("error", null, cause));
                }/*w  w w .ja va 2  s  . co  m*/
            }
        });
        redisCommand.commandResponse(finalResult);
    }
}

From source file:com.groupon.vertx.utils.config.ConfigLoader.java

License:Apache License

/**
 * Check if the configuration has already been loaded, and if so return that, otherwise
 * attempt to load the configuration from the filesystem and save the result
 *
 * @param field   JsonObject or String/* w  w w. j a  v a 2 s. c o m*/
 * @param handler AsyncResultHandler to be called when the config is ready
 */
public void load(Object field, AsyncResultHandler<JsonObject> handler) {
    Future<JsonObject> configFuture = load(field);
    configFuture.setHandler(handler);
}

From source file:com.groupon.vertx.utils.config.ConfigLoader.java

License:Apache License

/**
 * Check if the configuration has already been loaded, and if so return that, otherwise
 * attempt to load the configuration from the filesystem and save the result
 *
 * @param path path to the configuration file
 * @return future that eventually contains the JsonObject representing the configuration
 *//*  w  ww.j  av a 2s. co  m*/
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private Future<JsonObject> getOrLoadConfig(final String path) {
    final Future<JsonObject> configFuture = Future.future();

    if (loadedConfigs.containsKey(path)) {
        configFuture.complete(loadedConfigs.get(path));
    } else {
        final Future<JsonObject> loadedConfigFuture = loadAndParseConfigFromFilesystem(path);
        loadedConfigFuture.setHandler(new AsyncResultHandler<JsonObject>() {
            @Override
            public void handle(AsyncResult<JsonObject> result) {
                if (result.succeeded()) {
                    JsonObject loadedConfig = result.result();
                    loadedConfigs.put(path, loadedConfig);
                    configFuture.complete(loadedConfig);
                } else {
                    configFuture.fail(result.cause());
                }
            }
        });
    }

    return configFuture;
}

From source file:com.groupon.vertx.utils.MainVerticle.java

License:Apache License

/**
 * @param startedResult future indicating when all verticles have been deployed successfully
 *//* w  w  w.j a va  2  s . com*/
@Override
public void start(final Future<Void> startedResult) {
    final JsonObject config = config();
    final boolean abortOnFailure = config.getBoolean(ABORT_ON_FAILURE_FIELD, true);

    try {
        registerMessageCodecs(vertx, config, abortOnFailure);
    } catch (final CodecRegistrationException e) {
        log.error("start", "abort", "Shutting down due to one or more errors", e);
        vertx.close();
        return;
    }

    Future<Void> deployResult = deployVerticles(config);
    deployResult.setHandler(new AsyncResultHandler<Void>() {
        @Override
        public void handle(AsyncResult<Void> result) {
            if (result.succeeded()) {
                startedResult.complete(null);
            } else {
                if (abortOnFailure) {
                    log.warn("start", "abort", new String[] { "message" },
                            "Shutting down due to one or more errors");
                    vertx.close();
                } else {
                    startedResult.fail(result.cause());
                }
            }
        }
    });
}

From source file:com.hubrick.vertx.kafka.consumer.KafkaConsumer.java

License:Apache License

private void handle(String msg, Long offset, int tries, int delaySeconds) {
    final Future<Void> futureResult = Future.future();
    futureResult.setHandler(result -> {
        if (result.succeeded()) {
            unacknowledgedOffsets.remove(offset);
            phaser.arriveAndDeregister();
        } else {/* w  w  w .j a  v a  2 s  .  c  o  m*/
            final int nextDelaySeconds = computeNextDelay(delaySeconds);
            if (tries > 0) {
                LOG.error("Exception occurred during kafka message processing, will retry in {} seconds: {}",
                        delaySeconds, msg, result.cause());
                final int nextTry = tries - 1;
                vertx.setTimer(delaySeconds * 1000, event -> handle(msg, offset, nextTry, nextDelaySeconds));
            } else {
                LOG.error(
                        "Exception occurred during kafka message processing. Max number of retries reached. Skipping message: {}",
                        msg, result.cause());
                unacknowledgedOffsets.remove(offset);
                phaser.arriveAndDeregister();
            }
        }
    });
    handler.handle(msg, futureResult);
}

From source file:com.thesoftwarefactory.vertx.web.mvc.impl.MvcServiceImpl.java

License:Apache License

@Override
public void handle(Future<ActionResult> result, RoutingContext context) {
    result.setHandler(actionResult -> {
        handle(actionResult, context);//www .  ja  v a 2s.  co  m
    });
}