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

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

Introduction

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

Prototype

public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
        Function<? super I, ? extends O> function, Executor executor) 

Source Link

Document

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future .

Usage

From source file:org.thingsboard.server.dao.attributes.BaseAttributesDao.java

@Override
public ListenableFuture<List<AttributeKvEntry>> find(EntityId entityId, String attributeType,
        Collection<String> attributeKeys) {
    List<ListenableFuture<Optional<AttributeKvEntry>>> entries = new ArrayList<>();
    attributeKeys.forEach(attributeKey -> entries.add(find(entityId, attributeType, attributeKey)));
    return Futures.transform(Futures.allAsList(entries),
            (Function<List<Optional<AttributeKvEntry>>, ? extends List<AttributeKvEntry>>) input -> {
                List<AttributeKvEntry> result = new ArrayList<>();
                input.stream().filter(opt -> opt.isPresent()).forEach(opt -> result.add(opt.get()));
                return result;
            }, readResultsProcessingExecutor);
}

From source file:com.ebay.pulsar.metric.impl.cassandra.MetricsServiceCassandra.java

@Override
public ListenableFuture<List<Counter>> findCounters(String metric, String group) {
    ResultSetFuture future = dataAccess.findCounters(metric, group);
    return Futures.transform(future, mapCounters, metricsTasks);
}

From source file:com.facebook.buck.artifact_cache.RetryingCacheDecorator.java

@Override
public ListenableFuture<CacheResult> fetchAsync(@Nullable BuildTarget target, RuleKey ruleKey,
        LazyPath output) {//from w  w w. ja v a2  s  . c o  m
    List<String> allCacheErrors = new ArrayList<>();
    ListenableFuture<CacheResult> resultFuture = delegate.fetchAsync(target, ruleKey, output);
    for (int retryCount = 1; retryCount < maxFetchRetries; retryCount++) {
        int retryCountForLambda = retryCount;
        resultFuture = Futures.transformAsync(resultFuture, result -> {
            if (result.getType() != CacheResultType.ERROR) {
                return Futures.immediateFuture(result);
            }
            result.cacheError().ifPresent(allCacheErrors::add);
            LOG.info("Failed to fetch %s after %d/%d attempts, exception: %s", ruleKey, retryCountForLambda + 1,
                    maxFetchRetries, result.cacheError());
            return delegate.fetchAsync(target, ruleKey, output);
        });
    }
    return Futures.transform(resultFuture, result -> {
        if (result.getType() != CacheResultType.ERROR) {
            return result;
        }
        String msg = String.join("\n", allCacheErrors);
        if (!msg.contains(NoHealthyServersException.class.getName())) {
            buckEventBus.post(ConsoleEvent.warning("Failed to fetch %s over %s after %d attempts.", ruleKey,
                    cacheMode.name(), maxFetchRetries));
        }
        return CacheResult.builder().from(result).setCacheError(msg).build();
    }, MoreExecutors.directExecutor());
}

From source file:com.ebay.pulsar.metric.impl.cassandra.MetricsServiceCassandra.java

@Override
public ListenableFuture<List<RawNumericMetric>> findData(QueryParam queryParam) {
    ResultSetFuture future = dataAccess.findData(queryParam);
    return Futures.transform(future, mapQueryResultSet, metricsTasks);
}

From source file:org.thingsboard.server.dao.attributes.CassandraBaseAttributesDao.java

@Override
public ListenableFuture<Optional<AttributeKvEntry>> find(TenantId tenantId, EntityId entityId,
        String attributeType, String attributeKey) {
    Select.Where select = select().from(ATTRIBUTES_KV_CF)
            .where(eq(ENTITY_TYPE_COLUMN, entityId.getEntityType())).and(eq(ENTITY_ID_COLUMN, entityId.getId()))
            .and(eq(ATTRIBUTE_TYPE_COLUMN, attributeType)).and(eq(ATTRIBUTE_KEY_COLUMN, attributeKey));
    log.trace("Generated query [{}] for entityId {} and key {}", select, entityId, attributeKey);
    return Futures.transform(executeAsyncRead(tenantId, select),
            (Function<? super ResultSet, ? extends Optional<AttributeKvEntry>>) input -> Optional
                    .ofNullable(convertResultToAttributesKvEntry(attributeKey, input.one())),
            readResultsProcessingExecutor);
}

From source file:io.soliton.protobuf.json.JsonRpcRequestInvoker.java

/**
 * Actually invokes the server method.//from w ww.ja  v a 2 s.c om
 *
 * @param method the method to invoke
 * @param parameter the request's parameter
 * @param id the request's client-side identifier
 * @param <I> the method's input proto-type
 * @param <O> the method's output proto-type
 */
private <I extends Message, O extends Message> ListenableFuture<JsonRpcResponse> invoke(
        ServerMethod<I, O> method, JsonObject parameter, JsonElement id) {
    I request;
    try {
        request = (I) Messages.fromJson(method.inputBuilder(), parameter);
    } catch (Exception e) {
        serverLogger.logServerFailure(method, e);
        SettableFuture<JsonRpcResponse> future = SettableFuture.create();
        future.setException(e);
        return future;
    }
    ListenableFuture<O> response = method.invoke(request);
    return Futures.transform(response, new JsonConverter(id), TRANSFORM_EXECUTOR);
}

From source file:com.facebook.buck.core.build.engine.cache.manager.ManifestRuleKeyServiceImpl.java

