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:de.braintags.netrelay.NetRelay.java

License:Open Source License

/**
 * Initialize all needed resources of NetRelay
 * /* ww w. j a  va2 s.  c  o m*/
 * @param handler
 */
protected void init(Handler<AsyncResult<Void>> handler) {
    try {
        router = Router.router(vertx);
        mapperFactory = new NetRelayMapperFactory(this);
        initMailClient();
        initController(router);
        initProcessors();
        initHttpServer(router, res -> {
            if (res.failed()) {
                handler.handle(Future.failedFuture(res.cause()));
            } else {
                initHttpsServer(router, httpsResult -> {
                    if (httpsResult.failed()) {
                        handler.handle(Future.failedFuture(httpsResult.cause()));
                    } else {
                        handler.handle(Future.succeededFuture());
                    }
                });
            }
        });
    } catch (Exception e) {
        handler.handle(Future.failedFuture(e));
    }
}

From source file:de.braintags.netrelay.NetRelay.java

License:Open Source License

/**
 * Create an instance of {@link IDataStore} which will be used by the current instance of NetRelay.
 * The init is performed by using the {@link Settings#getDatastoreSettings()}
 * /*from   w  ww.ja v  a 2s .  c  o  m*/
 * @handler the handler to be informed
 * @return the {@link IDataStore} to be used
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public final void initDataStore(Handler<AsyncResult<Void>> handler)
        throws InstantiationException, IllegalAccessException {
    IDataStoreInit dsInit = settings.getDatastoreSettings().getDatastoreInit().newInstance();
    dsInit.initDataStore(vertx, settings.getDatastoreSettings(), dsInitResult -> {
        if (dsInitResult.failed()) {
            handler.handle(Future.failedFuture(dsInitResult.cause()));
        } else {
            datastore = dsInitResult.result();
            handler.handle(Future.succeededFuture());
        }
    });
}

From source file:de.braintags.netrelay.NetRelay.java

License:Open Source License

private void initHttpServer(Router router, Handler<AsyncResult<Void>> handler) {
    HttpServerOptions options = new HttpServerOptions().setPort(settings.getServerPort());
    HttpServer server = vertx.createHttpServer(options);
    server.requestHandler(router::accept).listen(result -> {
        if (result.failed()) {
            handler.handle(Future.failedFuture(result.cause()));
        } else {/*w w w .  ja  v  a  2s .  c o m*/
            handler.handle(Future.succeededFuture());
        }
    });
}

From source file:de.braintags.netrelay.NetRelay.java

License:Open Source License

private void initHttpsServer(Router router, Handler<AsyncResult<Void>> handler) {
    if (settings.getSslPort() > 0) {
        LOGGER.info("launching ssl server listening on port " + settings.getSslPort());
        HttpServerOptions options = new HttpServerOptions().setPort(settings.getSslPort());
        options.setSsl(true);//w w w  .  jav  a  2  s. c  o  m
        try {
            handleSslCertificate(options, handler);
            HttpServer server = vertx.createHttpServer(options);
            server.requestHandler(router::accept).listen(result -> {
                if (result.failed()) {
                    handler.handle(Future.failedFuture(result.cause()));
                } else {
                    handler.handle(Future.succeededFuture());
                }
            });
        } catch (Exception e) {
            handler.handle(Future.failedFuture(e));
        }
    } else {
        LOGGER.info("no ssl server is launched, cause ssl port is not set: " + settings.getSslPort());
        handler.handle(Future.succeededFuture());
    }
}

From source file:de.braintags.netrelay.NetRelay.java

License:Open Source License

private void handleSslCertificate(HttpServerOptions options, Handler<AsyncResult<Void>> handler)
        throws GeneralSecurityException, IOException {
    if (settings.isCertificateSelfSigned()) {
        String password = validateSslPassword();
        CertificateHelper.createSelfCertificate(options, settings.getHostName(), password);
    } else if (settings.getCertificatePath() != null && settings.getCertificatePath().hashCode() != 0) {
        importCertificate(options);/* w w w . j ava2 s . co  m*/
    } else {
        handler.handle(Future.failedFuture(new UnsupportedOperationException(
                "ssl port is set, but no certificate path set and option certificateSelfSigned is not activated")));
    }
}

From source file:de.braintags.netrelay.templateengine.thymeleaf.ThymeleafTemplateEngineImplBt.java

License:Open Source License

@Override
public void render(RoutingContext context, String templateFileName, Handler<AsyncResult<Buffer>> handler) {
    Buffer buffer = Buffer.buffer();

    try {/*from w  ww. j av a 2  s  .c  om*/
        Map<String, Object> data = new HashMap<>();
        data.put("context", context);
        data.putAll(context.data());

        synchronized (this) {
            templateResolver.setVertx(context.vertx());
            final List<Locale> acceptableLocales = context.acceptableLocales();

            io.vertx.ext.web.Locale locale;

            if (acceptableLocales.size() == 0) {
                locale = io.vertx.ext.web.Locale.create();
            } else {
                // this is the users preferred locale
                locale = acceptableLocales.get(0);
            }

            templateEngine.process(templateFileName, new WebIContext(data, locale), new Writer() {
                @Override
                public void write(char[] cbuf, int off, int len) throws IOException {
                    buffer.appendString(new String(cbuf, off, len));
                }

                @Override
                public void flush() throws IOException {
                }

                @Override
                public void close() throws IOException {
                }
            });
        }

        handler.handle(Future.succeededFuture(buffer));
    } catch (Exception ex) {
        handler.handle(Future.failedFuture(ex));
    }
}

