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, Executor executor) 

Source Link

Document

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

Usage

From source file:com.facebook.presto.transaction.InMemoryTransactionManager.java

@Override
public ListenableFuture<?> asyncAbort(TransactionId transactionId) {
    return nonCancellationPropagating(Futures.transformAsync(removeTransactionMetadataAsFuture(transactionId),
            TransactionMetadata::asyncAbort, directExecutor()));
}

From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentService.java

public ListenableFuture<Boolean> delete(String database, String table, Identifier id) {
    ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(database, table);
    return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, Boolean>() {
        @Override//from   ww  w  .jav  a  2  s .  c o m
        public ListenableFuture<Boolean> apply(AbstractDocumentRepository input) throws Exception {
            return input.delete(new Identifier(id));
        }
    }, MoreExecutors.directExecutor());
}

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

private ListenableFuture<Optional<TsKvEntry>> findAndAggregateAsync(TenantId tenantId, EntityId entityId,
        ReadTsKvQuery query, long minPartition, long maxPartition) {
    final Aggregation aggregation = query.getAggregation();
    final String key = query.getKey();
    final long startTs = query.getStartTs();
    final long endTs = query.getEndTs();
    final long ts = startTs + (endTs - startTs) / 2;
    ListenableFuture<List<Long>> partitionsListFuture = getPartitionsFuture(tenantId, query, entityId,
            minPartition, maxPartition);
    ListenableFuture<List<ResultSet>> aggregationChunks = Futures.transformAsync(partitionsListFuture,
            getFetchChunksAsyncFunction(tenantId, entityId, key, aggregation, startTs, endTs),
            readResultsProcessingExecutor);

    return Futures.transform(aggregationChunks, new AggregatePartitionsFunction(aggregation, key, ts),
            readResultsProcessingExecutor);
}

From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentService.java

