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.rule.engine.action.TbCreateAlarmNode.java

private ListenableFuture<AlarmResult> updateAlarm(TbContext ctx, TbMsg msg, Alarm alarm) {
    ListenableFuture<Alarm> asyncUpdated = Futures.transform(buildAlarmDetails(ctx, msg, alarm.getDetails()),
            (Function<JsonNode, Alarm>) details -> {
                alarm.setSeverity(config.getSeverity());
                alarm.setPropagate(config.isPropagate());
                alarm.setDetails(details);
                alarm.setEndTs(System.currentTimeMillis());
                return ctx.getAlarmService().createOrUpdateAlarm(alarm);
            }, ctx.getDbCallbackExecutor());

    return Futures.transform(asyncUpdated, a -> new AlarmResult(false, true, false, a));
}

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

/** Run all the local steps required after the build. */
public StampedeExecutionResult runPostDistBuildLocalSteps(ListeningExecutorService networkExecutorService,
        List<BuildSlaveStatus> buildSlaveStatusList, BuildJob finalJob,
        ConsoleEventsDispatcher consoleEventsDispatcher) throws InterruptedException {
    distBuildClientStats.startTimer(POST_DISTRIBUTED_BUILD_LOCAL_STEPS);

    consoleEventsDispatcher.postDistBuildStatusEvent(finalJob, buildSlaveStatusList,
            "FETCHING DIST BUILD STATS");
    distBuildClientStats.startTimer(PUBLISH_BUILD_SLAVE_FINISHED_STATS);
    ListenableFuture<?> slaveFinishedStatsFuture = publishBuildSlaveFinishedStatsEvent(finalJob,
            networkExecutorService, consoleEventsDispatcher);
    slaveFinishedStatsFuture = Futures.transform(slaveFinishedStatsFuture, f -> {
        distBuildClientStats.stopTimer(PUBLISH_BUILD_SLAVE_FINISHED_STATS);
        return f;
    }, MoreExecutors.directExecutor());//  ww w .j a v a 2 s  .co m

    consoleEventsDispatcher.postDistBuildStatusEvent(finalJob, buildSlaveStatusList, "FETCHING LOG DIRS");

    if (logMaterializationEnabled) {
        materializeSlaveLogDirs(finalJob);
    }

    try {
        slaveFinishedStatsFuture.get();
    } catch (ExecutionException e) {
        LOG.error(e, "Exception while trying to fetch and publish BuildSlaveFinishedStats.");
    }

    if (finalJob.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY)) {
        LOG.info("DistBuild was successful!");
        consoleEventsDispatcher.postDistBuildStatusEvent(finalJob, buildSlaveStatusList, "FINISHED");
    } else {
        LOG.info("DistBuild was not successful!");
        consoleEventsDispatcher.postDistBuildStatusEvent(finalJob, buildSlaveStatusList, "FAILED");
    }

    return StampedeExecutionResult
            .of(finalJob.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) ? DistributedExitCode.SUCCESSFUL
                    : DistributedExitCode.DISTRIBUTED_BUILD_STEP_REMOTE_FAILURE);
}

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

@Override
public ListenableFuture<List<TsKvEntry>> findAllAsync(String entityType, UUID entityId,
        List<TsKvQuery> queries) {
    List<ListenableFuture<List<TsKvEntry>>> futures = queries.stream()
            .map(query -> findAllAsync(entityType, entityId, query)).collect(Collectors.toList());
    return Futures.transform(Futures.allAsList(futures),
            new Function<List<List<TsKvEntry>>, List<TsKvEntry>>() {
                @Nullable//ww w  . j a  v a2s .  com
                @Override
                public List<TsKvEntry> apply(@Nullable List<List<TsKvEntry>> results) {
                    List<TsKvEntry> result = new ArrayList<TsKvEntry>();
                    results.forEach(r -> result.addAll(r));
                    return result;
                }
            }, readResultsProcessingExecutor);
}

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

@Override
public ListenableFuture<List<AttributeKvEntry>> findAll(EntityId entityId, String attributeType) {
    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));
    log.trace("Generated query [{}] for entityId {} and attributeType {}", select, entityId, attributeType);
    return Futures.transform(executeAsyncRead(select),
            (Function<? super ResultSet, ? extends List<AttributeKvEntry>>) input -> convertResultToAttributesKvEntryList(
                    input),//w  w w . j  av a  2s  .  c o m
            readResultsProcessingExecutor);
}

From source file:com.facebook.buck.core.rulekey.calculator.ParallelRuleKeyCalculator.java

/**
 * @return a {@link ListenableFuture} wrapping the result of calculating the {@link RuleKey} of
 *     the given {@link BuildRule}./*from   w w w.  j  av  a2 s. c om*/
 */
