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.mdsal.dom.broker.ShardedDOMReadTransactionAdapter.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    checkRunning();/*from w  w w.  jav  a2 s  .  c  o  m*/
    LOG.debug("{}: Invoking exists at {}:{}", txIdentifier, store, path);
    final Function<Optional<NormalizedNode<?, ?>>, Boolean> transform = optionalNode -> optionalNode.isPresent()
            ? Boolean.TRUE
            : Boolean.FALSE;
    final ListenableFuture<Boolean> existsResult = Futures.transform(read(store, path), transform);
    return Futures.makeChecked(existsResult, ReadFailedException.MAPPER);
}

From source file:co.cask.cdap.explore.client.AbstractExploreClient.java

@Override
public ListenableFuture<Void> enableExploreStream(final Id.Stream stream) {
    ListenableFuture<ExploreExecutionResult> futureResults = getResultsFuture(new HandleProducer() {
        @Override/*www .  j  a  va 2s  .com*/
        public QueryHandle getHandle() throws ExploreException, SQLException {
            return doEnableExploreStream(stream);
        }
    });

    // Exceptions will be thrown in case of an error in the futureHandle
    return Futures.transform(futureResults, Functions.<Void>constant(null));
}

From source file:org.thingsboard.server.dao.alarm.AlarmDaoImpl.java

@Override
public ListenableFuture<List<AlarmInfo>> findAlarms(AlarmQuery query) {
    log.trace("Try to find alarms by entity [{}], searchStatus [{}], status [{}] and pageLink [{}]",
            query.getAffectedEntityId(), query.getSearchStatus(), query.getStatus(), query.getPageLink());
    EntityId affectedEntity = query.getAffectedEntityId();
    String searchStatusName;//from w w w .ja  va  2s .  co  m
    if (query.getSearchStatus() == null && query.getStatus() == null) {
        searchStatusName = AlarmSearchStatus.ANY.name();
    } else if (query.getSearchStatus() != null) {
        searchStatusName = query.getSearchStatus().name();
    } else {
        searchStatusName = query.getStatus().name();
    }
    String relationType = BaseAlarmService.ALARM_RELATION_PREFIX + searchStatusName;
    ListenableFuture<List<EntityRelation>> relations = relationDao.findRelations(affectedEntity, relationType,
            RelationTypeGroup.ALARM, EntityType.ALARM, query.getPageLink());
    return Futures.transform(relations, (AsyncFunction<List<EntityRelation>, List<AlarmInfo>>) input -> {
        List<ListenableFuture<AlarmInfo>> alarmFutures = new ArrayList<>(input.size());
        for (EntityRelation relation : input) {
            alarmFutures.add(Futures.transform(findAlarmByIdAsync(relation.getTo().getId()),
                    (Function<Alarm, AlarmInfo>) alarm1 -> new AlarmInfo(alarm1)));
        }
        return Futures.successfulAsList(alarmFutures);
    });
}

From source file:io.airlift.discovery.client.CachingServiceSelector.java

@Override
public ListenableFuture<List<ServiceDescriptor>> refresh() {
    ServiceDescriptors oldDescriptors = this.serviceDescriptors.get();

    ListenableFuture<ServiceDescriptors> future;
    if (oldDescriptors == null) {
        future = lookupClient.getServices(type, pool);
    } else {//  www . ja  v a  2s.  c o m
        future = lookupClient.refreshServices(oldDescriptors);
    }

    future = chainedCallback(future, new FutureCallback<ServiceDescriptors>() {
        @Override
        public void onSuccess(ServiceDescriptors newDescriptors) {
            serviceDescriptors.set(newDescriptors);
            errorBackOff.success();

            Duration delay = newDescriptors.getMaxAge();
            if (delay == null) {
                delay = DEFAULT_DELAY;
            }
            scheduleRefresh(delay);
        }

        @Override
        public void onFailure(Throwable t) {
            Duration duration = errorBackOff.failed(t);
            scheduleRefresh(duration);
        }
    }, executor);

    return Futures.transform(future, new Function<ServiceDescriptors, List<ServiceDescriptor>>() {
        @Override
        public List<ServiceDescriptor> apply(ServiceDescriptors serviceDescriptors) {
            return serviceDescriptors.getServiceDescriptors();
        }
    });
}

From source file:org.grouplens.lenskit.eval.script.ConfigMethodInvoker.java

Object finishBuilder(final Builder<?> builder) {
    List<ListenableFuture<?>> deps = getDeps(builder);
    clearDeps(builder);//www  .  j a va 2 s.  c  o  m
    if (deps.isEmpty()) {
        return builder.build();
    } else {
        ListenableFuture<List<Object>> ideps = Futures.allAsList(deps);
        if (ideps.isDone()) {
            return builder.build();
        } else {
            return Futures.transform(ideps, new Function<List<Object>, Object>() {
                @Nullable
                @Override
                public Object apply(@Nullable List<Object> input) {
                    return builder.build();
                }
            });
        }
    }
}

From source file:org.opendaylight.bgpcep.pcep.tunnel.provider.UpdateTunnelInstructionExecutor.java

