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:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void searchIndexByValueBlocking(String fieldName, String indexName, String min, String max,
        Integer offset, Integer limit, AsyncResultHandler<List<String>> resultHandler) {
    redissonOther.<String>getLexSortedSet(getScoredSortedIndexKey(fieldName, indexName))
            .lexRangeAsync(min, true, max, true, offset, limit).addListener(future -> {
                Collection<String> res = (Collection<String>) future.get();
                try {
                    ArrayList<String> ids = res.stream().map(r -> lookupIdFromIndex(r, fieldName, indexName))
                            .collect(Collectors.toCollection(ArrayList::new));
                    resultHandler/*from   w w w .j  a  va2  s.com*/
                            .handle(future.isSuccess()
                                    ? (future.get() != null ? Future.succeededFuture(ids)
                                            : Future.failedFuture(
                                                    new RepositoryException("No search result returned")))
                                    : Future.failedFuture(new RepositoryException(future.cause())));
                    if (future.isSuccess()) {
                        logger.debug("[" + getStorageKey() + "] Search Index By Value Success. Records: "
                                + ((Collection<String>) future.get()).size());
                    } else {
                        logger.debug("[" + getStorageKey() + "] Search Index By Value Failure.",
                                future.cause());
                    }
                } catch (RuntimeException e) {
                    resultHandler.handle(Future.failedFuture(e.getCause()));
                    logger.debug("[" + getStorageKey() + "] Search Index By Value Failure.", e);
                }
            });
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void create(String data, RBatch redissonBatch, AsyncResultHandler<String> resultHandler) {
    vertx.<JsonObject>executeBlocking(f -> {
        JsonObject d = new JsonObject(data);
        if (schema == null && !f.isComplete()) {
            f.complete(d);/*  w w  w .  j a  v a2s  .c o m*/
            return;
        }
        try {
            ProcessingReport validate = VALIDATOR.validate(schema, Json.mapper.readTree(data));
            if (validate.isSuccess() && !d.containsKey("id") && !f.isComplete()) {
                f.complete(d);
            } else if (!f.isComplete()) {
                f.fail(new RepositoryException("Invalid Data"));
            }
        } catch (ProcessingException | IOException ex) {
            if (!f.isComplete()) {
                f.fail(ex);
            }
        }
    }, result -> {
        if (result.succeeded()) {
            createWithoutValidate(result.result(), redissonBatch, resultHandler);
        } else {
            resultHandler.handle(Future.failedFuture(result.cause()));
        }
    });
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void createWithoutValidate(JsonObject data, RBatch redissonBatch,
        AsyncResultHandler<String> resultHandler) {
    AtomicReference<String> id = new AtomicReference<>();
    Async.waterfall().<String>task(this::newId).<String>task((i, t) -> {
        id.set(i);//from www.  ja  va  2  s.  c  o  m
        ensureUniqueAndIndexing(id.get(), data, true, rs -> {
            if (rs.succeeded() && rs.result() == null) {
                t.handle(Future.succeededFuture());
            } else if (rs.result() != null) {
                t.handle(Future.failedFuture(new RepositoryException(rs.result())));
            } else {
                t.handle(Future.failedFuture(rs.cause()));
            }
        });
    }).<Boolean>task((rs, t) -> {
        persist(id.get(), data.put("id", id.get()), redissonBatch, t);
    }).run(run -> {
        resultHandler
                .handle(run.succeeded() ? Future.succeededFuture(id.get()) : Future.failedFuture(run.cause()));
    });
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void update(String id, String data, RBatch redissonBatch, Handler<AsyncResult<Boolean>> resultHandler) {
    vertx.<JsonObject>executeBlocking(f -> {
        JsonObject d = new JsonObject(data);
        if (schema == null && !f.isComplete()) {
            f.complete(d);//from   w  w w.j  ava  2  s. c om
            return;
        }
        try {
            ProcessingReport validate = VALIDATOR.validate(schema, Json.mapper.readTree(data));
            if (id != null && validate.isSuccess() && d.containsKey("id") && id.equals(d.getString("id"))
                    && !f.isComplete()) {
                f.complete(d);
            } else if (!f.isComplete()) {
                f.fail(new RepositoryException("Invalid Data"));
            }
        } catch (ProcessingException | IOException ex) {
            if (!f.isComplete()) {
                f.fail(ex);
            }
        }
    }, result -> {
        if (result.succeeded()) {
            updateWithoutValidate(id, result.result(), redissonBatch, resultHandler);
        } else {
            resultHandler.handle(Future.failedFuture(result.cause()));
        }
    });
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void updateWithoutValidate(String id, JsonObject data, RBatch redissonBatch,
        Handler<AsyncResult<Boolean>> resultHandler) {
    vertx.<Boolean>executeBlocking(f -> {
        Async.waterfall().<Boolean>task(t -> idExist(id, t)).<String>task((idExist, t) -> {
            if (!idExist) {
                t.handle(Future.failedFuture(new RepositoryException("ID: " + id + " does not exist")));
                return;
            }//from ww w  .  j a  v  a2 s. c o  m
            ensureUniqueAndIndexing(id, data, false, rs -> {
                if (rs.succeeded() && rs.result() == null) {
                    t.handle(Future.succeededFuture());
                } else if (rs.result() != null) {
                    t.handle(Future.failedFuture(rs.result()));
                } else {
                    t.handle(Future.failedFuture(rs.cause()));
                }
            });

        }).<Boolean>task((rs, t) -> persist(id, data, redissonBatch, t)).run(run -> {
            if (run.succeeded() && !f.isComplete()) {
                f.complete(run.result());
            } else if (!f.isComplete()) {
                f.fail(run.cause());
            }
        });
    }, resultHandler);
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void deleteBlocking(String id, Handler<AsyncResult<Boolean>> resultHandler) {
    RBatch batch = redissonWrite.createBatch();
    //remove the indexes.
    batch.<String, String>getMap(getStorageKey(), StringCodec.INSTANCE).fastRemoveAsync(id);
    batch.getAtomicLongAsync(getCounterKey()).decrementAndGetAsync();
    batch.executeAsync().addListener(future -> {
        resultHandler.handle(future.isSuccess()
                ? (future.get() != null ? Future.succeededFuture(((Integer) ((List) future.get()).get(0)) == 1)
                        : Future.failedFuture(new RepositoryException("No batch result returned")))
                : Future.failedFuture(new RepositoryException(future.cause())));
        if (future.isSuccess()) {
            logger.debug("[" + getStorageKey() + "] Delete Success : " + id);
        } else {/*from   w  w  w .  j  a  v a 2  s . com*/
            logger.debug("[" + getStorageKey() + "] Delete Failure : " + id, future.cause());
        }
    });
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

@Override
public void totalCount(Handler<AsyncResult<Long>> resultHandler) {
    redissonOther.<String, String>getAtomicLong(getCounterKey()).getAsync().addListener(future -> {
        resultHandler.handle(future.isSuccess()
                ? (future.get() != null ? Future.succeededFuture((Long) future.get())
                        : Future.failedFuture(new RepositoryException("No search result returned")))
                : Future.failedFuture(new RepositoryException(future.cause())));
        if (future.isSuccess()) {
            logger.debug("[" + getCounterKey() + "] Count Success : " + (Long) future.get());
        } else {/*from   www .  ja  va2  s .  com*/
            logger.debug("[" + getCounterKey() + "] Count Failure ", future.cause());
        }
    });
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void idExist(String id, Handler<AsyncResult<Boolean>> resultHandler) {
    redissonOther.<String, String>getMap(getStorageKey(), StringCodec.INSTANCE).containsKeyAsync(id)
            .addListener(future -> {//from  w  w w  . j a  va  2 s.  c  om
                resultHandler
                        .handle(future.isSuccess()
                                ? (future.get() != null ? Future.succeededFuture((Boolean) future.get())
                                        : Future.failedFuture(
                                                new RepositoryException("No search result returned")))
                                : Future.failedFuture(new RepositoryException(future.cause())));
                if (future.isSuccess()) {
                    logger.debug("[" + getStorageKey() + "] ID Exist Success : " + id);
                } else {
                    logger.debug("[" + getStorageKey() + "] ID Exist Failure : " + id, future.cause());
                }
            });
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void getIdByUnique(String fieldName, String value, AsyncResultHandler<String> resultHandler) {
    redissonOther.<String, String>getMap(getUniqueKey(fieldName)).getAsync(value).addListener(future -> {
        resultHandler.handle(future.isSuccess()
                ? (future.get() != null ? Future.succeededFuture((String) future.get())
                        : Future.failedFuture(new RepositoryException("No search result returned")))
                : Future.failedFuture(new RepositoryException(future.cause())));
        if (future.isSuccess()) {
            logger.debug("[" + getStorageKey() + "] Get ID By Unique Success : " + value + " - "
                    + (String) future.get());
        } else {/*from w ww .j a v  a  2  s .  c o m*/
            logger.debug("[" + getStorageKey() + "] Get ID By Unique : " + value, future.cause());
        }
    });
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void ensureUniqueAndIndexingBlocking(String id, JsonObject data, Boolean isNew,
        AsyncResultHandler<String> resultHandler) {
    Async.waterfall().<String>task(t -> {
        RBatch batch = redissonOther.createBatch();
        ArrayList<String> pList = new ArrayList();
        try {//from  w  ww .  j a  va 2  s .  co m
            prepareEnsureUnique(id, data, batch, pList, null);
        } catch (RepositoryException ex) {
            t.handle(Future.failedFuture(ex));
            return;
        }
        if (pList.isEmpty()) {
            t.handle(Future.succeededFuture());
            return;
        }
        batch.executeAsync().addListener(future -> {
            if (future.isSuccess() && future.get() != null) {
                List<String> result = (List<String>) future.get();
                Stream<String> filter = pList.stream().filter(
                        p -> result.get(pList.indexOf(p)) != null && !result.get(pList.indexOf(p)).equals(id));//uniques are ensured by using putIfAbsent and all results should be null or itself to indicate no violation.
                Object[] filterArray = filter.toArray();
                if (filterArray.length != 0) {
                    t.handle(Future.succeededFuture(
                            new JsonObject().put("uniqueViolation", Json.encode(filterArray)).encode()));
                    //now undo these things.
                    ArrayList<String> undoList = pList.stream()
                            .filter(p -> result.get(pList.indexOf(p)) == null
                                    || result.get(pList.indexOf(p)).equals(id))
                            .collect(Collectors.toCollection(ArrayList::new));
                    Async.<Void>waterfall().<Void>task(task -> {
                        RBatch b = redissonOther.createBatch();
                        try {
                            prepareUndoUnique(id, data, b, undoList, null);
                        } catch (RepositoryException ex) {
                            task.handle(Future.failedFuture(ex));
                        }
                        b.executeAsync().addListener(fu -> {
                            task.handle(fu.isSuccess() ? Future.succeededFuture((Void) fu.get())
                                    : Future.failedFuture(fu.cause()));
                        });
                    }).run(run -> {
                        logger.debug("Parallel undo indexing [id: " + id + "] "
                                + (run.succeeded() ? "successed." : "failed."));
                    });
                } else {
                    t.handle(Future.succeededFuture());
                }
            } else {
                t.handle(Future.failedFuture(!future.isSuccess() ? future.cause().fillInStackTrace()
                        : new RepositoryException("No unique check result returned")));
            }
        });
    }).<String>task((violations, t) -> {
        if (violations != null) {
            t.handle(Future.failedFuture(violations));
            return;
        } else {
            t.handle(Future.succeededFuture());
        }
        //parallel indexing
        Async.<Void>waterfall().<T>task(task -> {
            if (!isNew) {
                fetch(id, Boolean.TRUE, task);
            } else {
                task.handle(Future.succeededFuture(null));
            }
        }).<Void>task((r, task) -> {
            reIndex(id, r, data, isNew, ri -> {
                task.handle(
                        ri.succeeded() ? Future.succeededFuture(ri.result()) : Future.failedFuture(ri.cause()));
            });
        }).run(run -> {
            logger.debug("Parallel Indexing [id: " + id + "] " + (run.succeeded() ? "successed." : "failed."),
                    run.cause());
        });
    }).run(resultHandler);

}