List of usage examples for com.google.common.util.concurrent Futures transform
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function)
From source file:org.opendaylight.controller.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider.java
@Override public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource( final SourceIdentifier sourceIdentifier) { final String moduleName = sourceIdentifier.getName(); // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request final String formattedRevision = sourceIdentifier.getRevision() .equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) ? null : sourceIdentifier.getRevision(); final Optional<String> revision = Optional.fromNullable(formattedRevision); final NormalizedNode<?, ?> getSchemaRequest = createGetSchemaRequest(moduleName, revision); logger.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision); final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform( rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),// ww w .j a v a2 s . co m new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision)); final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed, MAPPER); // / FIXME remove this get, it is only present to wait until source is retrieved // (goal is to limit concurrent schema download, since NetconfDevice listener does not handle concurrent messages properly) // TODO retest this try { logger.trace("{}: Blocking for {}", id, sourceIdentifier); checked.checkedGet(); } catch (final SchemaSourceException e) { return Futures.immediateFailedCheckedFuture(e); } return checked; }
From source file:com.continuuity.weave.internal.logging.KafkaAppender.java
private ListenableFuture<Integer> publishLogs() { // If the publisher is not available, simply returns a completed future. PreparePublish publisher = KafkaAppender.this.publisher.get(); if (publisher == null) { return Futures.immediateFuture(0); }//from w ww .j a va 2 s . c om int count = 0; for (String json : Iterables.consumingIterable(buffer)) { publisher.add(Charsets.UTF_8.encode(json), 0); count++; } // Nothing to publish, simply returns a completed future. if (count == 0) { return Futures.immediateFuture(0); } bufferedSize.set(0); final int finalCount = count; return Futures.transform(publisher.publish(), new Function<Object, Integer>() { @Override public Integer apply(Object input) { return finalCount; } }); }
From source file:org.opendaylight.bgpcep.pcep.tunnel.provider.CreateTunnelInstructionExecutor.java
@Override protected ListenableFuture<OperationResult> invokeOperation() { try (final ReadOnlyTransaction transaction = this.dataProvider.newReadOnlyTransaction()) { AddLspInput addLspInput = createAddLspInput(transaction); return Futures.transform( (ListenableFuture<RpcResult<AddLspOutput>>) this.topologyService.addLsp(addLspInput), new Function<RpcResult<AddLspOutput>, OperationResult>() { @Override/*from ww w .j av a2 s .c o m*/ public OperationResult apply(final RpcResult<AddLspOutput> input) { return input.getResult(); } }); } }
From source file:org.blackbananacoin.twd2btc.ExtRateGenServiceImpl.java
public void startRequest(final MyCallback mcb) throws Exception { HttpTransport transport = new NetHttpTransport.Builder().doNotValidateCertificate().build(); HttpRequestFactory requestFactory = transport.createRequestFactory(new HttpRequestInitializer() { public void initialize(HttpRequest request) { request.setParser(new JsonObjectParser(JSON_FACTORY)); }//from w ww . ja va 2 s . com }); 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()); rmap.put(GenType.TWDUSD, twdJsonBuilder.buildJson(twdPerUsd, usdPerBtc)); 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:org.opendaylight.openflowplugin.impl.services.SalMetersBatchServiceImpl.java
@Override public Future<RpcResult<AddMetersBatchOutput>> addMetersBatch(final AddMetersBatchInput input) { LOG.trace("Adding meters @ {} : {}", PathUtil.extractNodeId(input.getNode()), input.getBatchAddMeters().size()); final ArrayList<ListenableFuture<RpcResult<AddMeterOutput>>> resultsLot = new ArrayList<>(); for (BatchAddMeters addMeter : input.getBatchAddMeters()) { final AddMeterInput addMeterInput = new AddMeterInputBuilder(addMeter) .setMeterRef(createMeterRef(input.getNode(), addMeter)).setNode(input.getNode()).build(); resultsLot.add(JdkFutureAdapters.listenInPoolThread(salMeterService.addMeter(addMeterInput))); }//from w w w. j a v a 2s . c o m final ListenableFuture<RpcResult<List<BatchFailedMetersOutput>>> commonResult = Futures.transform( Futures.allAsList(resultsLot), MeterUtil.<AddMeterOutput>createCumulativeFunction(input.getBatchAddMeters())); ListenableFuture<RpcResult<AddMetersBatchOutput>> addMetersBulkFuture = Futures.transform(commonResult, MeterUtil.METER_ADD_TRANSFORM); if (input.isBarrierAfter()) { addMetersBulkFuture = BarrierUtil.chainBarrier(addMetersBulkFuture, input.getNode(), transactionService, MeterUtil.METER_ADD_COMPOSING_TRANSFORM); } return addMetersBulkFuture; }
From source file:org.opendaylight.openflowplugin.impl.services.SalGroupsBatchServiceImpl.java
@Override public Future<RpcResult<AddGroupsBatchOutput>> addGroupsBatch(final AddGroupsBatchInput input) { LOG.trace("Adding groups @ {} : {}", PathUtil.extractNodeId(input.getNode()), input.getBatchAddGroups().size()); final ArrayList<ListenableFuture<RpcResult<AddGroupOutput>>> resultsLot = new ArrayList<>(); for (BatchAddGroups addGroup : input.getBatchAddGroups()) { final AddGroupInput addGroupInput = new AddGroupInputBuilder(addGroup) .setGroupRef(createGroupRef(input.getNode(), addGroup)).setNode(input.getNode()).build(); resultsLot.add(JdkFutureAdapters.listenInPoolThread(salGroupService.addGroup(addGroupInput))); }/*from ww w. ja va2 s .c o m*/ final ListenableFuture<RpcResult<List<BatchFailedGroupsOutput>>> commonResult = Futures.transform( Futures.allAsList(resultsLot), GroupUtil.<AddGroupOutput>createCumulatingFunction(input.getBatchAddGroups())); ListenableFuture<RpcResult<AddGroupsBatchOutput>> addGroupsBulkFuture = Futures.transform(commonResult, GroupUtil.GROUP_ADD_TRANSFORM); if (input.isBarrierAfter()) { addGroupsBulkFuture = BarrierUtil.chainBarrier(addGroupsBulkFuture, input.getNode(), transactionService, GroupUtil.GROUP_ADD_COMPOSING_TRANSFORM); } return addGroupsBulkFuture; }
From source file:com.facebook.watchman.WatchmanClientImpl.java
/** * unsubscribes from all the subscriptions; convenience method */// ww w. j a v a 2s . c o m @Override public ListenableFuture<Boolean> unsubscribeAll() { Collection<ListenableFuture<Boolean>> unsubscribeAll = Collections2.transform(subscriptions.keySet(), new Function<SubscriptionDescriptor, ListenableFuture<Boolean>>() { @Nullable @Override public ListenableFuture<Boolean> apply(@Nullable SubscriptionDescriptor input) { return unsubscribe(input); } }); return Futures.transform(Futures.allAsList(unsubscribeAll), new Function<List<Boolean>, Boolean>() { @Nullable @Override public Boolean apply(@Nullable List<Boolean> input) { return !Collections2.filter(input, Predicates.equalTo(false)).isEmpty(); } }); }
From source file:com.google.gerrit.server.index.ChangeBatchIndexer.java
public Result indexAll(ChangeIndex index, Iterable<Project.NameKey> projects, int numProjects, int numChanges, OutputStream progressOut, OutputStream verboseOut) { if (progressOut == null) { progressOut = NullOutputStream.INSTANCE; }// w ww.java 2 s .c om PrintWriter verboseWriter = verboseOut != null ? new PrintWriter(verboseOut) : null; Stopwatch sw = Stopwatch.createStarted(); final MultiProgressMonitor mpm = new MultiProgressMonitor(progressOut, "Reindexing changes"); final Task projTask = mpm.beginSubTask("projects", numProjects >= 0 ? numProjects : MultiProgressMonitor.UNKNOWN); final Task doneTask = mpm.beginSubTask(null, numChanges >= 0 ? numChanges : MultiProgressMonitor.UNKNOWN); final Task failedTask = mpm.beginSubTask("failed", MultiProgressMonitor.UNKNOWN); final List<ListenableFuture<?>> futures = Lists.newArrayList(); final AtomicBoolean ok = new AtomicBoolean(true); for (final Project.NameKey project : projects) { if (!updateMergeable(project)) { ok.set(false); } final ListenableFuture<?> future = executor.submit( reindexProject(indexerFactory.create(index), project, doneTask, failedTask, verboseWriter)); futures.add(future); future.addListener(new Runnable() { @Override public void run() { try { future.get(); } catch (InterruptedException e) { fail(project, e); } catch (ExecutionException e) { fail(project, e); } catch (RuntimeException e) { failAndThrow(project, e); } catch (Error e) { failAndThrow(project, e); } finally { projTask.update(1); } } private void fail(Project.NameKey project, Throwable t) { log.error("Failed to index project " + project, t); ok.set(false); } private void failAndThrow(Project.NameKey project, RuntimeException e) { fail(project, e); throw e; } private void failAndThrow(Project.NameKey project, Error e) { fail(project, e); throw e; } }, MoreExecutors.sameThreadExecutor()); } try { mpm.waitFor(Futures.transform(Futures.successfulAsList(futures), new AsyncFunction<List<?>, Void>() { @Override public ListenableFuture<Void> apply(List<?> input) { mpm.end(); return Futures.immediateFuture(null); } })); } catch (ExecutionException e) { log.error("Error in batch indexer", e); ok.set(false); } return new Result(sw, ok.get(), doneTask.getCount(), failedTask.getCount()); }
From source file:com.google.cloud.pubsub.PubSubImpl.java
private static <I, O> Future<O> transform(Future<I> future, Function<? super I, ? extends O> function) { if (future instanceof ListenableFuture) { return Futures.transform((ListenableFuture<I>) future, function); }//from ww w . j ava2 s.co m return Futures.lazyTransform(future, function); }
From source file:org.opendaylight.controller.md.sal.dom.broker.impl.legacy.sharded.adapter.ShardedDOMDataBrokerDelegatingReadWriteTransaction.java
@Override public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) { checkState(root != null,//w ww. j av a 2s . c o m "A modify operation (put, merge or delete) must be performed prior to an exists operation"); return Futures.makeChecked( Futures.transform(read(store, path), (Function<Optional<NormalizedNode<?, ?>>, Boolean>) Optional::isPresent), ReadFailedException.MAPPER); }