From source file:de.fraunhofer.fokus.redistest.DoInterestingThings.java

License:Creative Commons License

public void doIt(final Vertx vertx, final JsonObject redisConfig, String uuid, Logger logger,
        Handler<AsyncResult<JsonArray>> handler) {
    String zSetName = String.format(ZSET_NAME_FORMAT, uuid);
    final RangeLimitOptions rangeLimitOptions = (RangeLimitOptions) new RangeLimitOptions().setLimit(0,
            Constants.MAX_SEARCH_RESULTS);

    /*//www  .  j  a  v a  2  s  .c om
     * To prevent errors in streams due to empty result set and to enable subscription
     * a dummy element will be prepended to the result set and removed in the subscription
     */
    final List<JsonArray> secureResultList = new ArrayList<JsonArray>();
    secureResultList.add(new JsonArray().add("default"));

    Single.using(DisposableRedisConnection::new, f -> f.create(vertx, redisConfig, logger), f -> f.dispose())
            .subscribe(redisClient -> {
                // emulate searech time in database
                //               vertx.setTimer(40,  xx->{
                Observable.range(1, 40)
                        .map(x -> new JsonObject().put(Constants.KEY_TYPE, Constants.KEY_DICE_OBJECT)
                                .put(Constants.KEY_RECORD_ID, String.valueOf(x))
                                .put(Constants.KEY_DICE_VALUE, x * 0.1).put(Constants.KEY_FAMILYNAME, x * 0.1)
                                .put(Constants.KEY_FIRSTNAME, 1))
                        .filter(x -> x != null) //remove results where comparison has been stopped due to bad dice values
                        // side effect - store objects in redis   
                        .subscribe(res -> {
                            String handle = res.getString(Constants.KEY_RECORD_ID);
                            String hashName = String.format(HASH_NAME_FORMAT, handle);
                            Single.zip(
                                    redisClient.rxZadd(zSetName, res.getDouble(Constants.KEY_DICE_VALUE),
                                            handle),
                                    redisClient.rxExpire(hashName, Constants.EXPIRE_AFTER),
                                    redisClient.rxHmset(hashName, res), (a, b, c) -> {
                                        return res;
                                    }).subscribe(r -> {
                                        // do nothing
                                    }, t -> handler.handle(Future.failedFuture(t)));
                        }, t -> handler.handle(Future.failedFuture(t)), () -> { //set expiration and retrieve record_ids
                            Observable
                                    .zip(redisClient.rxExpire(zSetName, Constants.EXPIRE_AFTER).toObservable(), // set expiration
                                            redisClient
                                                    .rxZrevrangebyscore(zSetName, "1", "0", rangeLimitOptions)
                                                    .toObservable(), // list of record_ids as JsonArray
                                            (a, b) -> Observable.from(b))
                                    .flatMap(x -> x)
                                    .map(handle -> redisClient
                                            .rxHgetall(String.format(HASH_NAME_FORMAT, handle)).toObservable()) // retrieve hash from redis
                                    .flatMap(x -> x).map(json -> toEntry(json))
                                    .collect(() -> new JsonArray(), (eList, e) -> eList.add(e))
                                    .subscribe(collectedJson -> handler
                                            .handle(Future.succeededFuture(collectedJson)), t -> {
                                                System.out.println("XXXX: " + t);
                                                logger.error("XXX", t);
                                                handler.handle(Future.failedFuture(t));
                                            });
                            //                        });
                        });
            }, t -> {
                CharArrayWriter cw = new CharArrayWriter();
                PrintWriter w = new PrintWriter(cw);
                t.printStackTrace(w);
                w.close();
                logger.error("trace", cw.toString());
                logger.error("YYY", t);
                handler.handle(Future.failedFuture(t));
            });

}

From source file:fr.pjthin.vertx.client.UserDaoVertxEBProxy.java

License:Apache License

public void save(User newUser, Handler<AsyncResult<String>> complete) {
    if (closed) {
        complete.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
        return;/*  w  w  w.j  av  a2s .  co  m*/
    }
    JsonObject _json = new JsonObject();
    _json.put("newUser", newUser == null ? null : newUser.toJson());
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options)
            : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "save");
    _vertx.eventBus().<String>send(_address, _json, _deliveryOptions, res -> {
        if (res.failed()) {
            complete.handle(Future.failedFuture(res.cause()));
        } else {
            complete.handle(Future.succeededFuture(res.result().body()));
        }
    });
}

From source file:fr.pjthin.vertx.client.UserDaoVertxEBProxy.java

License:Apache License

public void findAll(Handler<AsyncResult<List<User>>> complete) {
    if (closed) {
        complete.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
        return;//from  w w  w .  ja va 2s . co m
    }
    JsonObject _json = new JsonObject();
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options)
            : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "findAll");
    _vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> {
        if (res.failed()) {
            complete.handle(Future.failedFuture(res.cause()));
        } else {
            complete.handle(Future.succeededFuture(res.result().body().stream()
                    .map(o -> o instanceof Map ? new User(new JsonObject((Map) o)) : new User((JsonObject) o))
                    .collect(Collectors.toList())));
        }
    });
}

From source file:fr.pjthin.vertx.client.UserDaoVertxEBProxy.java

License:Apache License

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