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) 

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.opendaylight.yangtools.yang.parser.repo.SharedSchemaContextFactory.java

private CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(
        final Collection<SourceIdentifier> requiredSources,
        final Cache<Collection<SourceIdentifier>, SchemaContext> cache,
        final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources) {
    // Make sources unique
    final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);

    final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
    if (existing != null) {
        LOG.debug("Returning cached context {}", existing);
        return Futures.immediateCheckedFuture(existing);
    }//from w w  w.  ja va 2  s . c om

    // Request all sources be loaded
    ListenableFuture<List<ASTSchemaSource>> sf = Futures
            .allAsList(Collections2.transform(uniqueSourceIdentifiers, this::requestSource));

    // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
    // Also remove duplicates if present
    // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
    sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers));

    // Assemble sources into a schema context
    final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources);

    // Populate cache when successful
    Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
        @Override
        public void onSuccess(final SchemaContext result) {
            cache.put(uniqueSourceIdentifiers, result);
        }

        @Override
        public void onFailure(@Nonnull final Throwable t) {
            LOG.debug("Failed to assemble sources", t);
        }
    });

    return Futures.makeChecked(cf, MAPPER);
}

From source file:com.google.gapid.models.ApiState.java

public ListenableFuture<Path.StateTreeNode> getResolvedSelectedPath() {
    Path.Any path = selection.get();
    if (path == null || !isLoaded()) {
        return Futures.immediateFuture(Path.StateTreeNode.getDefaultInstance());
    } else if (path.getPathCase() == Path.Any.PathCase.STATE_TREE_NODE) {
        return Futures.immediateFuture(path.getStateTreeNode());
    }/*from  ww w  .java 2s  .  com*/

    return Futures.transform(client.get(Paths.stateTree(((RootNode) getData()).tree, path)),
            value -> value.getPath().getStateTreeNode());
}

From source file:org.springframework.data.cassandra.core.cql.session.DefaultBridgedReactiveSession.java

@Override
public Mono<ReactiveResultSet> execute(Statement statement) {

    Assert.notNull(statement, "Statement must not be null");

    return Mono.create(sink -> {

        try {/*from   ww w  .j  a v  a  2s .  c  o  m*/
            if (logger.isDebugEnabled()) {
                logger.debug("Executing Statement [{}]", statement);
            }

            ListenableFuture<ResultSet> future = this.session.executeAsync(statement);

            ListenableFuture<ReactiveResultSet> resultSetFuture = Futures.transform(future,
                    DefaultReactiveResultSet::new);

            adaptFuture(resultSetFuture, sink);
        } catch (Exception cause) {
            sink.error(cause);
        }
    });
}

From source file:org.opendaylight.netconf.sal.connect.netconf.sal.tx.WriteCandidateTx.java

@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
    final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(),
            new Function<RpcResult<TransactionStatus>, Void>() {
                @Override//from  w  ww.j  a va2 s  .c o  m
                public Void apply(final RpcResult<TransactionStatus> input) {
                    Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
                            "Submit failed with errors: %s", input.getErrors());
                    return null;
                }
            });

    return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
        @Override
        public TransactionCommitFailedException apply(final Exception input) {
            return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed",
                    input);
        }
    });
}

From source file:com.facebook.buck.rules.UnskippedRulesTracker.java

private ListenableFuture<Void> acquireReferences(ImmutableSet<BuildRule> rules) {
    ImmutableList.Builder<ListenableFuture<Void>> futures = ImmutableList.builder();
    for (BuildRule rule : rules) {
        futures.add(acquireReference(rule));
    }// w  w  w  .  j a v a 2  s  .c o  m
    return Futures.transform(Futures.allAsList(futures.build()), NULL_FUNCTION);
}

From source file:org.blackbananacoin.ext.curconvert.testlog.CurFutureMixChain.java