public synchronized ListenableFuture<T> calculate(BuckEventBus buckEventBus, BuildRule rule) {
    ListenableFuture<T> fromOurCache = ruleKeys.get(rule.getBuildTarget());
    if (fromOurCache != null) {
        return fromOurCache;
    }

    T fromInternalCache = ruleKeyFactory.getFromCache(rule);
    if (fromInternalCache != null) {
        ListenableFuture<T> future = Futures.immediateFuture(fromInternalCache);
        // Record the rule key future.
        ruleKeys.put(rule.getBuildTarget(), future);
        // Because a rule key will be invalidated from the internal cache any time one of its
        // dependents is invalidated, we know that all of our transitive deps are also in cache.
        return future;
    }

    // Grab all the dependency rule key futures.  Since our rule key calculation depends on this
    // one, we need to wait for them to complete.
    ListenableFuture<List<T>> depKeys = Futures.transformAsync(Futures.immediateFuture(ruleDepsCache.get(rule)),
            (@Nonnull SortedSet<BuildRule> deps) -> {
                List<ListenableFuture<T>> depKeys1 = new ArrayList<>(
                        SortedSets.sizeEstimate(rule.getBuildDeps()));
                for (BuildRule dep : deps) {
                    depKeys1.add(calculate(buckEventBus, dep));
                }
                return Futures.allAsList(depKeys1);
            }, service);

    // Setup a future to calculate this rule key once the dependencies have been calculated.
    ListenableFuture<T> calculated = Futures.transform(depKeys, (List<T> input) -> {
        try (Scope scope = ruleKeyCalculationScope.apply(buckEventBus, rule)) {
            return ruleKeyFactory.build(rule);
        } catch (Exception e) {
            throw new BuckUncheckedExecutionException(e, String.format("When computing rulekey for %s.", rule));
        }
    }, service);

    // Record the rule key future.
    ruleKeys.put(rule.getBuildTarget(), calculated);
    return calculated;
}

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

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

From source file:com.facebook.buck.parser.RawTargetNodePipeline.java

@Override
protected ListenableFuture<ImmutableList<Map<String, Object>>> getItemsToConvert(Cell cell, Path buildFile)
        throws BuildTargetException {
    return Futures.transform(buildFileRawNodeParsePipeline.getAllNodesJob(cell, buildFile),
            map -> ImmutableList.copyOf(map.getTargets().values()), MoreExecutors.directExecutor());
}

From source file:org.opendaylight.faas.fabric.general.EndPointRegister.java

@Override
public Future<RpcResult<Void>> unregisterEndpoint(UnregisterEndpointInput input) {

    final RpcResult<Void> result = RpcResultBuilder.<Void>success().build();

    if (input == null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("Endpoint can not be empty!"));
    }//from   w ww .  ja  v  a  2s .  com
    final List<Uuid> toBeDeletedList = input.getIds();

    if (toBeDeletedList == null || toBeDeletedList.isEmpty()) {
        return Futures.immediateFuture(result);
    }

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    for (Uuid ep : toBeDeletedList) {
        InstanceIdentifier<Endpoint> eppath = Constants.DOM_ENDPOINTS_PATH.child(Endpoint.class,
                new EndpointKey(ep));
        trans.delete(LogicalDatastoreType.OPERATIONAL, eppath);
    }
    CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit();

    return Futures.transform(future, new AsyncFunction<Void, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void input) throws Exception {
            return Futures.immediateFuture(result);
        }
    }, executor);
}

From source file:io.v.discoverysample.MainActivity.java

private void flipAdvertise() {
    advertiseButton.setEnabled(false);//from   w w  w . j  av a 2s .  co  m
    if (advCtx == null) { // not advertising
        advCtx = rootCtx.withCancel();
        Futures.addCallback(discovery.advertise(advCtx, SERVICE_TO_ADVERTISE, NO_PATTERNS),
                new FutureCallback<ListenableFuture<Void>>() {
                    @Override
                    public void onSuccess(ListenableFuture<Void> result) {
                        // Advertising started.
                        advertiseButton.setText("Stop advertising");
                        advertiseButton.setEnabled(true);
                        Futures.transform(result, new Function<Void, Void>() {
                            @Override
                            public Void apply(Void input) {
                                // Advertising done.
                                advertiseButton.setText("Advertise");
                                advertiseButton.setEnabled(true);
                                return null;
                            }
                        }, UiThreadExecutor.INSTANCE);
                    }

                    @Override
                    public void onFailure(final Throwable t) {
                        if (!(t instanceof CanceledException)) {
                            // advertising wasn't stopped via advCtx.cancel()
                            String msg = "Couldn't start advertising: " + t.getMessage();
                            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
                        }
                        advertiseButton.setText("Advertise");
                        advertiseButton.setEnabled(true);
                    }
                }, UiThreadExecutor.INSTANCE);
    } else { // advertising
        advCtx.cancel();
        advCtx = null;
    }
}

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

@Override
public ListenableFuture<List<AttributeKvEntry>> find(TenantId tenantId, EntityId entityId, String attributeType,
        Collection<String> attributeKeys) {
    List<ListenableFuture<Optional<AttributeKvEntry>>> entries = new ArrayList<>();
    attributeKeys.forEach(attributeKey -> entries.add(find(tenantId, 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);
}