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.glassfish.jersey.examples.rx.agent.ListenableFutureAgentResource.java
private ListenableFuture<AgentResponse> recommended(final AgentResponse response) { // Destinations. final ListenableFuture<List<Destination>> recommended = RxListenableFuture.from(destination) .path("recommended").request() // Identify the user. .header("Rx-User", "Guava") // Reactive invoker. .rx()//from w w w. j ava 2 s .com // Return a list of destinations. .get(new GenericType<List<Destination>>() { }); final ListenableFuture<List<Recommendation>> recommendations = Futures.transform(recommended, new AsyncFunction<List<Destination>, List<Recommendation>>() { @Override public ListenableFuture<List<Recommendation>> apply(final List<Destination> input) throws Exception { final List<Recommendation> recommendations = Lists .newArrayList(Lists.transform(input, new Function<Destination, Recommendation>() { @Override public Recommendation apply(final Destination input) { return new Recommendation(input.getDestination(), null, 0); } })); return Futures.immediateFuture(recommendations); } }); final ListenableFuture<List<List<Recommendation>>> syncedFuture = Futures.successfulAsList(Arrays.asList( // Add Forecasts to Recommendations. forecasts(recommendations), // Add Forecasts to Recommendations. calculations(recommendations))); return Futures.transform(syncedFuture, new AsyncFunction<List<List<Recommendation>>, AgentResponse>() { @Override public ListenableFuture<AgentResponse> apply(final List<List<Recommendation>> input) throws Exception { response.setRecommended(input.get(0)); return Futures.immediateFuture(response); } }); }
From source file:org.thingsboard.server.controller.EntityViewController.java
private ListenableFuture<List<Void>> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection<String> keys, SecurityUser user) throws ThingsboardException { EntityViewId entityId = entityView.getId(); if (keys != null && !keys.isEmpty()) { ListenableFuture<List<AttributeKvEntry>> getAttrFuture = attributesService.find(getTenantId(), entityView.getEntityId(), scope, keys); return Futures.transform(getAttrFuture, attributeKvEntries -> { List<AttributeKvEntry> attributes; if (attributeKvEntries != null && !attributeKvEntries.isEmpty()) { attributes = attributeKvEntries.stream().filter(attributeKvEntry -> { long startTime = entityView.getStartTimeMs(); long endTime = entityView.getEndTimeMs(); long lastUpdateTs = attributeKvEntry.getLastUpdateTs(); return startTime == 0 && endTime == 0 || (endTime == 0 && startTime < lastUpdateTs) || (startTime == 0 && endTime > lastUpdateTs) ? true : startTime < lastUpdateTs && endTime > lastUpdateTs; }).collect(Collectors.toList()); tsSubService.saveAndNotify(entityView.getTenantId(), entityId, scope, attributes, new FutureCallback<Void>() { @Override public void onSuccess(@Nullable Void tmp) { try { logAttributesUpdated(user, entityId, scope, attributes, null); } catch (ThingsboardException e) { log.error("Failed to log attribute updates", e); }//w w w .j av a 2 s . co m } @Override public void onFailure(Throwable t) { try { logAttributesUpdated(user, entityId, scope, attributes, t); } catch (ThingsboardException e) { log.error("Failed to log attribute updates", e); } } }); } return null; }); } else { return Futures.immediateFuture(null); } }
From source file:co.cask.cdap.common.zookeeper.coordination.ResourceCoordinatorClient.java
/** * Fetches the {@link ResourceRequirement} for the given resource. * * @param resourceName Name of the resource. * @return A {@link ListenableFuture} that will be completed when the requirement is fetch. A {@code null} result * will be set into the future if no such requirement exists. The future will fail if failed to fetch * the requirement due to error other than requirement not exists. * Calling {@link ListenableFuture#cancel(boolean)} has no effect. *///from www .j a va 2 s . co m public ListenableFuture<ResourceRequirement> fetchRequirement(String resourceName) { String zkPath = CoordinationConstants.REQUIREMENTS_PATH + "/" + resourceName; return Futures.transform( ZKOperations.ignoreError(zkClient.getData(zkPath), KeeperException.NoNodeException.class, null), NODE_DATA_TO_REQUIREMENT); }
From source file:org.opendaylight.distributed.tx.it.provider.datawriter.DtxNetconfAsyncWriter.java
/** * Asynchronously write configuration to NetConf device with distributed-tx API *//*from w ww . j av a 2 s.c o m*/ @Override public void writeData() { int putsPerTx = input.getPutsPerTx(); int counter = 0; List<ListenableFuture<Void>> putFutures = new ArrayList<ListenableFuture<Void>>(putsPerTx); List<NodeId> nodeIdList = new ArrayList(this.nodeIdSet); Set<InstanceIdentifier<?>> txIidSet = new HashSet<>(); NodeId nodeId = nodeIdList.get(0); InstanceIdentifier msNodeId = NETCONF_TOPO_IID.child(Node.class, new NodeKey(nodeId)); InterfaceName ifName = nodeIfList.get(nodeId).get(0); if (input.getOperation() == OperationType.DELETE) { //Build subInterfaces for delete operation configInterface(); } txIidSet.add(msNodeId); dtx = dTxProvider.newTx(txIidSet); startTime = System.nanoTime(); for (int i = 1; i <= input.getLoop(); i++) { KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid .child(InterfaceConfiguration.class, new InterfaceConfigurationKey( new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), ifName)); InterfaceConfigurationBuilder interfaceConfigurationBuilder = new InterfaceConfigurationBuilder(); interfaceConfigurationBuilder.setInterfaceName(ifName); interfaceConfigurationBuilder .setDescription(DTXITConstants.TEST_DESCRIPTION + input.getOperation() + i); interfaceConfigurationBuilder.setActive(new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE)); InterfaceConfiguration config = interfaceConfigurationBuilder.build(); CheckedFuture<Void, DTxException> writeFuture = null; if (input.getOperation() == OperationType.PUT) { //Put configuration to the same interface writeFuture = dtx.putAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid, config, msNodeId); } else if (input.getOperation() == OperationType.MERGE) { //Merge configuration to the same interface writeFuture = dtx.mergeAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid, config, msNodeId); } else { //Delete subInterfaces InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i); KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> subSpecificInterfaceCfgIid = netconfIid .child(InterfaceConfiguration.class, new InterfaceConfigurationKey( new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName)); writeFuture = dtx.deleteAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION, subSpecificInterfaceCfgIid, msNodeId); } putFutures.add(writeFuture); counter++; if (counter == putsPerTx) { ListenableFuture<Void> aggregatePutFuture = Futures.transform(Futures.allAsList(putFutures), new Function<List<Void>, Void>() { @Nullable @Override public Void apply(@Nullable List<Void> voids) { return null; } }); try { aggregatePutFuture.get(); CheckedFuture<Void, TransactionCommitFailedException> submitFuture = dtx.submit(); try { submitFuture.checkedGet(); txSucceed++; } catch (TransactionCommitFailedException e) { txError++; } } catch (Exception e) { txError++; dtx.cancel(); } counter = 0; dtx = dTxProvider.newTx(txIidSet); putFutures = new ArrayList<ListenableFuture<Void>>((int) putsPerTx); } } ListenableFuture<Void> aggregatePutFuture = Futures.transform(Futures.allAsList(putFutures), new Function<List<Void>, Void>() { @Nullable @Override public Void apply(@Nullable List<Void> voids) { return null; } }); try { aggregatePutFuture.get(); CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dtx.submit(); try { restSubmitFuture.checkedGet(); txSucceed++; } catch (Exception e) { txError++; } } catch (Exception e) { txError++; } endTime = System.nanoTime(); }
From source file:org.opendaylight.openflowplugin.impl.services.SalFlatBatchServiceImpl.java
@VisibleForTesting Future<RpcResult<ProcessFlatBatchOutput>> executeBatchPlan(final List<BatchStepJob> batchJobsChain) { BatchStepJob batchJob;//ww w . j a v a 2 s. co m final List<ListenableFuture<RpcResult<ProcessFlatBatchOutput>>> firedJobs = new ArrayList<>(); ListenableFuture<RpcResult<ProcessFlatBatchOutput>> chainSummaryResult = FlatBatchUtil .createEmptyRpcBatchResultFuture(true); for (int i = 0; i < batchJobsChain.size(); i++) { batchJob = batchJobsChain.get(i); // wire actual job with chain firedJobs.add(Futures.transform(chainSummaryResult, batchJob.getStepFunction())); // if barrier after actual job is needed or it is the last job -> merge fired job results with chain result if ((batchJob.getPlanStep().isBarrierAfter()) || (i == batchJobsChain.size() - 1)) { firedJobs.add(0, chainSummaryResult); chainSummaryResult = FlatBatchUtil.mergeJobsResultsFutures(firedJobs); firedJobs.clear(); } } return chainSummaryResult; }
From source file:org.opendaylight.toaster.impl.ToasterServiceImpl.java
@Override public Future<RpcResult<java.lang.Void>> makeToast(final MakeToastInput input) { LOG.info("makeToast: {}", input); String name = ManagementFactory.getRuntimeMXBean().getName(); LOG.info(name);// www . j ava 2 s . c om // get pid String pid = name.split("@")[0]; LOG.info("#########pid is:" + pid); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//? String time = df.format(new Date()); LOG.info("#########time is " + time);// new Date()?? String tid = Long.toString(Thread.currentThread().getId()); LOG.info("#########tid is:" + tid); record("makeToast", time, pid, tid); final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build(); final ReadWriteTransaction tx = broker.newReadWriteTransaction(); ListenableFuture<Optional<Toaster>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, TOASTER_IID); //Optional<Toaster>ListenableFuture??VoidListenableFuture final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, new AsyncFunction<Optional<Toaster>, Void>() { @Override public ListenableFuture<Void> apply(final Optional<Toaster> toasterData) throws Exception { //?toastertasterStatus ToasterStatus toasterStatus = ToasterStatus.Down; if (toasterData.isPresent()) { toasterStatus = toasterData.get().getToasterStatus(); } //???Up if (toasterStatus == ToasterStatus.Up) { //Up? LOG.info("the toaster is already using,please wait a moment!"); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", RpcResultBuilder.newWarning( ErrorType.APPLICATION, "in-use", "Toaster is busy", null, null, null))); } else { //down??Up? tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID, new ToasterBuilder().setToasterStatus(ToasterStatus.Up).build()); return tx.submit(); } } }); //callback Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { // data store?makeToast LOG.info("******Task Starts******"); currentMakeToastTask.set(executor.submit(new MakeToastTask(input))); } @Override public void onFailure(final Throwable ex) { LOG.debug("Failed to commit Toaster status", ex); } }); return Futures.immediateFuture(RpcResultBuilder.<Void>success().build()); }
From source file:com.microsoft.azure.keyvault.extensions.KeyVaultKey.java
@Override public ListenableFuture<byte[]> unwrapKeyAsync(byte[] ciphertext, String algorithm) { if (implementation == null) { return null; }/* www . j a v a 2 s . c o m*/ if (Strings.isNullOrWhiteSpace(algorithm)) { algorithm = getDefaultKeyWrapAlgorithm(); } // Never local ListenableFuture<KeyOperationResult> futureCall = client.unwrapKeyAsync(implementation.getKid(), new JsonWebKeyEncryptionAlgorithm(algorithm), ciphertext, null); return Futures.transform(futureCall, new DecryptResultTransform()); }
From source file:org.opendaylight.faas.fabric.general.FabricResourceAPIProvider.java
@Override public Future<RpcResult<Void>> setFabricPortRole(SetFabricPortRoleInput input) { InstanceIdentifier<FportAttribute> iid = MdSalUtils .createFabricPortIId(input.getFabricId(), input.getFabricPortId()) .augmentation(FabricPortAugment.class).child(FportAttribute.class); FportAttributeBuilder builder = new FportAttributeBuilder(); builder.setRole(input.getPortRole()); WriteTransaction wt = dataBroker.newWriteOnlyTransaction(); wt.put(LogicalDatastoreType.OPERATIONAL, iid, builder.build()); CheckedFuture<Void, TransactionCommitFailedException> future = wt.submit(); return Futures.transform(future, new AsyncFunction<Void, RpcResult<Void>>() { @Override/*from w w w . j a va 2 s.c o m*/ public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception { RpcResultBuilder<Void> resultBuilder = RpcResultBuilder.<Void>success(); return Futures.immediateFuture(resultBuilder.build()); } }); }
From source file:org.opendaylight.controller.cluster.datastore.TransactionProxy.java
private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() { final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames(); final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>( allShardNames.size());//from w w w . j av a 2s . c o m for (String shardName : allShardNames) { futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY)); } final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures); final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture; aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() { @Override public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) { try { return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext(), txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType()); } catch (DataValidationFailedException e) { throw new IllegalArgumentException("Failed to aggregate", e); } } }); return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER); }
From source file:de.dfki.kiara.impl.DefaultInvocationHandler.java
@Override protected Object handleInvocation(Object o, Method method, Object[] os) throws Throwable { if (method.equals(SpecialMethods.riGetConnection)) { return connection; }//from w ww . java 2s . co m InterfaceMapping<?> mapping = getInterfaceMapping(); final String idlFunctionName = mapping.getIDLMethodName(method); if (idlFunctionName == null) { throw new UnsupportedOperationException("Unbound method: " + method); } // check for Future<?> final MethodEntry methodEntry = mapping.getMethodEntry(method); logger.debug("has future params {} has listeningfuture params {}", methodEntry.hasFutureParams, methodEntry.hasListeningFutureParams); ListenableFuture<List<Object>> futureParams = null; if (methodEntry.hasFutureParams) { List<ListenableFuture<Object>> futureParamsList = new ArrayList<>(os.length); for (int i = 0; i < os.length; ++i) { final Function<Object, Object> f = ((Function<Object, Object>) methodEntry.paramConverters[i]); futureParamsList.add((ListenableFuture<Object>) f.apply(os[i])); } futureParams = Futures.allAsList(futureParamsList); //System.out.format("futureParams = %s%n", Joiner.on(" ").join(futureParams.get())); } if (methodEntry.kind == MethodEntry.MethodKind.SERIALIZER) { if (futureParams != null) { return protocol .createRequestMessage(new Message.RequestObject(idlFunctionName, futureParams.get())); } else { return protocol.createRequestMessage(new Message.RequestObject(idlFunctionName, os)); } } else if (methodEntry.kind == MethodEntry.MethodKind.DESERIALIZER) { Message msg = (Message) os[0]; Message.ResponseObject ro = msg.getResponseObject(TypeToken.of(method.getGenericReturnType())); if (ro.isException) { if (ro.result instanceof Exception) { throw (Exception) ro.result; } throw new WrappedRemoteException(ro.result); } return ro.result; } else { if (futureParams != null && methodEntry.futureParamOfReturnType != null) { AsyncFunction<List<Object>, Object> f = new AsyncFunction<List<Object>, Object>() { @Override public ListenableFuture<Object> apply(List<Object> params) throws Exception { final Message request = protocol .createRequestMessage(new Message.RequestObject(idlFunctionName, params)); final TypeToken<?> returnType = TypeToken.of(methodEntry.futureParamOfReturnType); final ListenableFuture<Message> responseFuture = connection.performRemoteAsyncCall(request, Global.executor); AsyncFunction<Message, Object> g = new AsyncFunction<Message, Object>() { @Override public ListenableFuture<Object> apply(final Message response) throws Exception { return Global.executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { Message.ResponseObject ro = response.getResponseObject(returnType); if (ro.isException) { if (ro.result instanceof Exception) { throw (Exception) ro.result; } throw new WrappedRemoteException(ro.result); } return ro.result; } }); } }; return Futures.transform(responseFuture, g); } }; return Futures.transform(futureParams, f); } else { /* Following code is for testing of synchronous message sending if (futureParams == null && methodEntry.futureParamOfReturnType == null) { final Message request = protocol.createRequestMessage(new Message.RequestObject(idlFunctionName, os)); final Message response = performSyncCall(request, method); final Message.ResponseObject ro = response.getResponseObject(method.getReturnType()); if (ro.isException) { if (ro.result instanceof Exception) { throw (Exception) ro.result; } throw new WrappedRemoteException(ro.result); } return ro.result; } */ List<Object> params = futureParams != null ? futureParams.get() : Arrays.asList(os); final Message request = protocol .createRequestMessage(new Message.RequestObject(idlFunctionName, params)); final TypeToken<?> returnType = methodEntry.futureParamOfReturnType != null ? TypeToken.of(methodEntry.futureParamOfReturnType) : TypeToken.of(method.getGenericReturnType()); final ListenableFuture<Message> responseFuture = connection.performRemoteAsyncCall(request, Global.executor); if (methodEntry.futureParamOfReturnType != null) { AsyncFunction<Message, Object> f = new AsyncFunction<Message, Object>() { @Override public ListenableFuture<Object> apply(final Message response) throws Exception { return Global.executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { Message.ResponseObject ro = response.getResponseObject(returnType); if (ro.isException) { if (ro.result instanceof Exception) { throw (Exception) ro.result; } throw new WrappedRemoteException(ro.result); } return ro.result; } }); } }; return Futures.transform(responseFuture, f); } else { Message response; try { response = responseFuture.get(); } catch (Exception ex) { throw new RemoteInvocationException(ex); } Message.ResponseObject ro = response.getResponseObject(returnType); if (ro.isException) { if (ro.result instanceof Exception) { throw (Exception) ro.result; } throw new WrappedRemoteException(ro.result); } return ro.result; } } } }