public void run() throws Exception {

    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }/*from ww w.  ja  v  a2s .c o m*/
    });
    final GenericUrl urlBlockchain = new GenericUrl(EXURL_BLOCKCHAIN);
    final GenericUrl urlYahooTwd = new GenericUrl(EXURL_YAHOO_USDTWD);
    final HttpRequest requestBlockChain = requestFactory.buildGetRequest(urlBlockchain);

    final HttpRequest requestYahoo = requestFactory.buildGetRequest(urlYahooTwd);

    final ListenableFuture<Double> futureYahoo = pool.submit(new Callable<Double>() {
        public Double call() throws Exception {
            GenericJson jsonYahoo = requestYahoo.execute().parseAs(GenericJson.class);
            System.out.println(jsonYahoo);
            Map query = (Map) jsonYahoo.get("query");
            Map results = (Map) query.get("results");
            Map row = (Map) results.get("row");
            double twd = Double.parseDouble((String) row.get("col1"));
            System.out.println("======== GET TWD/USD Rate =========");
            System.out.println(twd);
            return twd;
        }
    });

    final AsyncFunction<Double, GenericJson> relevanceAsyncFun = new AsyncFunction<Double, GenericJson>() {
        public ListenableFuture<GenericJson> apply(final Double twdPerUsd) throws Exception {

            final ListenableFuture<GenericJson> futureReqBlockChain = pool.submit(new Callable<GenericJson>() {
                public GenericJson call() throws Exception {
                    GenericJson json = requestBlockChain.execute().parseAs(GenericJson.class);
                    handleTwdAppend(twdPerUsd, json);
                    return json;
                }

                private void handleTwdAppend(final Double twdPerUsd, GenericJson json) {
                    System.out.println(json);
                    Map usdJson = (Map) json.get("USD");
                    Map ntdJson = new HashMap<String, Object>();
                    BigDecimal usdBuy = (BigDecimal) usdJson.get("buy");
                    BigDecimal usdLast = (BigDecimal) usdJson.get("last");
                    BigDecimal usd15m = (BigDecimal) usdJson.get("15m");
                    BigDecimal usdSell = (BigDecimal) usdJson.get("sell");
                    BigDecimal twdBuy = usdBuy.multiply(BigDecimal.valueOf(twdPerUsd));
                    BigDecimal twdSell = usdSell.multiply(BigDecimal.valueOf(twdPerUsd));
                    BigDecimal twd15m = usd15m.multiply(BigDecimal.valueOf(twdPerUsd));
                    BigDecimal twdLast = usdLast.multiply(BigDecimal.valueOf(twdPerUsd));
                    ntdJson.put("buy", twdBuy);
                    ntdJson.put("sell", twdSell);
                    ntdJson.put("last", twdLast);
                    ntdJson.put("15m", twd15m);
                    ntdJson.put("symbol", "NT$");
                    json.put(YAHOO_CUR_TAG, ntdJson);
                    // System.out.println(json);
                }
            });

            return futureReqBlockChain;
        }
    };

    ListenableFuture<GenericJson> futureMix = Futures.transform(futureYahoo, relevanceAsyncFun);

    Futures.addCallback(futureMix, new FutureCallback<GenericJson>() {

        public void onSuccess(GenericJson result) {
            System.out.println("======== RESULT =========");
            System.out.println(result);
            pool.shutdown();
        }

        public void onFailure(Throwable t) {
            t.printStackTrace();
            pool.shutdown();
        }
    });

}

From source file:com.sk89q.worldguard.commands.region.MemberCommands.java

@Command(aliases = { "addowner", "addowner",
        "ao" }, usage = "<id> <owners...>", flags = "nw:", desc = "Add an owner to a region", min = 2)
