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.blackbananacoin.ext.curconvert.ExtRateGenServiceImpl.java

public void startRequest(final MyCallback mcb) throws Exception {

    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }/*  ww w .j a  va2  s.  c o m*/
    });
    final GenericUrl urlBlockchain = new GenericUrl(EXURL_BLOCKCHAIN);
    final GenericUrl urlYahooTwd = new GenericUrl(getExtRateYahooUrl());
    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, Map<GenType, String>> relevanceAsyncFun = new AsyncFunction<Double, Map<GenType, String>>() {
        public ListenableFuture<Map<GenType, String>> apply(final Double twdPerUsd) throws Exception {

            final ListenableFuture<Map<GenType, String>> futureReqBlockChain = pool
                    .submit(new Callable<Map<GenType, String>>() {
                        public Map<GenType, String> call() throws Exception {
                            GenericJson json = requestBlockChain.execute().parseAs(GenericJson.class);
                            double usdPerBtc = processTwdAppend(twdPerUsd, json);
                            Map<GenType, String> rmap = Maps.newHashMap();
                            rmap.put(GenType.BLOCKCHAIN, json.toString());

                            TwdBit twdBit = new TwdBit();
                            twdBit.setTwdPerUsd(twdPerUsd);
                            twdBit.setUsdPerBtc(usdPerBtc);
                            twdBit.update();
                            //System.out.println(gson.toJson(twdBit));
                            rmap.put(GenType.TWDUSD, gson.toJson(twdBit));
                            return rmap;
                        }

                        private double processTwdAppend(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 usdBuy.doubleValue();
                        }
                    });

            return futureReqBlockChain;
        }
    };

    ListenableFuture<Map<GenType, String>> futureMix = Futures.transform(futureYahoo, relevanceAsyncFun);

    FutureCallback<Map<GenType, String>> callback = new FutureCallback<Map<GenType, String>>() {
        public void onSuccess(Map<GenType, String> result) {
            mcb.onResult(result);
            shutdown();
        }

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

    Futures.addCallback(futureMix, callback);

}

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

@Command(aliases = { "removemember", "remmember", "removemem", "remmem",
        "rm" }, usage = "<id> <owners...>", flags = "naw:", desc = "Remove an owner to a region", min = 1)
public void removeMember(CommandContext args, CommandSender sender) throws CommandException {
    warnAboutSaveFailures(sender);/*www  .j a  va  2 s .com*/

    World world = checkWorld(args, sender, 'w'); // Get the world
    String id = args.getString(0);
    RegionManager manager = checkRegionManager(plugin, world);
    ProtectedRegion region = checkExistingRegion(manager, id, true);

    // Check permissions
    if (!getPermissionModel(sender).mayRemoveMembers(region)) {
        throw new CommandPermissionsException();
    }

    ListenableFuture<?> future;

    if (args.hasFlag('a')) {
        region.getMembers().removeAll();

        future = Futures.immediateFuture(null);
    } else {
        if (args.argsLength() < 2) {
            throw new CommandException("List some names to remove, or use -a to remove all.");
        }

        // Resolve members asynchronously
        DomainInputResolver resolver = new DomainInputResolver(plugin.getProfileService(),
                args.getParsedPaddedSlice(1, 0));
        resolver.setLocatorPolicy(
                args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_AND_NAME);

        // Then remove it from the members
        future = Futures.transform(plugin.getExecutorService().submit(resolver),
                resolver.createRemoveAllFunction(region.getMembers()));
    }

    AsyncCommandHelper.wrap(future, plugin, sender).formatUsing(region.getId(), world.getName())
            .registerWithSupervisor("Removing members from the region '%s' on '%s'")
            .sendMessageAfterDelay("(Please wait... querying player names...)")
            .thenRespondWith("Region '%s' updated with members removed.", "Failed to remove members");
}

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

@Command(aliases = { "removemember", "remmember", "removemem", "remmem",
        "rm" }, usage = "<id> <owners...>", flags = "naw:", desc = "Remove an owner to a region", min = 1)
