List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction
AsyncFunction
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)); }/*from ww w . j av a2 s. co 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.facebook.buck.util.concurrent.ResourcePool.java
/** * @param executorService where to perform the resource processing. Should really be a "real" * executor (not a directExecutor). * @return a {@link ListenableFuture} containing the result of the processing. The future will be * cancelled if the {@link ResourcePool#close()} method is called. *///from w w w.ja v a 2 s. c o m public synchronized <T> ListenableFuture<T> scheduleOperationWithResource(ThrowingFunction<R, T> withResource, final ListeningExecutorService executorService) { Preconditions.checkState(!closing.get()); final ListenableFuture<T> futureWork = Futures.transformAsync(initialSchedule(), new AsyncFunction<Void, T>() { @Override public ListenableFuture<T> apply(Void input) throws Exception { Either<R, ListenableFuture<Void>> resourceRequest = requestResource(); if (resourceRequest.isLeft()) { R resource = resourceRequest.getLeft(); boolean resourceIsDefunct = false; try { return Futures.immediateFuture(withResource.apply(resource)); } catch (Exception e) { resourceIsDefunct = (resourceUsageErrorPolicy == ResourceUsageErrorPolicy.RETIRE); throw e; } finally { returnResource(resource, resourceIsDefunct); } } else { return Futures.transformAsync(resourceRequest.getRight(), this, executorService); } } }, executorService); pendingWork.add(futureWork); futureWork.addListener(() -> { synchronized (ResourcePool.this) { pendingWork.remove(futureWork); } }, executorService); // If someone else calls cancel on `futureWork` it makes it impossible to wait for that future // to finish using the resource, which then makes shutdown code exit too early. return Futures.nonCancellationPropagating(futureWork); }
From source file:org.opendaylight.faas.fabric.general.FabricResourceAPIProvider.java
@Override public Future<RpcResult<AddFabricLinkOutput>> addFabricLink(AddFabricLinkInput input) { FabricId fabric1 = input.getSourceFabric(); FabricId fabric2 = input.getDestFabric(); TpId tp1 = input.getSourceFabricPort(); TpId tp2 = input.getDestFabricPort(); final LinkId lnkId = new LinkId(UUID.randomUUID().toString()); InstanceIdentifier<Link> path = MdSalUtils.createInterFabricLinkIId(lnkId); Link data = new LinkBuilder().setSource(new SourceBuilder().setSourceNode(fabric1).setSourceTp(tp1).build()) .setDestination(new DestinationBuilder().setDestNode(fabric2).setDestTp(tp2).build()) .setLinkId(lnkId).build();/* ww w .ja va 2 s .c om*/ WriteTransaction wt = dataBroker.newWriteOnlyTransaction(); wt.put(LogicalDatastoreType.CONFIGURATION, path, data); wt.put(LogicalDatastoreType.OPERATIONAL, path, data); CheckedFuture<Void, TransactionCommitFailedException> future = wt.submit(); return Futures.transform(future, new AsyncFunction<Void, RpcResult<AddFabricLinkOutput>>() { @Override public ListenableFuture<RpcResult<AddFabricLinkOutput>> apply(Void submitResult) throws Exception { RpcResultBuilder<AddFabricLinkOutput> resultBuilder = RpcResultBuilder .<AddFabricLinkOutput>success(); AddFabricLinkOutput output = new AddFabricLinkOutputBuilder().setLinkId(lnkId).build(); return Futures.immediateFuture(resultBuilder.withResult(output).build()); } }); }
From source file:com.continuuity.weave.internal.ZKServiceDecorator.java
/** * Deletes the given ZK path recursively and create the path again. *//* ww w . j ava2s . co m*/ private ListenableFuture<String> deleteAndCreate(final String path, final byte[] data, final CreateMode mode) { return Futures.transform(ZKOperations.ignoreError(ZKOperations.recursiveDelete(zkClient, path), KeeperException.NoNodeException.class, null), new AsyncFunction<String, String>() { @Override public ListenableFuture<String> apply(String input) throws Exception { return zkClient.create(path, data, mode); } }, Threads.SAME_THREAD_EXECUTOR); }
From source file:org.glowroot.central.util.MoreFutures.java
private static <V, R> ListenableFuture<R> transformAsync(ListenableFuture<V> future, Executor asyncExecutor, AsyncFunction<V, R> function) { boolean inRollupThread = Session.isInRollupThread(); return Futures.transformAsync(future, new AsyncFunction<V, R>() { @Override// ww w . j a v a 2 s . c o m public ListenableFuture<R> apply(V input) throws Exception { boolean priorInRollupThread = Session.isInRollupThread(); Session.setInRollupThread(inRollupThread); try { return function.apply(input); } finally { Session.setInRollupThread(priorInRollupThread); } } }, // calls to Session.readAsync() inside of the function could block due to the // per-thread concurrent limit, so this needs to be executed in its own thread, not // in the cassandra driver thread that completes the last future which will block // the cassandra driver thread pool asyncExecutor); }
From source file:io.vitess.client.VTGateTx.java
public synchronized SQLFuture<Cursor> execute(Context ctx, String query, Map<String, ?> bindVars, TabletType tabletType, Query.ExecuteOptions.IncludedFields includedFields) throws SQLException { checkCallIsAllowed("execute"); ExecuteRequest.Builder requestBuilder = ExecuteRequest.newBuilder() .setQuery(Proto.bindQuery(query, bindVars)).setKeyspaceShard(keyspace).setTabletType(tabletType) .setSession(session)//from w ww. java2 s .co m .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields)); if (ctx.getCallerId() != null) { requestBuilder.setCallerId(ctx.getCallerId()); } SQLFuture<Cursor> call = new SQLFuture<>(transformAsync(client.execute(ctx, requestBuilder.build()), new AsyncFunction<ExecuteResponse, Cursor>() { @Override public ListenableFuture<Cursor> apply(ExecuteResponse response) throws Exception { setSession(response.getSession()); Proto.checkError(response.getError()); return Futures.<Cursor>immediateFuture(new SimpleCursor(response.getResult())); } }, directExecutor())); lastCall = call; return call; }
From source file:org.glassfish.jersey.examples.rx.agent.ListenableFutureAgentResource.java
private ListenableFuture<AgentResponse> visited(final AgentResponse response) { final ListenableFuture<List<Destination>> visited = RxListenableFuture.from(destination).path("visited") .request()/*from ww w.j a v a 2s.c o m*/ // Identify the user. .header("Rx-User", "Guava") // Reactive invoker. .rx() // Return a list of destinations. .get(new GenericType<List<Destination>>() { }); return Futures.transform(visited, new AsyncFunction<List<Destination>, AgentResponse>() { @Override public ListenableFuture<AgentResponse> apply(final List<Destination> input) throws Exception { final SettableFuture<AgentResponse> future = SettableFuture.create(); response.setVisited(input); future.set(response); return future; } }); }
From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java
public ListenableFuture<T> read(Identifier id) { ListenableFuture<ResultSet> rs = submitRead(id); return Futures.transformAsync(rs, new AsyncFunction<ResultSet, T>() { @Override//from w w w.j a v a 2 s . co m public ListenableFuture<T> apply(ResultSet result) { if (result.isExhausted()) { return Futures.immediateFailedFuture(new ItemNotFoundException(id.toString())); } return Futures.immediateFuture(marshalRow(result.one())); } }, MoreExecutors.directExecutor()); }
From source file:org.opendaylight.vpnservice.natservice.internal.VpnFloatingIpHandler.java
@Override public void onAddFloatingIp(final BigInteger dpnId, final String routerId, Uuid networkId, final String interfaceName, final String externalIp, final String internalIp) { final String vpnName = NatUtil.getAssociatedVPN(dataBroker, networkId, LOG); if (vpnName == null) { LOG.info("No VPN associated with ext nw {} to handle add floating ip configuration {} in router {}", networkId, externalIp, routerId); return;/*from ww w . j a v a2s . com*/ } GenerateVpnLabelInput labelInput = new GenerateVpnLabelInputBuilder().setVpnName(vpnName) .setIpPrefix(externalIp).build(); Future<RpcResult<GenerateVpnLabelOutput>> labelFuture = vpnService.generateVpnLabel(labelInput); ListenableFuture<RpcResult<Void>> future = Futures.transform( JdkFutureAdapters.listenInPoolThread(labelFuture), new AsyncFunction<RpcResult<GenerateVpnLabelOutput>, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(RpcResult<GenerateVpnLabelOutput> result) throws Exception { if (result.isSuccessful()) { GenerateVpnLabelOutput output = result.getResult(); long label = output.getLabel(); LOG.debug("Generated label {} for prefix {}", label, externalIp); listener.updateOperationalDS(routerId, interfaceName, (int) label, internalIp, externalIp); //Inform BGP String rd = NatUtil.getVpnRd(dataBroker, vpnName); String nextHopIp = NatUtil.getEndpointIpAddressForDPN(dataBroker, dpnId); LOG.debug("Nexthop ip for prefix {} is {}", externalIp, nextHopIp); NatUtil.addPrefixToBGP(bgpManager, rd, externalIp + "/32", nextHopIp, label, LOG); List<Instruction> instructions = new ArrayList<Instruction>(); List<ActionInfo> actionsInfos = new ArrayList<ActionInfo>(); actionsInfos.add(new ActionInfo(ActionType.nx_resubmit, new String[] { Integer.toString(NatConstants.PDNAT_TABLE) })); instructions.add(new InstructionInfo(InstructionType.apply_actions, actionsInfos) .buildInstruction(0)); makeTunnelTableEntry(dpnId, label, instructions); //Install custom FIB routes List<Instruction> customInstructions = new ArrayList<>(); customInstructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { NatConstants.PDNAT_TABLE }).buildInstruction(0)); makeLFibTableEntry(dpnId, label, NatConstants.PDNAT_TABLE); CreateFibEntryInput input = new CreateFibEntryInputBuilder().setVpnName(vpnName) .setSourceDpid(dpnId).setInstruction(customInstructions) .setIpAddress(externalIp + "/32").setServiceId(label) .setInstruction(customInstructions).build(); //Future<RpcResult<java.lang.Void>> createFibEntry(CreateFibEntryInput input); Future<RpcResult<Void>> future = fibService.createFibEntry(input); return JdkFutureAdapters.listenInPoolThread(future); } else { String errMsg = String.format( "Could not retrieve the label for prefix %s in VPN %s, %s", externalIp, vpnName, result.getErrors()); LOG.error(errMsg); return Futures.immediateFailedFuture(new RuntimeException(errMsg)); } } }); Futures.addCallback(future, new FutureCallback<RpcResult<Void>>() { @Override public void onFailure(Throwable error) { LOG.error("Error in generate label or fib install process", error); } @Override public void onSuccess(RpcResult<Void> result) { if (result.isSuccessful()) { LOG.info("Successfully installed custom FIB routes for prefix {}", externalIp); } else { LOG.error("Error in rpc call to create custom Fib entries for prefix {} in DPN {}, {}", externalIp, dpnId, result.getErrors()); } } }); }
From source file:org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SyncPlanPushStrategyIncrementalImpl.java
@Override public ListenableFuture<RpcResult<Void>> executeSyncStrategy(ListenableFuture<RpcResult<Void>> resultVehicle, final SynchronizationDiffInput diffInput, final SyncCrudCounters counters) { final InstanceIdentifier<FlowCapableNode> nodeIdent = diffInput.getNodeIdent(); final NodeId nodeId = PathUtil.digNodeId(nodeIdent); /* Tables - have to be pushed before groups */ // TODO enable table-update when ready //resultVehicle = updateTableFeatures(nodeIdent, configTree); resultVehicle = Futures.transform(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() { @Override// w w w. j a v a 2s . c o m public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception { if (!input.isSuccessful()) { //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input); //final ListenableFuture<RpcResult<Void>> singleVoidUpdateResult = Futures.transform( // Futures.asList Arrays.asList(input, output), // ReconcileUtil.<UpdateFlowOutput>createRpcResultCondenser("TODO")); } return addMissingGroups(nodeId, nodeIdent, diffInput.getGroupsToAddOrUpdate(), counters); } }); Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "addMissingGroups")); resultVehicle = Futures.transform(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception { if (!input.isSuccessful()) { //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input); } return addMissingMeters(nodeId, nodeIdent, diffInput.getMetersToAddOrUpdate(), counters); } }); Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "addMissingMeters")); resultVehicle = Futures.transform(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception { if (!input.isSuccessful()) { //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input); } return addMissingFlows(nodeId, nodeIdent, diffInput.getFlowsToAddOrUpdate(), counters); } }); Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "addMissingFlows")); resultVehicle = Futures.transform(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception { if (!input.isSuccessful()) { //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input); } return removeRedundantFlows(nodeId, nodeIdent, diffInput.getFlowsToRemove(), counters); } }); Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "removeRedundantFlows")); resultVehicle = Futures.transform(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception { if (!input.isSuccessful()) { //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input); } return removeRedundantMeters(nodeId, nodeIdent, diffInput.getMetersToRemove(), counters); } }); Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "removeRedundantMeters")); resultVehicle = Futures.transform(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception { if (!input.isSuccessful()) { //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input); } return removeRedundantGroups(nodeId, nodeIdent, diffInput.getGroupsToRemove(), counters); } }); Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "removeRedundantGroups")); return resultVehicle; }