public void addOwner(CommandContext args, Actor sender) throws CommandException, AuthorizationException {
    warnAboutSaveFailures(sender);/*from w  w  w.j av  a  2  s .  co m*/

    World world = checkWorld(args, sender, 'w'); // Get the world

    LocalPlayer player = null;
    if (sender instanceof LocalPlayer) {
        player = (LocalPlayer) sender;
    }

    String id = args.getString(0);

    RegionManager manager = checkRegionManager(world);
    ProtectedRegion region = checkExistingRegion(manager, id, true);

    id = region.getId();

    DefaultDomain owners = region.getOwners();

    if (player != null) {
        if (owners != null && owners.size() == 0) {
            if (!sender.hasPermission("worldguard.region.unlimited")) {
                int maxRegionCount = WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(world)
                        .getMaxRegionCount(player);
                if (maxRegionCount >= 0 && manager.getRegionCountOfPlayer(player) >= maxRegionCount) {
                    throw new CommandException("You already own the maximum allowed amount of regions.");
                }
            }
            sender.checkPermission("worldguard.region.addowner.unclaimed." + id.toLowerCase());
        } else {
            // Check permissions
            if (!getPermissionModel(player).mayAddOwners(region)) {
                throw new CommandPermissionsException();
            }
        }
    }

    // Resolve owners asynchronously
    DomainInputResolver resolver = new DomainInputResolver(WorldGuard.getInstance().getProfileService(),
            args.getParsedPaddedSlice(1, 0));
    resolver.setLocatorPolicy(args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_ONLY);

    // Then add it to the owners
    ListenableFuture<DefaultDomain> future = Futures.transform(
            WorldGuard.getInstance().getExecutorService().submit(resolver),
            resolver.createAddAllFunction(region.getOwners()));

    AsyncCommandHelper.wrap(future, worldGuard.getSupervisor(), sender, worldGuard.getExceptionConverter())
            .formatUsing(region.getId(), world.getName())
            .registerWithSupervisor("Adding owners to the region '%s' on '%s'")
            .sendMessageAfterDelay("(Please wait... querying player names...)")
            .thenRespondWith("Region '%s' updated with new owners.", "Failed to add new owners");
}

From source file:com.facebook.watchman.WatchmanClientImpl.java

@Override
public ListenableFuture<SubscriptionDescriptor> subscribe(Path path, Map<String, Object> query,
        final Callback listener) {
    final String subscriptionId = "sub-" + subscriptionIndex.getAndAdd(1);
    final String root = path.toAbsolutePath().toString();

    final SubscriptionDescriptor result = new SubscriptionDescriptorBuilder().name(subscriptionId).root(root)
            .build();//from  ww  w . jav  a 2  s  . c  om
    subscriptions.put(result, listener);

    List<Object> request = ImmutableList.of("subscribe", root, subscriptionId,
            query == null ? Collections.emptyMap() : query);

    return Futures.transform(connection.run(request),
            new Function<Map<String, Object>, SubscriptionDescriptor>() {
                @Nullable
                @Override
                public SubscriptionDescriptor apply(@Nullable Map<String, Object> input) {
                    // TODO remove subscription descriptor from `subscriptions` if we got an error from wman
                    return result;
                }
            });
}

From source file:com.vsct.strowgr.monitoring.gui.cassandra.CassandraClient.java

private static AsyncFunction<ResultSet, Multimap<Key, Value>> iterate(Multimap<Key, Value> result) {
    return new AsyncFunction<ResultSet, Multimap<Key, Value>>() {
        @Override/*from   w w w.  j  av a2s  . c  o  m*/
        public ListenableFuture<Multimap<Key, Value>> apply(ResultSet rs) throws Exception {
            int remaining = rs.getAvailableWithoutFetching();

            for (Row row : rs) {
                Date d = row.get(0, Date.class);
                String name = row.get(1, String.class);
                String correlationId = row.get(2, UUID.class).toString();

                Key k = new Key();
                k.correlationId = correlationId;
                Value v = new Value();
                v.name = name;
                v.timestamp = d;

                if (showPayload) {
                    v.payload = row.get(3, String.class);
                }

                result.put(k, v);

                messageProcessed.incrementAndGet();
                if (--remaining == 0)
                    break;
            }

            boolean wasLastPage = rs.getExecutionInfo().getPagingState() == null;
            if (wasLastPage) {
                return Futures.immediateFuture(result);
            } else {
                ListenableFuture<ResultSet> future = rs.fetchMoreResults();
                return Futures.transform(future, iterate(result));
            }

        }
    };
}

