Example usage for com.google.common.util.concurrent Futures transformAsync

List of usage examples for com.google.common.util.concurrent Futures transformAsync

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures transformAsync.

Prototype

public static <I, O> ListenableFuture<O> transformAsync(ListenableFuture<I> input,
        AsyncFunction<? super I, ? extends O> function) 

Source Link

Document

Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future .

Usage

From source file:google.registry.bigquery.BigqueryConnection.java

/**
 * Starts an asynchronous job to run the provided query, store the results in a temporary table,
 * and then extract the contents of that table to the given GCS filepath in the specified
 * destination format, optionally printing headers.
 *
 * <p>Returns a ListenableFuture that holds the destination GCS URI on success.
 *//* w  w  w  . j a  v a  2  s .c om*/
public ListenableFuture<String> extractQuery(String querySql, final String destinationUri,
        final DestinationFormat destinationFormat, final boolean printHeader) {
    // Note: although BigQuery queries save their results to an auto-generated anonymous table,
    // we can't rely on that for running the extract job because it may not be fully replicated.
    // Tracking bug for query-to-GCS support is b/13777340.
    DestinationTable tempTable = buildTemporaryTable().build();
    return Futures.transformAsync(query(querySql, tempTable), new AsyncFunction<DestinationTable, String>() {
        @Override
        public ListenableFuture<String> apply(DestinationTable tempTable) {
            return extractTable(tempTable, destinationUri, destinationFormat, printHeader);
        }
    });
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchRefresh.java

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processCatalogs(final List<String> catalogNames) {
    log.info("Start: Full refresh of catalogs: {}", catalogNames);
    final List<ListenableFuture<CatalogDto>> getCatalogFutures = catalogNames.stream()
            .map(catalogName -> service.submit(() -> {
                CatalogDto result = null;
                try {
                    result = getCatalog(catalogName);
                } catch (Exception e) {
                    log.error("Failed to retrieve catalog: {}", catalogName);
                    elasticSearchUtil.log("ElasticSearchRefresh.getCatalog",
                            ElasticSearchDoc.Type.catalog.name(), catalogName, null, e.getMessage(), e, true);
                }//from  ww w . ja  va2 s. c o  m
                return result;
            })).collect(Collectors.toList());
    return Futures.transformAsync(Futures.successfulAsList(getCatalogFutures), input -> {
        final List<ListenableFuture<Void>> processCatalogFutures = input.stream().filter(NOT_NULL)
                .map(catalogDto -> {
                    final List<QualifiedName> databaseNames = getDatabaseNamesToRefresh(catalogDto);
                    return _processDatabases(catalogDto.getName(), databaseNames);
                }).filter(NOT_NULL).collect(Collectors.toList());
        return Futures.transform(Futures.successfulAsList(processCatalogFutures), Functions.constant(null));
    });
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchMetacatRefresh.java

/**
 * Process the list of databases./*  w w  w .j  a  v  a2s  . co m*/
 *
 * @param catalogName   catalog name
 * @param databaseNames database names
 * @return future
 */
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processDatabases(final QualifiedName catalogName,
        final List<QualifiedName> databaseNames) {
    ListenableFuture<Void> resultFuture = null;
    log.info("Full refresh of catalog {} for databases({}): {}", catalogName, databaseNames.size(),
            databaseNames);
    final List<ListenableFuture<DatabaseDto>> getDatabaseFutures = databaseNames.stream()
            .map(databaseName -> service.submit(() -> {
                DatabaseDto result = null;
                try {
                    result = getDatabase(databaseName);
                } catch (Exception e) {
                    log.error("Failed to retrieve database: {}", databaseName);
                    elasticSearchUtil.log("ElasticSearchMetacatRefresh.getDatabase",
                            ElasticSearchDoc.Type.database.name(), databaseName.toString(), null,
                            e.getMessage(), e, true);
                }
                return result;
            })).collect(Collectors.toList());

    if (getDatabaseFutures != null && !getDatabaseFutures.isEmpty()) {
        resultFuture = Futures.transformAsync(Futures.successfulAsList(getDatabaseFutures), input -> {
            final ListenableFuture<Void> processDatabaseFuture = indexDatabaseDtos(catalogName, input);
            final List<ListenableFuture<Void>> processDatabaseFutures = input.stream().filter(NOT_NULL)
                    .map(databaseDto -> {
                        final List<QualifiedName> tableNames = databaseDto.getTables().stream()
                                .map(s -> QualifiedName.ofTable(databaseDto.getName().getCatalogName(),
                                        databaseDto.getName().getDatabaseName(), s))
                                .collect(Collectors.toList());
                        log.info("Full refresh of database {} for tables({}): {}",
                                databaseDto.getName().toString(), databaseDto.getTables().size(),
                                databaseDto.getTables());
                        return processTables(databaseDto.getName(), tableNames);
                    }).filter(NOT_NULL).collect(Collectors.toList());
            processDatabaseFutures.add(processDatabaseFuture);
            return Futures.transform(Futures.successfulAsList(processDatabaseFutures),
                    Functions.constant(null));
        });
    }

    return resultFuture;
}

From source file:org.bitcoinj.protocols.channels.PaymentChannelServer.java

@GuardedBy("lock")
private void settlePayment(final CloseReason clientRequestedClose) throws InsufficientMoneyException {
    // Setting channelSettling here prevents us from sending another CLOSE when state.close() calls
    // close() on us here below via the stored channel state.
    // TODO: Strongly separate the lifecycle of the payment channel from the TCP connection in these classes.
    channelSettling = true;//ww w  .  j  ava2  s  .c o m
    ListenableFuture<KeyParameter> keyFuture = conn.getUserKey();
    ListenableFuture<Transaction> result;
    if (keyFuture != null) {
        result = Futures.transformAsync(conn.getUserKey(), new AsyncFunction<KeyParameter, Transaction>() {
            @Override
            public ListenableFuture<Transaction> apply(KeyParameter userKey) throws Exception {
                return state.close(userKey);
            }
        });
    } else {
        result = state.close();
    }
    Futures.addCallback(result, new FutureCallback<Transaction>() {
        @Override
        public void onSuccess(Transaction result) {
            // Send the successfully accepted transaction back to the client.
            final Protos.TwoWayChannelMessage.Builder msg = Protos.TwoWayChannelMessage.newBuilder();
            msg.setType(Protos.TwoWayChannelMessage.MessageType.CLOSE);
            if (result != null) {
                // Result can be null on various error paths, like if we never actually opened
                // properly and so on.
                msg.getSettlementBuilder().setTx(ByteString.copyFrom(result.unsafeBitcoinSerialize()));
                log.info("Sending CLOSE back with broadcast settlement tx.");
            } else {
                log.info("Sending CLOSE back without broadcast settlement tx.");
            }
            conn.sendToClient(msg.build());
            conn.destroyConnection(clientRequestedClose);
        }

        @Override
        public void onFailure(Throwable t) {
            log.error("Failed to broadcast settlement tx", t);
            conn.destroyConnection(clientRequestedClose);
        }
    });
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchRefresh.java

/**
 * Process the list of databases./*from w w  w .jav a  2s . co m*/
 *
 * @param catalogName   catalog name
 * @param databaseNames database names
 * @return future
 */
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processDatabases(final QualifiedName catalogName,
        final List<QualifiedName> databaseNames) {
    ListenableFuture<Void> resultFuture = null;
    log.info("Full refresh of catalog {} for databases({}): {}", catalogName, databaseNames.size(),
            databaseNames);
    final List<ListenableFuture<DatabaseDto>> getDatabaseFutures = databaseNames.stream()
            .map(databaseName -> service.submit(() -> {
                DatabaseDto result = null;
                try {
                    result = getDatabase(databaseName);
                } catch (Exception e) {
                    log.error("Failed to retrieve database: {}", databaseName);
                    elasticSearchUtil.log("ElasticSearchRefresh.getDatabase",
                            ElasticSearchDoc.Type.database.name(), databaseName.toString(), null,
                            e.getMessage(), e, true);
                }
                return result;
            })).collect(Collectors.toList());

    if (getDatabaseFutures != null && !getDatabaseFutures.isEmpty()) {
        resultFuture = Futures.transformAsync(Futures.successfulAsList(getDatabaseFutures), input -> {
            final ListenableFuture<Void> processDatabaseFuture = indexDatabaseDtos(catalogName, input);
            final List<ListenableFuture<Void>> processDatabaseFutures = input.stream().filter(NOT_NULL)
                    .map(databaseDto -> {
                        final List<QualifiedName> tableNames = databaseDto.getTables().stream()
                                .map(s -> QualifiedName.ofTable(databaseDto.getName().getCatalogName(),
                                        databaseDto.getName().getDatabaseName(), s))
                                .collect(Collectors.toList());
                        log.info("Full refresh of database {} for tables({}): {}", databaseDto.getName(),
                                databaseDto.getTables().size(), databaseDto.getTables());
                        return processTables(databaseDto.getName(), tableNames);
                    }).filter(NOT_NULL).collect(Collectors.toList());
            processDatabaseFutures.add(processDatabaseFuture);
            return Futures.transform(Futures.successfulAsList(processDatabaseFutures),
                    Functions.constant(null));
        });
    }

    return resultFuture;
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchMetacatRefresh.java

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processTables(final QualifiedName databaseName,
        final List<QualifiedName> tableNames) {
    final List<ListenableFuture<Optional<TableDto>>> getTableFutures = tableNames.stream()
            .map(tableName -> service.submit(() -> {
                Optional<TableDto> result = null;
                try {
                    result = getTable(tableName);
                } catch (Exception e) {
                    log.error("Failed to retrieve table: {}", tableName);
                    elasticSearchUtil.log("ElasticSearchMetacatRefresh.getTable",
                            ElasticSearchDoc.Type.table.name(), tableName.toString(), null, e.getMessage(), e,
                            true);//from  ww  w . jav  a  2  s  .com
                }
                return result;
            })).collect(Collectors.toList());

    return Futures.transformAsync(Futures.successfulAsList(getTableFutures),
            input -> indexTableDtos(databaseName, input));
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchRefresh.java

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processTables(final QualifiedName databaseName,
        final List<QualifiedName> tableNames) {
    final List<ListenableFuture<Optional<TableDto>>> getTableFutures = tableNames.stream()
            .map(tableName -> service.submit(() -> {
                Optional<TableDto> result = null;
                try {
                    result = getTable(tableName);
                } catch (Exception e) {
                    log.error("Failed to retrieve table: {}", tableName);
                    elasticSearchUtil.log("ElasticSearchRefresh.getTable", ElasticSearchDoc.Type.table.name(),
                            tableName.toString(), null, e.getMessage(), e, true);
                }//from  w w w .j  a v a  2 s.c o m
                return result;
            })).collect(Collectors.toList());

    return Futures.transformAsync(Futures.successfulAsList(getTableFutures),
            input -> indexTableDtos(databaseName, input));
}