@Override
protected ListenableFuture<OperationResult> invokeOperation() {
    final InstanceIdentifier<Topology> tii = TopologyProgrammingUtil.topologyForInput(this.updateTunnelInput);
    final InstanceIdentifier<Link> lii = TunnelProgrammingUtil.linkIdentifier(tii, this.updateTunnelInput);
    try (final ReadOnlyTransaction t = this.dataProvider.newReadOnlyTransaction()) {
        final Link link;
        final Node node;
        try {/*from   www  .j  a  v a 2s  .com*/
            // The link has to exist
            link = t.read(LogicalDatastoreType.OPERATIONAL, lii).checkedGet().get();
            // The source node has to exist
            node = TunelProgrammingUtil.sourceNode(t, tii, link).get();
        } catch (IllegalStateException | ReadFailedException e) {
            LOG.debug("Link or node does not exist.", e);
            return TunelProgrammingUtil.RESULT;
        }
        return Futures.transform(
                (ListenableFuture<RpcResult<UpdateLspOutput>>) this.topologyService
                        .updateLsp(buildUpdateInput(link, node)),
                new Function<RpcResult<UpdateLspOutput>, OperationResult>() {
                    @Override
                    public OperationResult apply(final RpcResult<UpdateLspOutput> input) {
                        return input.getResult();
                    }
                });
    }
}

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();//from w  ww.j ava2 s  .  c o  m

    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:org.opendaylight.distributed.tx.it.provider.datawriter.DtxDataStoreAsyncWriter.java

/**
 * Asynchronously write to datastore with distributed-tx API
 *//*ww  w .j  a  v  a  2  s .c o  m*/
@Override
public void writeData() {
    int putsPerTx = input.getPutsPerTx();
    int counter = 0;

    InstanceIdentifier<DatastoreTestData> nodeId = InstanceIdentifier.create(DatastoreTestData.class);
    List<ListenableFuture<Void>> putFutures = new ArrayList<ListenableFuture<Void>>((int) putsPerTx);
    List<OuterList> outerLists = dataStoreListBuilder.buildOuterList();

    if (input.getOperation() == OperationType.DELETE) {
        dataStoreListBuilder.buildTestInnerList();
    }

    dtx = dTxProvider.newTx(nodesMap);
    startTime = System.nanoTime();
    for (OuterList outerList : outerLists) {
        for (InnerList innerList : outerList.getInnerList()) {
            InstanceIdentifier<InnerList> innerIid = InstanceIdentifier.create(DatastoreTestData.class)
                    .child(OuterList.class, outerList.getKey()).child(InnerList.class, innerList.getKey());

            CheckedFuture<Void, DTxException> writeFuture;
            if (input.getOperation() == OperationType.PUT) {
                writeFuture = dtx.putAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, innerList, nodeId);
            } else if (input.getOperation() == OperationType.MERGE) {
                writeFuture = dtx.mergeAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, innerList, nodeId);
            } else {
                writeFuture = dtx.deleteAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, nodeId);
            }
            putFutures.add(writeFuture);
            counter++;

            if (counter == putsPerTx) {
                //Aggregate all the put futures into a listenable future which can ensure all asynchronous writes has been finished
                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(nodesMap);
                putFutures = new ArrayList<ListenableFuture<Void>>(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.mdsal.binding.dom.adapter.RpcServiceAdapter.java

private static ListenableFuture<RpcResult<?>> transformFuture(final SchemaPath rpc,
        final ListenableFuture<DOMRpcResult> domFuture, final BindingNormalizedNodeCodecRegistry codec) {
    return Futures.transform(domFuture, new Function<DOMRpcResult, RpcResult<?>>() {
        @Override/*from w  w w.  j av  a  2s  .  c om*/
        public RpcResult<?> apply(final DOMRpcResult input) {
            final NormalizedNode<?, ?> domData = input.getResult();
            final DataObject bindingResult;
            if (domData != null) {
                final SchemaPath rpcOutput = rpc.createChild(QName.create(rpc.getLastComponent(), "output"));
                bindingResult = codec.fromNormalizedNodeRpcData(rpcOutput, (ContainerNode) domData);
            } else {
                bindingResult = null;
            }
            return RpcResult.class.cast(RpcResultBuilder.success(bindingResult).build());
        }
    });
}

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

private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readOperationalData(
        final YangInstanceIdentifier path) {
    final ListenableFuture<DOMRpcResult> configCandidate = netconfOps.get(loggingCallback,
            Optional.fromNullable(path));

    // Find data node and normalize its content
    final ListenableFuture<Optional<NormalizedNode<?, ?>>> transformedFuture = Futures
            .transform(configCandidate, new Function<DOMRpcResult, Optional<NormalizedNode<?, ?>>>() {
                @Override/*from  ww  w  .j av a 2  s  .co  m*/
                public Optional<NormalizedNode<?, ?>> apply(final DOMRpcResult result) {
                    checkReadSuccess(result, path);

                    final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataNode = findDataNode(
                            result);
                    return NormalizedNodes.findNode(dataNode, path.getPathArguments());
                }
            });

    return MappingCheckedFuture.create(transformedFuture, ReadFailedException.MAPPER);
}