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.timeseries.BaseTimeseriesDao.java

private ListenableFuture<List<TsKvEntry>> findAllAsyncWithLimit(String entityType, UUID entityId,
        TsKvQuery query) {//from w w  w. j  av a2 s .c  om
    long minPartition = toPartitionTs(query.getStartTs());
    long maxPartition = toPartitionTs(query.getEndTs());

    ResultSetFuture partitionsFuture = fetchPartitions(entityType, entityId, query.getKey(), minPartition,
            maxPartition);

    final SimpleListenableFuture<List<TsKvEntry>> resultFuture = new SimpleListenableFuture<>();
    final ListenableFuture<List<Long>> partitionsListFuture = Futures.transform(partitionsFuture,
            getPartitionsArrayFunction(), readResultsProcessingExecutor);

    Futures.addCallback(partitionsListFuture, new FutureCallback<List<Long>>() {
        @Override
        public void onSuccess(@Nullable List<Long> partitions) {
            TsKvQueryCursor cursor = new TsKvQueryCursor(entityType, entityId, query, partitions);
            findAllAsyncSequentiallyWithLimit(cursor, resultFuture);
        }

        @Override
        public void onFailure(Throwable t) {
            log.error("[{}][{}] Failed to fetch partitions for interval {}-{}", entityType, entityId,
                    minPartition, maxPartition, t);
        }
    }, readResultsProcessingExecutor);

    return resultFuture;
}

From source file:org.jclouds.atmos.internal.StubAtmosAsyncClient.java

@Override
public ListenableFuture<Void> deletePath(String path) {
    if (path.indexOf('/') == path.length() - 1) {
        // chop off the trailing slash
        return Futures.transform(blobStore.deleteContainerIfEmpty(path.substring(0, path.length() - 1)),
                new Function<Boolean, Void>() {

                    public Void apply(Boolean from) {
                        return null;
                    }/*from w ww . j a v a 2 s. co  m*/

                }, userExecutor);
    } else {
        String container = path.substring(0, path.indexOf('/'));
        path = path.substring(path.indexOf('/') + 1);
        return blobStore.removeBlob(container, path);
    }
}

From source file:io.prestosql.server.TaskResource.java

@GET
@Path("{taskId}")
@Produces(MediaType.APPLICATION_JSON)/*from w  w  w  . j  ava  2 s .c  o m*/
public void getTaskInfo(@PathParam("taskId") final TaskId taskId,
        @HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState,
        @HeaderParam(PRESTO_MAX_WAIT) Duration maxWait, @Context UriInfo uriInfo,
        @Suspended AsyncResponse asyncResponse) {
    requireNonNull(taskId, "taskId is null");

    if (currentState == null || maxWait == null) {
        TaskInfo taskInfo = taskManager.getTaskInfo(taskId);
        if (shouldSummarize(uriInfo)) {
            taskInfo = taskInfo.summarize();
        }
        asyncResponse.resume(taskInfo);
        return;
    }

    Duration waitTime = randomizeWaitTime(maxWait);
    ListenableFuture<TaskInfo> futureTaskInfo = addTimeout(taskManager.getTaskInfo(taskId, currentState),
            () -> taskManager.getTaskInfo(taskId), waitTime, timeoutExecutor);

    if (shouldSummarize(uriInfo)) {
        futureTaskInfo = Futures.transform(futureTaskInfo, TaskInfo::summarize, directExecutor());
    }

    // For hard timeout, add an additional time to max wait for thread scheduling contention and GC
    Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS);
    bindAsyncResponse(asyncResponse, futureTaskInfo, responseExecutor).withTimeout(timeout);
}

From source file:com.google.caliper.runner.server.ServerSocketService.java

/**
 * Returns a {@link ListenableFuture} for an {@link InputStream} corresponding to the given id.
 *
 * <p>N.B. calling this method 'consumes' the connection and as such calling it or {@link
 * #getConnection} twice with the same id will not work; the second future returned will never
 * complete. Similarly calling it with an id that does not correspond to a worker trying to
 * connect will also fail.//from  ww  w.j a v  a2  s  .  com
 */