public ListenableFuture<Boolean> exists(String database, String table, Identifier id) {
    ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(database, table);
    return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, Boolean>() {
        @Override//from w w w  .j  av a 2s . com
        public ListenableFuture<Boolean> apply(AbstractDocumentRepository input) throws Exception {
            return input.exists(new Identifier(id));
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.thingsboard.server.dao.sql.timeseries.JpaTimeseriesDao.java

@Override
public ListenableFuture<Void> removeLatest(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) {
    ListenableFuture<TsKvEntry> latestFuture = findLatest(tenantId, entityId, query.getKey());

    ListenableFuture<Boolean> booleanFuture = Futures.transform(latestFuture, tsKvEntry -> {
        long ts = tsKvEntry.getTs();
        return ts > query.getStartTs() && ts <= query.getEndTs();
    }, service);//from   w w w. ja  va2 s  .com

    ListenableFuture<Void> removedLatestFuture = Futures.transformAsync(booleanFuture, isRemove -> {
        if (isRemove) {
            TsKvLatestEntity latestEntity = new TsKvLatestEntity();
            latestEntity.setEntityType(entityId.getEntityType());
            latestEntity.setEntityId(fromTimeUUID(entityId.getId()));
            latestEntity.setKey(query.getKey());
            return service.submit(() -> {
                tsKvLatestRepository.delete(latestEntity);
                return null;
            });
        }
        return Futures.immediateFuture(null);
    }, service);

    final SimpleListenableFuture<Void> resultFuture = new SimpleListenableFuture<>();
    Futures.addCallback(removedLatestFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(@Nullable Void result) {
            if (query.getRewriteLatestIfDeleted()) {
                ListenableFuture<Void> savedLatestFuture = Futures.transformAsync(booleanFuture, isRemove -> {
                    if (isRemove) {
                        return getNewLatestEntryFuture(tenantId, entityId, query);
                    }
                    return Futures.immediateFuture(null);
                }, service);

                try {
                    resultFuture.set(savedLatestFuture.get());
                } catch (InterruptedException | ExecutionException e) {
                    log.warn("Could not get latest saved value for [{}], {}", entityId, query.getKey(), e);
                }
            } else {
                resultFuture.set(null);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            log.warn("[{}] Failed to process remove of the latest value", entityId, t);
        }
    });
    return resultFuture;
}

From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentService.java

private ListenableFuture<AbstractDocumentRepository> acquireRepositoryFor(String database, String table) {
    Identifier cacheKey = new Identifier(database, table);
    AbstractDocumentRepository repo = repoCache.get(cacheKey);

    if (repo != null) {
        return Futures.immediateFuture(repo);
    }//from w w w  .j  a v a2  s. co  m

    ListenableFuture<Table> futureTable = tables.read(database, table);
    return Futures.transformAsync(futureTable, new AsyncFunction<Table, AbstractDocumentRepository>() {
        @Override
        public ListenableFuture<AbstractDocumentRepository> apply(Table input) throws Exception {
            AbstractDocumentRepository repo = factory.newInstance(input);
            repoCache.put(cacheKey, repo);
            return Futures.immediateFuture(repo);
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.facebook.buck.rules.modern.builders.RemoteExecutionStrategy.java

private ListenableFuture<Optional<BuildResult>> executeNowThatInputsAreReady(ProjectFilesystem filesystem,
        BuildStrategyContext strategyContext, BuildTarget buildTarget, Callable<Throwable> tryStart,
        Digest actionDigest, Iterable<? extends Path> actionOutputs, String ruleName) {
    AtomicReference<Throwable> cancelled = new AtomicReference<>(null);
    ListenableFuture<ExecutionResult> executionResult = executionLimiter.schedule(service, () -> {
        cancelled.set(tryStart.call());//from  w w  w  . j a v a 2s.  c  o  m
        boolean isCancelled = cancelled.get() != null;
        if (isCancelled) {
            RemoteExecutionActionEvent.sendTerminalEvent(eventBus, State.ACTION_CANCELLED, buildTarget,
                    Optional.of(actionDigest));
            return Futures.immediateFuture(null);
        }
        Scope executingScope = RemoteExecutionActionEvent.sendEvent(eventBus, State.EXECUTING, buildTarget,
                Optional.of(actionDigest));
        return Futures.transform(executionClients.getRemoteExecutionService().execute(actionDigest, ruleName),
                result -> {
                    executingScope.close();
                    return result;
                }, MoreExecutors.directExecutor());
    });

    return sendFailedEventOnException(Futures.transformAsync(executionResult, result -> {
        if (cancelled.get() != null) {
            return Futures.immediateFuture(Optional.of(strategyContext.createCancelledResult(cancelled.get())));
        }
        return handleResultLimiter.schedule(service, () -> handleExecutionResult(filesystem, strategyContext,
                buildTarget, result, actionDigest, actionOutputs));
    }, service), buildTarget, actionDigest);
}

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

/** Run the build while updating the console messages. */
public BuildResult runDistBuildAndUpdateConsoleStatus(ListeningExecutorService executorService,
        StampedeId stampedeId, BuildMode buildMode, DistLocalBuildMode distLocalBuildMode,
        InvocationInfo invocationInfo,/*from ww  w .  ja  v  a2 s . c  om*/
        ListenableFuture<ParallelRuleKeyCalculator<RuleKey>> localRuleKeyCalculator)
        throws IOException, InterruptedException, ExecutionException {
    distBuildClientStats.startTimer(PERFORM_DISTRIBUTED_BUILD);

    BuildJob job = distBuildService.startBuild(stampedeId,
            !buildMode.equals(DISTRIBUTED_BUILD_WITH_LOCAL_COORDINATOR));
    LOG.info("Started job. Build status: " + job.getStatus());

    ListenableFuture<List<Pair<BuildRule, RuleKey>>> ruleKeyPairsFutureFuture = Futures.immediateFuture(null);

    if (distLocalBuildMode.equals(DistLocalBuildMode.RULE_KEY_DIVERGENCE_CHECK)) {
        ruleKeyPairsFutureFuture = Futures.transformAsync(localRuleKeyCalculator,
                ruleKeyCalculator -> RuleKeyUtils.calculateDefaultRuleKeys(
                        buildGraphs.getActionGraphAndBuilder().getActionGraphBuilder(), ruleKeyCalculator,
                        buildExecutorArgs.getBuckEventBus(), topLevelTargets),
                Objects.requireNonNull(buildExecutorArgs.getExecutors().get(ExecutorPool.CPU)));
    }

    if (distLocalBuildMode.equals(DistLocalBuildMode.FIRE_AND_FORGET)) {
        LOG.info("Fire-and-forget mode: returning after build status is:started. " + job.getStatus());
        return new BuildResult(job, ImmutableList.of(), ImmutableSet.of());
    }

    nextEventIdBySlaveRunId.clear();
    ScheduledFuture<?> distBuildStatusUpdatingFuture = scheduler.scheduleWithFixedDelay(() -> {
        try {
            fetchBuildInformationFromServerAndPublishPendingEvents(job, executorService);
        } catch (InterruptedException e) {
            LOG.warn(e, "fetchBuildInformationFromServerAndPublishPendingEvents was interrupted");
            Thread.currentThread().interrupt();
            throw new RuntimeException(e); // Ensure we don't schedule any more fetches
        }
    }, 0, statusPollIntervalMillis, TimeUnit.MILLISECONDS);

    if (buildMode.equals(DISTRIBUTED_BUILD_WITH_LOCAL_COORDINATOR)) {
        runLocalCoordinatorAsync(executorService, stampedeId, invocationInfo, localRuleKeyCalculator);
    }

    BuildJob finalJob = null;
    List<BuildSlaveStatus> buildSlaveStatusList = null;
    try {
        distBuildStatusUpdatingFuture.get();
        throw new RuntimeException("Unreachable State.");
    } catch (InterruptedException ex) {
        // Important to cancel distBuildStatusUpdatingFuture, otherwise the async task will
        // keep blocking the ScheduledExecutorService that it runs inside
        distBuildStatusUpdatingFuture.cancel(true);
        Thread.currentThread().interrupt();
        throw ex;
    } catch (ExecutionException e) {
        if (e.getCause() instanceof JobCompletedException) {
            // Everything is awesome.
            JobCompletedException jobCompletedException = (JobCompletedException) e.getCause();
            finalJob = jobCompletedException.getDistBuildJob();
            buildSlaveStatusList = jobCompletedException.getBuildSlaveStatuses().orElse(ImmutableList.of());
        } else {
            throw new HumanReadableException(e, "Failed to fetch build information from server.");
        }
    } finally {
        distBuildClientStats.stopTimer(PERFORM_DISTRIBUTED_BUILD);

        // Remote build is now done, so ensure local build is unlocked for all build rules.
        remoteBuildRuleCompletionNotifier.signalCompletionOfRemoteBuild(
                finalJob != null && finalJob.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY));
    }

    Set<String> mismatchingBuildTargets = checkForRuleKeyMismatches(distLocalBuildMode,
            ruleKeyPairsFutureFuture);

    return new BuildResult(finalJob, buildSlaveStatusList, mismatchingBuildTargets);
}

From source file:org.thingsboard.server.dao.sql.timeseries.JpaTimeseriesDao.java

private ListenableFuture<Void> getNewLatestEntryFuture(TenantId tenantId, EntityId entityId,
        DeleteTsKvQuery query) {/*from  w w  w . ja  v a  2  s  . co m*/
    long startTs = 0;
    long endTs = query.getStartTs() - 1;
    ReadTsKvQuery findNewLatestQuery = new BaseReadTsKvQuery(query.getKey(), startTs, endTs, endTs - startTs, 1,
            Aggregation.NONE, DESC_ORDER);
    ListenableFuture<List<TsKvEntry>> future = findAllAsync(tenantId, entityId, findNewLatestQuery);

    return Futures.transformAsync(future, entryList -> {
        if (entryList.size() == 1) {
            return saveLatest(tenantId, entityId, entryList.get(0));
        } else {
            log.trace("Could not find new latest value for [{}], key - {}", entityId, query.getKey());
        }
        return Futures.immediateFuture(null);
    }, service);
}

From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentService.java

private ListenableFuture<List<View>> getTableViews(String database, String table) {
    Identifier tableId = new Identifier(database, table);
    List<View> cachedViews = viewsByTable.get(tableId);

    if (cachedViews != null) {
        return Futures.immediateFuture(cachedViews);
    }//from   ww w  .  ja va 2 s .c  om

    ListenableFuture<List<View>> allViews = views.readAll(database, table);
    return Futures.transformAsync(allViews, new AsyncFunction<List<View>, List<View>>() {
        @Override
        public ListenableFuture<List<View>> apply(List<View> input) {
            List<View> cachedViews = new ArrayList<>();
            cachedViews.addAll(input);
            viewsByTable.put(tableId, cachedViews);
            return Futures.immediateFuture(input);
        }
    }, MoreExecutors.directExecutor());
}