@Override
public ListenableFuture<CacheResult> fetchManifest(final RuleKey manifestKey,
        final LazyPath downloadedManifest) {
    String key = toManifestServiceKey(manifestKey);
    final ListenableFuture<Manifest> future = manifestService.fetchManifest(key);
    final ListenableFuture<CacheResult> cacheResultFuture = Futures.transform(future,
            (manifest) -> writeManifestToFile(manifest, downloadedManifest), MoreExecutors.directExecutor());
    return Futures.catching(cacheResultFuture, IOException.class, (exception) -> {
        String msg = String.format("Failed to fetch manifest with error [%s].", exception);
        LOG.error(exception, msg);// w  w w.j  av  a 2  s  .c  o m
        return CacheResult.error(MANIFEST_SERVICE_SOURCE, ArtifactCacheMode.unknown, msg);
    }, MoreExecutors.directExecutor());
}

From source file:org.apache.cassandra.repair.RepairJob.java

/**
 * Runs repair job.//  w w  w.  j a  v a2s.  c  o m
 *
 * This sets up necessary task and runs them on given {@code taskExecutor}.
 * After submitting all tasks, waits until validation with replica completes.
 */
public void run() {
    List<InetAddress> allEndpoints = new ArrayList<>(session.endpoints);
    allEndpoints.add(FBUtilities.getBroadcastAddress());

    ListenableFuture<List<TreeResponse>> validations;
    // Create a snapshot at all nodes unless we're using pure parallel repairs
    if (parallelismDegree != RepairParallelism.PARALLEL) {
        // Request snapshot to all replica
        List<ListenableFuture<InetAddress>> snapshotTasks = new ArrayList<>(allEndpoints.size());
        for (InetAddress endpoint : allEndpoints) {
            SnapshotTask snapshotTask = new SnapshotTask(desc, endpoint);
            snapshotTasks.add(snapshotTask);
            taskExecutor.execute(snapshotTask);
        }
        // When all snapshot complete, send validation requests
        ListenableFuture<List<InetAddress>> allSnapshotTasks = Futures.allAsList(snapshotTasks);
        validations = Futures.transform(allSnapshotTasks,
                new AsyncFunction<List<InetAddress>, List<TreeResponse>>() {
                    public ListenableFuture<List<TreeResponse>> apply(List<InetAddress> endpoints)
                            throws Exception {
                        logger.info(String.format("[repair #%s] requesting merkle trees for %s (to %s)",
                                desc.sessionId, desc.columnFamily, endpoints));
                        if (parallelismDegree == RepairParallelism.SEQUENTIAL)
                            return sendSequentialValidationRequest(endpoints);
                        else
                            return sendDCAwareValidationRequest(endpoints);
                    }
                }, taskExecutor);
    } else {
        logger.info(String.format("[repair #%s] requesting merkle trees for %s (to %s)", desc.sessionId,
                desc.columnFamily, allEndpoints));
        // If not sequential, just send validation request to all replica
        validations = sendValidationRequest(allEndpoints);
    }

    // When all validations complete, submit sync tasks
    ListenableFuture<List<SyncStat>> syncResults = Futures.transform(validations,
            new AsyncFunction<List<TreeResponse>, List<SyncStat>>() {
                public ListenableFuture<List<SyncStat>> apply(List<TreeResponse> trees) throws Exception {
                    InetAddress local = FBUtilities.getLocalAddress();

                    List<SyncTask> syncTasks = new ArrayList<>();
                    // We need to difference all trees one against another
                    for (int i = 0; i < trees.size() - 1; ++i) {
                        TreeResponse r1 = trees.get(i);
                        for (int j = i + 1; j < trees.size(); ++j) {
                            TreeResponse r2 = trees.get(j);
                            SyncTask task;
                            if (r1.endpoint.equals(local) || r2.endpoint.equals(local)) {
                                task = new LocalSyncTask(desc, r1, r2, repairedAt);
                            } else {
                                task = new RemoteSyncTask(desc, r1, r2);
                                // RemoteSyncTask expects SyncComplete message sent back.
                                // Register task to RepairSession to receive response.
                                session.waitForSync(Pair.create(desc, new NodePair(r1.endpoint, r2.endpoint)),
                                        (RemoteSyncTask) task);
                            }
                            syncTasks.add(task);
                            taskExecutor.submit(task);
                        }
                    }
                    return Futures.allAsList(syncTasks);
                }
            }, taskExecutor);

    // When all sync complete, set the final result
    Futures.addCallback(syncResults, new FutureCallback<List<SyncStat>>() {
        public void onSuccess(List<SyncStat> stats) {
            logger.info(String.format("[repair #%s] %s is fully synced", session.getId(), desc.columnFamily));
            SystemDistributedKeyspace.successfulRepairJob(session.getId(), desc.keyspace, desc.columnFamily);
            set(new RepairResult(desc, stats));
        }

        /**
         * Snapshot, validation and sync failures are all handled here
         */
        public void onFailure(Throwable t) {
            logger.warn(String.format("[repair #%s] %s sync failed", session.getId(), desc.columnFamily));
            SystemDistributedKeyspace.failedRepairJob(session.getId(), desc.keyspace, desc.columnFamily, t);
            setException(t);
        }
    }, taskExecutor);

    // Wait for validation to complete
    Futures.getUnchecked(validations);
}

From source file:info.archinnov.achilles.internal.async.AsyncUtils.java

public <T, V> ListenableFuture<T> transformFuture(ListenableFuture<V> from, Function<V, T> function,
        ExecutorService executorService) {
    return Futures.transform(from, function, executorService);
}

From source file:com.facebook.buck.distributed.build_slave.DelegateAndGraphsInitializer.java

public ListenableFuture<ActionGraphAndBuilder> getActionGraphAndBuilder() {
    return Futures.transform(delegateAndGraphs, x -> x.getActionGraphAndBuilder(),
            MoreExecutors.directExecutor());
}