me.escoffier.vertx.completablefuture.VertxCompletableFuture Java Examples

The following examples show how to use me.escoffier.vertx.completablefuture.VertxCompletableFuture. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AsyncWorker.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the specified action using a thread from the worker pool.
 *
 * @param action
 * @return a completion stage with the result of the specified action
 * @see Vertx#executeBlocking(io.vertx.core.Handler, io.vertx.core.Handler)
 */
public <V> CompletionStage<V> performBlocking(Callable<V> action) {
    VertxCompletableFuture<V> future = new VertxCompletableFuture<>(vertx);
    vertx.<V> executeBlocking((f -> {
        try {
            f.complete(action.call());
        } catch (Exception e) {
            f.fail(e);
        }
    }), false, (r) -> {
        if (r.succeeded()) {
            future.complete(r.result());
        } else {
            future.completeExceptionally(r.cause());
        }
    });
    return future;
}
 
Example #2
Source File: CompletableFutureTestBase.java    From vertx-jooq with MIT License 6 votes vote down vote up
@Test
public void findOneByConditionWithMultipleMatchesShouldFail() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    O someO = createSomeO();
    CompletableFuture<T> insertFuture1 = insertAndReturn(setSomeO(create(), someO));
    CompletableFuture<T> insertFuture2 = insertAndReturn(setSomeO(create(), someO));
    VertxCompletableFuture.allOf(insertFuture1, insertFuture2)
            .thenCompose(v -> dao.findOneByCondition(otherfield.eq(someO)))
            .handle((res, x) -> {
                Assert.assertNotNull(x);
                //cursor found more than one row
                Assert.assertEquals(TooManyRowsException.class, x.getCause().getClass());
                return null;
            })
            .thenCompose(v -> dao.deleteByCondition(otherfield.eq(someO)))
            .whenComplete(countdownLatchHandler(latch));
    await(latch);
}
 
Example #3
Source File: AsyncReferenceImpl.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
@Inject
public AsyncReferenceImpl(InjectionPoint injectionPoint, Vertx vertx, BeanManager beanManager, @Any WeldInstance<Object> instance) {
    this.isDone = new AtomicBoolean(false);
    this.future = new VertxCompletableFuture<>(vertx);
    this.instance = instance;

    ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType();
    Type requiredType = parameterizedType.getActualTypeArguments()[0];
    Annotation[] qualifiers = injectionPoint.getQualifiers().toArray(new Annotation[] {});

    // First check if there is a relevant async producer method available
    WeldInstance<Object> completionStage = instance.select(new ParameterizedTypeImpl(CompletionStage.class, requiredType), qualifiers);

    if (completionStage.isAmbiguous()) {
        failure(new AmbiguousResolutionException(
                "Ambiguous async producer methods for type " + requiredType + " with qualifiers " + injectionPoint.getQualifiers()));
    } else if (!completionStage.isUnsatisfied()) {
        // Use the produced CompletionStage
        initWithCompletionStage(completionStage.getHandler());
    } else {
        // Use Vertx worker thread
        initWithWorker(requiredType, qualifiers, vertx, beanManager);
    }
}
 
Example #4
Source File: AsyncCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 6 votes vote down vote up
@Override
public <Q extends Record> CompletableFuture<List<JsonObject>> findManyJson(Function<DSLContext, ? extends ResultQuery<Q>> queryFunction) {
    return getConnection().thenCompose(safeExecute(sqlConnection -> {
        Query query = createQuery(queryFunction);
        log(query);
        CompletableFuture<List<JsonObject>> cf = new VertxCompletableFuture<>(vertx);
        sqlConnection.queryWithParams(
                query.getSQL(),
                getBindValues(query),
                executeAndClose(ResultSet::getRows,
                        sqlConnection,
                        cf)
        );
        return cf;
    }));
}
 
Example #5
Source File: AsyncCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 6 votes vote down vote up
@Override
public <Q extends Record> CompletableFuture<JsonObject> findOneJson(Function<DSLContext, ? extends ResultQuery<Q>> queryFunction) {
    return getConnection().thenCompose(safeExecute(sqlConnection -> {
        Query query = createQuery(queryFunction);
        log(query);
        CompletableFuture<JsonObject> cf = new VertxCompletableFuture<>(vertx);
        sqlConnection.queryWithParams(query.getSQL(), getBindValues(query), executeAndClose(rs -> {
            List<JsonObject> rows = rs.getRows();
            switch (rows.size()) {
                case 0: return null;
                case 1: return rows.get(0);
                default: throw new TooManyRowsException(String.format("Found more than one row: %d", rows.size()));
            }
        }, sqlConnection, cf));
        return cf;
    }));
}
 