public ListenableFuture<InputStream> getInputStream(UUID id) {
    return Futures.transform(getSocket(id), INPUT_STREAM_FUNCTION, directExecutor());
}

From source file:org.hawkular.metrics.core.impl.cassandra.MetricsServiceCassandra.java

void loadDataRetentions() {
    DataRetentionsMapper mapper = new DataRetentionsMapper();
    List<String> tenantIds = loadTenantIds();
    CountDownLatch latch = new CountDownLatch(tenantIds.size() * 2);
    for (String tenantId : tenantIds) {
        ResultSetFuture gaugeFuture = dataAccess.findDataRetentions(tenantId, MetricType.GAUGE);
        ResultSetFuture availabilityFuture = dataAccess.findDataRetentions(tenantId, MetricType.AVAILABILITY);
        ListenableFuture<Set<Retention>> gaugeRetentions = Futures.transform(gaugeFuture, mapper, metricsTasks);
        ListenableFuture<Set<Retention>> availabilityRetentions = Futures.transform(availabilityFuture, mapper,
                metricsTasks);//  w ww .j ava  2 s.  c o  m
        Futures.addCallback(gaugeRetentions,
                new DataRetentionsLoadedCallback(tenantId, MetricType.GAUGE, latch));
        Futures.addCallback(availabilityRetentions,
                new DataRetentionsLoadedCallback(tenantId, MetricType.AVAILABILITY, latch));
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.facebook.buck.distributed.build_client.PostBuildPhase.java

@VisibleForTesting
ListenableFuture<BuildSlaveStats> publishBuildSlaveFinishedStatsEvent(BuildJob job,
        ListeningExecutorService executor, ConsoleEventsDispatcher consoleEventsDispatcher) {
    if (!job.isSetBuildSlaves()) {
        return Futures.immediateFuture(null);
    }//from  w  w w. ja va 2s . co m

    List<ListenableFuture<Pair<BuildSlaveRunId, Optional<BuildSlaveFinishedStats>>>> slaveFinishedStatsFutures = new ArrayList<>(
            job.getBuildSlavesSize());
    for (BuildSlaveInfo info : job.getBuildSlaves()) {
        BuildSlaveRunId runId = info.getBuildSlaveRunId();
        slaveFinishedStatsFutures.add(executor.submit(() -> {
            Optional<BuildSlaveFinishedStats> stats = fetchStatsForIndividualSlave(job, runId);
            return new Pair<BuildSlaveRunId, Optional<BuildSlaveFinishedStats>>(runId, stats);
        }));
    }

    Builder builder = BuildSlaveStats.builder().setStampedeId(job.getStampedeId());
    return Futures.transform(Futures.allAsList(slaveFinishedStatsFutures),
            statsList -> createAndPublishBuildSlaveStats(builder, statsList, consoleEventsDispatcher),
            MoreExecutors.directExecutor());
}

From source file:com.facebook.buck.distributed.ServerContentsProvider.java

@Override
@SuppressWarnings("CheckReturnValue")
public ListenableFuture<Boolean> materializeFileContentsAsync(BuildJobStateFileHashEntry entry,
        Path targetAbsPath) {//  www  .j a va  2  s.  c  o  m

    ListenableFuture<byte[]> fileFuture = scheduleFileToBeFetched(entry);
    // If the buffer is full, make a multi-fetch request using the thread pool.
    // Don't block the calling thread.
    networkThreadPool.submit(this::makeMultiFetchRequestIfBufferIsFull);

    return Futures.transform(fileFuture,
            (byte[] fileContents) -> writeFileContentsToPath(fileContents, targetAbsPath),
            MoreExecutors.directExecutor());
}

From source file:org.jclouds.atmos.internal.StubAtmosAsyncClient.java

@Override
public ListenableFuture<UserMetadata> getUserMetadata(String path) {
    if (path.indexOf('/') == -1)
        throw new UnsupportedOperationException();
    else {/*from ww  w.  j a  va 2 s. c  o m*/
        String container = path.substring(0, path.indexOf('/'));
        path = path.substring(path.indexOf('/') + 1);
        return Futures.transform(blobStore.blobMetadata(container, path),
                new Function<BlobMetadata, UserMetadata>() {
                    public UserMetadata apply(BlobMetadata from) {
                        return blob2ObjectInfo.apply(from).getUserMetadata();
                    }
                }, userExecutor);
    }
}

From source file:com.facebook.buck.distributed.DistBuildArtifactCacheImpl.java

@Override
public synchronized ListenableFuture<BuildRule> uploadFromLocal(BuildRule rule) throws IOException {
    Preconditions.checkState(localCache.isPresent());
    if (localUploadFutures.containsKey(rule)) {
        return localUploadFutures.get(rule);
    }//from www.j a  v  a 2 s .  com

    ListenableFuture<RuleKey> asyncRuleKey = ruleKeyCalculator.calculate(eventBus, rule);

    NamedTemporaryFile releasedFile;
    ListenableFuture<CacheResult> asyncfetchResult;
    try (CloseableHolder<NamedTemporaryFile> tempFile = new CloseableHolder<>(
            new NamedTemporaryFile(MostFiles.sanitize(rule.getBuildTarget().getShortName()), ""))) {
        asyncfetchResult = Futures.transformAsync(asyncRuleKey,
                ruleKey -> localCache.get().fetchAsync(rule.getBuildTarget(), ruleKey,
                        LazyPath.ofInstance(tempFile.get().get())),
                // We should already have computed the rulekey before calling this method, so using
                // DirectExecutor here is fine.
                MoreExecutors.directExecutor());

        releasedFile = tempFile.release();
    }

    ListenableFuture<Void> uploadFuture = Futures.transformAsync(asyncfetchResult, fetchResult -> {
        if (!fetchResult.getType().isSuccess()) {
            LOG.error("Could not upload missing target [%s] from local cache.",
                    rule.getBuildTarget().getFullyQualifiedName());
            return Futures.immediateFuture(null);
        }

        return remoteCache.store(
                ArtifactInfo.builder().setRuleKeys(ImmutableSet.of(Futures.getUnchecked(asyncRuleKey)))
                        .setMetadata(fetchResult.getMetadata()).build(),
                BorrowablePath.notBorrowablePath(releasedFile.get()));
    }, executorService);

    ListenableFuture<BuildRule> finalFuture = Futures.transform(uploadFuture, result -> {
        try {
            releasedFile.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return rule;
    }, MoreExecutors.directExecutor());

    localUploadFutures.put(rule, finalFuture);
    return finalFuture;
}

From source file:org.thingsboard.server.dao.timeseries.CassandraBaseTimeseriesDao.java

private ListenableFuture<List<TsKvEntry>> findAllAsync(TenantId tenantId, EntityId entityId,
        ReadTsKvQuery query) {//from w  w w. j a  va2s. c  o m
    if (query.getAggregation() == Aggregation.NONE) {
        return findAllAsyncWithLimit(tenantId, entityId, query);
    } else {
        long step = Math.max(query.getInterval(), MIN_AGGREGATION_STEP_MS);
        long stepTs = query.getStartTs();
        List<ListenableFuture<Optional<TsKvEntry>>> futures = new ArrayList<>();
        while (stepTs < query.getEndTs()) {
            long startTs = stepTs;
            long endTs = stepTs + step;
            ReadTsKvQuery subQuery = new BaseReadTsKvQuery(query.getKey(), startTs, endTs, step, 1,
                    query.getAggregation(), query.getOrderBy());
            futures.add(findAndAggregateAsync(tenantId, entityId, subQuery, toPartitionTs(startTs),
                    toPartitionTs(endTs)));
            stepTs = endTs;
        }
        ListenableFuture<List<Optional<TsKvEntry>>> future = Futures.allAsList(futures);
        return Futures.transform(future, new Function<List<Optional<TsKvEntry>>, List<TsKvEntry>>() {
            @Nullable
            @Override
            public List<TsKvEntry> apply(@Nullable List<Optional<TsKvEntry>> input) {
                return input == null ? Collections.emptyList()
                        : input.stream().filter(v -> v.isPresent()).map(v -> v.get())
                                .collect(Collectors.toList());
            }
        }, readResultsProcessingExecutor);
    }
}