public void removeMember(CommandContext args, Actor sender) throws CommandException {
    warnAboutSaveFailures(sender);//from   w  w  w.ja va2  s .  c  om

    World world = checkWorld(args, sender, 'w'); // Get the world
    String id = args.getString(0);
    RegionManager manager = checkRegionManager(world);
    ProtectedRegion region = checkExistingRegion(manager, id, true);

    // Check permissions
    if (!getPermissionModel(sender).mayRemoveMembers(region)) {
        throw new CommandPermissionsException();
    }

    ListenableFuture<?> future;

    if (args.hasFlag('a')) {
        region.getMembers().removeAll();

        future = Futures.immediateFuture(null);
    } else {
        if (args.argsLength() < 2) {
            throw new CommandException("List some names to remove, or use -a to remove all.");
        }

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

        // Then remove it from the members
        future = Futures.transform(WorldGuard.getInstance().getExecutorService().submit(resolver),
                resolver.createRemoveAllFunction(region.getMembers()));
    }

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

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

@Override
public synchronized ListenableFuture<RpcResult<TransactionStatus>> performCommit() {
    final ListenableFuture<DOMRpcResult> rpcResult = netOps.commit(new NetconfRpcFutureCallback("Commit", id) {
        @Override//from  w ww.  java 2s.  co m
        public void onSuccess(final DOMRpcResult result) {
            super.onSuccess(result);
            LOG.debug("{}: Write successful, transaction: {}. Unlocking", id, getIdentifier());
            cleanupOnSuccess();
        }

        @Override
        protected void onUnsuccess(final DOMRpcResult result) {
            LOG.error("{}: Write failed, transaction {}, discarding changes, unlocking: {}", id,
                    getIdentifier(), result.getErrors());
            cleanup();
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.error("{}: Write failed, transaction {}, discarding changes, unlocking", id, getIdentifier(),
                    t);
            cleanup();
        }
    });

    return Futures.transform(rpcResult, RPC_RESULT_TO_TX_STATUS);
}

From source file:org.glassfish.jersey.examples.rx.agent.ListenableFutureAgentResource.java

private ListenableFuture<List<Recommendation>> forecasts(
        final ListenableFuture<List<Recommendation>> recommendations) {
    return Futures.transform(recommendations, new AsyncFunction<List<Recommendation>, List<Recommendation>>() {
        @Override/*from ww w.  j  av a  2s .  c om*/
        public ListenableFuture<List<Recommendation>> apply(final List<Recommendation> input) throws Exception {
            final RxWebTarget<RxListenableFutureInvoker> rxForecast = RxListenableFuture.from(forecast);
            return Futures.successfulAsList(
                    Lists.transform(input, new Function<Recommendation, ListenableFuture<Recommendation>>() {
                        @Override
                        public ListenableFuture<Recommendation> apply(final Recommendation r) {
                            return Futures.transform(
                                    rxForecast.resolveTemplate("destination", r.getDestination()).request().rx()
                                            .get(Forecast.class),
                                    new AsyncFunction<Forecast, Recommendation>() {
                                        @Override
                                        public ListenableFuture<Recommendation> apply(final Forecast f)
                                                throws Exception {
                                            r.setForecast(f.getForecast());
                                            return Futures.immediateFuture(r);
                                        }
                                    });
                        }
                    }));
        }
    });
}

From source file:net.oneandone.troilus.ListReadQuery.java

private ListenableFuture<ResultList<Record>> executeAsync(final ReadQueryData queryData, DBSession dbSession) {
    // 12-11-2015: jwestra - pagination support. Calls toStatementAsync() to perform
    // extra post-processing on the Statement to do pagination correctly
    // perform query
    ListenableFuture<ResultSet> resultSetFuture = performAsync(dbSession,
            toStatementAsync(queryData, getUDTValueMapper(), dbSession));

    //ListenableFuture<ResultSet> resultSetFuture = performAsync(dbSession, ReadQueryDataImpl.toStatementAsync(queryData, getUDTValueMapper(), dbSession));        

    // result set to record list mapper
    Function<ResultSet, ResultList<Record>> resultSetToRecordList = new Function<ResultSet, ResultList<Record>>() {

        @Override/*from  ww  w.  j  a  v a  2  s  .  co m*/
        public ResultList<Record> apply(ResultSet resultSet) {
            return new RecordListImpl(getContext(), queryData, resultSet);
        }
    };
    ListenableFuture<ResultList<Record>> recordListFuture = Futures.transform(resultSetFuture,
            resultSetToRecordList);

    // running interceptors within dedicated threads!
    return executeResponseInterceptorsAsync(queryData, recordListFuture);
}

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

public ListenableFuture<Observation[]> getObservations(CommandIndex index) {
    return Futures.transform(client.get(observationsAfter(index, Application_VALUE)), v -> {
        Service.Memory mem = v.getMemory();
        Observation[] obs = new Observation[mem.getReadsCount() + mem.getWritesCount()];
        int idx = 0;
        for (Service.MemoryRange read : mem.getReadsList()) {
            obs[idx++] = new Observation(index, true, read);
        }/*from  ww  w  . ja  v a2  s .c  o  m*/
        for (Service.MemoryRange write : mem.getWritesList()) {
            obs[idx++] = new Observation(index, false, write);
        }
        return obs;
    });
}

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

private ListenableFuture<Boolean> attemptTwoLevelStore(final ArtifactInfo info, final BorrowablePath output) {

    return Futures.transformAsync(Futures.immediateFuture(null), (AsyncFunction<Void, Boolean>) input -> {
        long fileSize = projectFilesystem.getFileSize(output.getPath());

        if (!performTwoLevelStores || fileSize < minimumTwoLevelStoredArtifactSize
                || (maximumTwoLevelStoredArtifactSize.isPresent()
                        && fileSize > maximumTwoLevelStoredArtifactSize.get())) {
            return Futures.immediateFuture(false);
        }/*ww w.j a v a 2  s  .c o m*/

        long hashComputationStart = System.currentTimeMillis();
        String hashCode = projectFilesystem.computeSha1(output.getPath()) + "2c00";
        long hashComputationEnd = System.currentTimeMillis();
        secondLevelHashComputationTimeMs.addSample(hashComputationEnd - hashComputationStart);

        ImmutableMap<String, String> metadataWithCacheKey = ImmutableMap.<String, String>builder()
                .putAll(info.getMetadata()).put(METADATA_KEY, hashCode).build();

        return Futures
                .transform(Futures.allAsList(
                        delegate.store(
                                ArtifactInfo.builder().setRuleKeys(info.getRuleKeys())
                                        .setMetadata(metadataWithCacheKey).build(),
                                BorrowablePath.notBorrowablePath(emptyFilePath)),
                        delegate.store(ArtifactInfo.builder().addRuleKeys(new RuleKey(hashCode)).build(),
                                output)),
                        Functions.constant(true));
    });
}

From source file:zipkin.storage.elasticsearch.ElasticsearchSpanStore.java

ListenableFuture<List<List<Span>>> getTracesByIds(Collection<String> traceIds, String[] indices,
        final QueryRequest request) {
    return Futures.transform(client.findSpans(indices, termsQuery("traceId", traceIds)),
            new Function<List<Span>, List<List<Span>>>() {
                @Override/*from   ww  w  .j a  va 2  s  .c om*/
                public List<List<Span>> apply(List<Span> input) {
                    if (input == null)
                        return Collections.emptyList();
                    // Due to tokenization of the trace ID, our matches are imprecise on Span.traceIdHigh
                    return FluentIterable.from(GroupByTraceId.apply(input, strictTraceId, true))
                            .filter(new Predicate<List<Span>>() {
                                @Override
                                public boolean apply(List<Span> input) {
                                    return input.get(0).traceIdHigh == 0 || request.test(input);
                                }
                            }).toList();
                }
            });
}

From source file:org.apache.twill.internal.AbstractTwillController.java

@Override
public ListenableFuture<String> restartInstances(final String runnable, Set<Integer> instanceIds) {
    return Futures.transform(restartInstances(ImmutableMap.of(runnable, instanceIds)),
            new Function<Set<String>, String>() {
                public String apply(Set<String> input) {
                    return runnable;
                }/*from w  ww .  jav  a  2s . com*/
            });
}