Example #6
Source File: AsyncCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Integer> execute(Function<DSLContext, ? extends Query> queryFunction) {
    return getConnection().thenCompose(safeExecute(sqlConnection -> {
        Query query = createQuery(queryFunction);
        log(query);
        CompletableFuture<Integer> cf = new VertxCompletableFuture<>(vertx);
        JsonArray bindValues = getBindValues(query);
        sqlConnection.updateWithParams(query.getSQL(), bindValues, executeAndClose(UpdateResult::getUpdated,sqlConnection,cf));
        return cf;
    }));
}
 
Example #7
Source File: ReactiveCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * Executes the given queryFunction and returns a <code>RowSet</code>
 * @param queryFunction the query to execute
 * @return the results, never null
 */
public CompletableFuture<RowSet<Row>> executeAny(Function<DSLContext, ? extends Query> queryFunction) {
    Query query = createQuery(queryFunction);
    log(query);
    CompletableFuture<RowSet<Row>> rowFuture = new VertxCompletableFuture<>(vertx);
    delegate.preparedQuery(toPreparedQuery(query)).execute(getBindValues(query),createCompletionHandler(rowFuture));
    return rowFuture;
}
 
Example #8
Source File: ReactiveCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * Rolls a transaction back.
 * @return a <code>CompletableFuture</code> that completes when the transaction has been rolled back.
 * @throws IllegalStateException if not called <code>beginTransaction</code> before.
 */
public CompletableFuture<Void> rollback(){
    if(!(delegate instanceof Transaction)){
        throw new IllegalStateException("Not in transaction");
    }
    CompletableFuture<Void> commit = new VertxCompletableFuture<>(vertx);
    ((Transaction) delegate).rollback(createCompletionHandler(commit));
    return commit;
}
 
Example #9
Source File: ReactiveCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * @return an instance of a <code>ReactiveCompletableFutureGenericQueryExecutor</code> that performs all CRUD
 * functions in the scope of a transaction. The transaction has to be committed/rolled back by calling <code>commit</code>
 * or <code>rollback</code> on the QueryExecutor returned.
 */
public CompletableFuture<? extends ReactiveCompletableFutureGenericQueryExecutor> beginTransaction(){
    if(delegate instanceof Transaction){
        throw new IllegalStateException("Already in transaction");
    }
    CompletableFuture<Transaction> transactionFuture = new VertxCompletableFuture<>(vertx);
    ((Pool) delegate).begin(createCompletionHandler(transactionFuture));
    return transactionFuture.thenApply(newInstance());
}
 
Example #10
Source File: ReactiveCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Integer> execute(Function<DSLContext, ? extends Query> queryFunction) {
    Query query = createQuery(queryFunction);
    log(query);
    CompletableFuture<RowSet<Row>> rowFuture = new VertxCompletableFuture<>(vertx);
    delegate.preparedQuery(toPreparedQuery(query)).execute(getBindValues(query),createCompletionHandler(rowFuture));
    return rowFuture.thenApply(SqlResult::rowCount);
}
 
Example #11
Source File: JDBCCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * @param future
 * @param <U>
 * @return A handler which completes the given future.
 */
private static <U> Handler<AsyncResult<U>> createCompletionHandler(VertxCompletableFuture<U> future) {
    return h->{
        if(h.succeeded()){
            future.complete(h.result());
        }else{
            future.completeExceptionally(h.cause());
        }
    };
}
 
Example #12
Source File: AsyncCompletableFutureQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<T> insertReturning(Function<DSLContext, ? extends InsertResultStep<R>> queryFunction, Function<Object, T> keyMapper) {
    return getConnection().thenCompose(safeExecute(sqlConnection -> {
        Query query = createQuery(queryFunction);
        log(query);
        CompletableFuture<Object> cf = new VertxCompletableFuture<>(vertx);
        if(isMysql){
            sqlConnection.updateWithParams(
                    query.getSQL(),
                    getBindValues(query),
                    this.<UpdateResult, Object>executeAndClose(UpdateResult::getKeys,
                            sqlConnection,
                            cf)
            );
        }else{
            sqlConnection.queryWithParams(
                    query.getSQL(),
                    getBindValues(query),
                    this.<ResultSet, Object>executeAndClose(res -> res.getResults().get(0),
                            sqlConnection,
                            cf)
            );
        }
        return cf.thenApply(keyMapper);
    }));
}
 
Example #13
Source File: AsyncCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
protected <U> Function<SQLConnection,CompletableFuture<U>> safeExecute(Function<SQLConnection,CompletableFuture<U>> action){
    return sqlConnection -> {
        try{
            return action.apply(sqlConnection);
        }catch(Throwable e){
            sqlConnection.close();
            CompletableFuture<U> cf = new VertxCompletableFuture<>(vertx);
            cf.completeExceptionally(e);
            return cf;
        }
    };
}
 