From source file:org.opendaylight.openflowplugin.applications.frsync.impl.SyncReactorImpl.java

@Override
public ListenableFuture<Boolean> syncup(final InstanceIdentifier<FlowCapableNode> nodeIdent,
        final SyncupEntry syncupEntry) {
    final NodeId nodeId = PathUtil.digNodeId(nodeIdent);
    FlowCapableNode configTree = syncupEntry.getAfter();
    FlowCapableNode operationalTree = syncupEntry.getBefore();

    LOG.trace("syncup reactor {} cfg:{} oper:{}", nodeId.getValue(),
            configTree == null ? "is null" : "non null", operationalTree == null ? "is null" : "non null");
    final SyncCrudCounters counters = new SyncCrudCounters();

    /**//from   w  ww .  jav  a  2s  .c om
     * instructions:
     *  - extract diff changes and prepare change steps in safe order
     *    - optimization: decide if updates needed
     *  - execute chosen implementation (e.g. conventional API, bulk API, flat bulk API)
     *  - recommended order follows:
     * reconciliation strategy - phase 1: - add/update missing objects in following order:
     *  - table features - groups (reordered) - meters - flows
     *
     * reconciliation strategy - phase 2: - remove redundant objects in following order:
     *  - flows - meters - groups (reordered)
     **/

    final List<ItemSyncBox<Group>> groupsToAddOrUpdate = extractGroupsToAddOrUpdate(nodeId, configTree,
            operationalTree);
    final ItemSyncBox<Meter> metersToAddOrUpdate = extractMetersToAddOrUpdate(nodeId, configTree,
            operationalTree);
    final Map<TableKey, ItemSyncBox<Flow>> flowsToAddOrUpdate = extractFlowsToAddOrUpdate(nodeId, configTree,
            operationalTree);

    final Map<TableKey, ItemSyncBox<Flow>> flowsToRemove = extractFlowsToRemove(nodeId, configTree,
            operationalTree);
    final ItemSyncBox<Meter> metersToRemove = extractMetersToRemove(nodeId, configTree, operationalTree);
    final List<ItemSyncBox<Group>> groupsToRemove = extractGroupsToRemove(nodeId, configTree, operationalTree);

    final SynchronizationDiffInput input = new SynchronizationDiffInput(nodeIdent, groupsToAddOrUpdate,
            metersToAddOrUpdate, flowsToAddOrUpdate, flowsToRemove, metersToRemove, groupsToRemove);

    counters.setStartNano(System.nanoTime());
    final ListenableFuture<RpcResult<Void>> bootstrapResultFuture = RpcResultBuilder.<Void>success()
            .buildFuture();
    final ListenableFuture<RpcResult<Void>> resultVehicle = syncPlanPushStrategy
            .executeSyncStrategy(bootstrapResultFuture, input, counters);

    // log final result
    Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "final result"));

    return Futures.transform(resultVehicle, new Function<RpcResult<Void>, Boolean>() {
        @Override
        public Boolean apply(RpcResult<Void> input) {
            if (input == null) {
                return false;
            }
            if (LOG.isDebugEnabled()) {
                final CrudCounts flowCrudCounts = counters.getFlowCrudCounts();
                final CrudCounts meterCrudCounts = counters.getMeterCrudCounts();
                final CrudCounts groupCrudCounts = counters.getGroupCrudCounts();
                LOG.debug(
                        "syncup outcome[{}] (added/updated/removed): flow={}/{}/{}, group={}/{}/{}, meter={}/{}/{}, took={} ms",
                        nodeId.getValue(), flowCrudCounts.getAdded(), flowCrudCounts.getUpdated(),
                        flowCrudCounts.getRemoved(), groupCrudCounts.getAdded(), groupCrudCounts.getUpdated(),
                        groupCrudCounts.getRemoved(), meterCrudCounts.getAdded(), meterCrudCounts.getUpdated(),
                        meterCrudCounts.getRemoved(),
                        TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - counters.getStartNano()));
            }
            LOG.trace("syncup errors: {}", input.getErrors());
            return input.isSuccessful();
        }
    });
}