Example #14
Source File: AsyncCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * @return a CompletableFuture that returns a SQLConnection or an Exception.
 */
protected CompletableFuture<SQLConnection> getConnection(){
    CompletableFuture<SQLConnection> cf = new VertxCompletableFuture<>(vertx);
    delegate.getConnection(h -> {
        if (h.succeeded()) {
            cf.complete(h.result());
        } else {
            cf.completeExceptionally(h.cause());
        }
    });
    return cf;
}
 
Example #15
Source File: CompletableFutureTestBase.java    From vertx-jooq with MIT License 5 votes vote down vote up
@Test
public void findAllShouldReturnValues() throws InterruptedException{
    CountDownLatch latch = new CountDownLatch(1);
    CompletableFuture<T> insertFuture1 = insertAndReturn(create());
    CompletableFuture<T> insertFuture2 = insertAndReturn(create());
    VertxCompletableFuture.allOf(insertFuture1, insertFuture2).
            thenCompose(v -> dao.findAll()).
            thenAccept(list -> {
                Assert.assertNotNull(list);
                Assert.assertEquals(2, list.size());
            }).
            thenCompose(v -> dao.deleteByCondition(DSL.trueCondition())).
            whenComplete(countdownLatchHandler(latch));
    await(latch);
}
 
Example #16
Source File: CompletableFutureTestBase.java    From vertx-jooq with MIT License 5 votes vote down vote up
@Test
public void findManyByConditionWithMultipleMatchesShouldSucceed() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    O someO = createSomeO();
    CompletableFuture<T> insertFuture1 = insertAndReturn(setSomeO(create(), someO));
    CompletableFuture<T> insertFuture2 = insertAndReturn(setSomeO(create(), someO));
    VertxCompletableFuture.allOf(insertFuture1, insertFuture2).
            thenCompose(v -> dao.findManyByCondition(otherfield.eq(someO))).
            thenAccept(values -> Assert.assertEquals(2, values.size())).
            thenCompose(v -> dao.deleteByCondition(otherfield.eq(someO))).
            whenComplete(countdownLatchHandler(latch));
    await(latch);
}
 
Example #17
Source File: HttpClientTest.java    From vertx-completable-future with Apache License 2.0 5 votes vote down vote up
@Test
public void test(TestContext tc) {
  Async async = tc.async();

  HttpClientOptions options = new HttpClientOptions().setDefaultPort(8080).setDefaultHost("localhost");
  HttpClient client1 = vertx.createHttpClient(options);
  HttpClient client2 = vertx.createHttpClient(options);

  VertxCompletableFuture<Integer> requestA = new VertxCompletableFuture<>(vertx);
  client1.get("/A").handler(resp -> {
    resp.exceptionHandler(requestA::completeExceptionally)
        .bodyHandler(buffer -> {
          requestA.complete(Integer.parseInt(buffer.toString()));
        });
  }).exceptionHandler(requestA::completeExceptionally).end();

  VertxCompletableFuture<Integer> requestB = new VertxCompletableFuture<>(vertx);
  client2.get("/B").handler(resp -> {
    resp.exceptionHandler(requestB::completeExceptionally)
        .bodyHandler(buffer -> {
          requestB.complete(Integer.parseInt(buffer.toString()));
        });
  }).exceptionHandler(requestB::completeExceptionally).end();


  VertxCompletableFuture.allOf(requestA, requestB).thenApply(v -> requestA.join() + requestB.join())
      .thenAccept(i -> {
        tc.assertEquals(65, i);
        async.complete();
      });
}
 
Example #18
Source File: AsyncWorker.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
/**
 * Performs the specified action using the event-loop thread. The action should never block.
 *
 * @param action
 * @return a completion stage with the result of the specified action
 */
public <V> CompletionStage<V> perform(Callable<V> action) {
    VertxCompletableFuture<V> future = new VertxCompletableFuture<>(vertx);
    vertx.runOnContext(v -> {
        try {
            future.complete(action.call());
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
 
Example #19
Source File: JDBCCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 4 votes vote down vote up
/**
 * @param blockingCodeHandler
 * @param <U>
 * @return a CompletableFuture that is completed when the blocking code has been executed by Vertx.
 */
<U> CompletableFuture<U> executeBlocking(Handler<Promise<U>> blockingCodeHandler){
    VertxCompletableFuture<U> future = new VertxCompletableFuture<>(vertx);
    vertx.executeBlocking(blockingCodeHandler, false, createCompletionHandler(future));
    return future;
}