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:com.navercorp.redis.cluster.connection.RedisConnectionAsync.java

public static ListenableFuture<String> STRING(ListenableFuture<byte[]> f) {
    return Futures.transform(f, new Function<byte[], String>() {
        @Override/*from   www.j  a v  a2s .  co m*/
        public String apply(byte[] buf) {
            return getStatusCodeReply(buf);
        }
    });
}

From source file:org.thingsboard.server.dao.device.DeviceServiceImpl.java

@Override
public ListenableFuture<List<Device>> findDevicesByQuery(TenantId tenantId, DeviceSearchQuery query) {
    ListenableFuture<List<EntityRelation>> relations = relationService.findByQuery(tenantId,
            query.toEntitySearchQuery());
    ListenableFuture<List<Device>> devices = Futures.transformAsync(relations, r -> {
        EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection();
        List<ListenableFuture<Device>> futures = new ArrayList<>();
        for (EntityRelation relation : r) {
            EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom();
            if (entityId.getEntityType() == EntityType.DEVICE) {
                futures.add(findDeviceByIdAsync(tenantId, new DeviceId(entityId.getId())));
            }/*from  w w  w.  jav  a 2  s  . co  m*/
        }
        return Futures.successfulAsList(futures);
    });

    devices = Futures.transform(devices, new Function<List<Device>, List<Device>>() {
        @Nullable
        @Override
        public List<Device> apply(@Nullable List<Device> deviceList) {
            return deviceList == null ? Collections.emptyList()
                    : deviceList.stream().filter(device -> query.getDeviceTypes().contains(device.getType()))
                            .collect(Collectors.toList());
        }
    });

    return devices;
}

From source file:me.j360.trace.storage.elasticsearch.ElasticsearchSpanStore.java

@Override
public ListenableFuture<List<String>> getSpanNames(String serviceName) {
    if (Strings.isNullOrEmpty(serviceName)) {
        return EMPTY_LIST;
    }/* w ww  .  j a  va 2 s . c  om*/
    serviceName = serviceName.toLowerCase();
    QueryBuilder filter = boolQuery().should(termQuery("annotations.endpoint.serviceName", serviceName))
            .should(termQuery("binaryAnnotations.endpoint.serviceName", serviceName));
    SearchRequestBuilder elasticRequest = client.prepareSearch(indexNameFormatter.catchAll())
            .setTypes(ElasticsearchConstants.SPAN).setQuery(boolQuery().must(matchAllQuery()).filter(filter))
            .setSize(0).addAggregation(
                    AggregationBuilders.terms("name_agg").order(Order.term(true)).field("name").size(0));

    return Futures.transform(ElasticFutures.toGuava(elasticRequest.execute()),
            ConvertSpanNameResponse.INSTANCE);
}

From source file:org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SyncPlanPushStrategyIncrementalImpl.java

ListenableFuture<RpcResult<Void>> removeRedundantFlows(final NodeId nodeId,
        final InstanceIdentifier<FlowCapableNode> nodeIdent, final Map<TableKey, ItemSyncBox<Flow>> removalPlan,
        final SyncCrudCounters counters) {
    if (removalPlan.isEmpty()) {
        LOG.trace("no tables in operational for node: {} -> SKIPPING", nodeId.getValue());
        return RpcResultBuilder.<Void>success().buildFuture();
    }//w w  w  .  j ava 2s. c o m

    final List<ListenableFuture<RpcResult<RemoveFlowOutput>>> allResults = new ArrayList<>();
    final CrudCounts flowCrudCounts = counters.getFlowCrudCounts();

    for (final Map.Entry<TableKey, ItemSyncBox<Flow>> flowsPerTable : removalPlan.entrySet()) {
        final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
                flowsPerTable.getKey());

        // loop flows on device and check if the are configured
        for (final Flow flow : flowsPerTable.getValue().getItemsToPush()) {
            final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
                    flow.getKey());
            allResults.add(
                    JdkFutureAdapters.listenInPoolThread(flowForwarder.remove(flowIdent, flow, nodeIdent)));
            flowCrudCounts.incRemoved();
        }
    }

    final ListenableFuture<RpcResult<Void>> singleVoidResult = Futures.transform(Futures.allAsList(allResults),
            ReconcileUtil.<RemoveFlowOutput>createRpcResultCondenser("flow remove"));
    return Futures.transform(singleVoidResult,
            ReconcileUtil.chainBarrierFlush(PathUtil.digNodePath(nodeIdent), transactionService));

}

From source file:org.opendaylight.faas.fabric.general.FabricManagementAPIProvider.java

@Override
public Future<RpcResult<ComposeFabricOutput>> composeFabric(final ComposeFabricInput input) {
    ComposeFabricInputBuilder inputBuilder = new ComposeFabricInputBuilder(input);
    String msg = null;//from  w w  w  .j a v  a 2  s .  c  o m
    if ((msg = checkFabricOptions(inputBuilder)) != null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException(msg));
    }

    final FabricId fabricId = new FabricId(String.format("fabric:%d", this.genNextFabricNum()));

    final InstanceIdentifier<Node> fnodepath = MdSalUtils.createFNodeIId(fabricId);
    final InstanceIdentifier<FabricNode> fabricpath = fnodepath.augmentation(FabricNode.class);

    NodeBuilder fnodeBuilder = new NodeBuilder();
    buildNodeAttribute(fnodeBuilder, input, fabricId);

    FabricNodeBuilder fabricBuilder = new FabricNodeBuilder();
    FabricAttributeBuilder attrBuilder = new FabricAttributeBuilder();
    buildFabricAttribute(attrBuilder, inputBuilder);

    FabricRendererFactory rendererFactory = rendererMgr.getFabricRendererFactory(input.getType());
    FabricRenderer renderer = rendererFactory.composeFabric(fabricpath, attrBuilder, input);
    if (renderer == null) {
        return Futures.immediateFailedCheckedFuture(
                new RuntimeException("Can not compose fabric due the renderer return false."));
    }

    fabricBuilder.setFabricAttribute(attrBuilder.build());
    FabricInstance fabric = FabricInstanceCache.INSTANCE.addFabric(fabricId, input.getType(), renderer);
    fabric.addListener(rendererFactory.createListener(fabricpath, fabricBuilder.getFabricAttribute()));

    final FabricNode fabricNode = fabricBuilder.build();
    fnodeBuilder.addAugmentation(FabricNode.class, fabricNode);

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    trans.put(LogicalDatastoreType.OPERATIONAL, fnodepath, fnodeBuilder.build(), true);
    trans.put(LogicalDatastoreType.CONFIGURATION, fnodepath, fnodeBuilder.build(), true);
    trans.put(LogicalDatastoreType.OPERATIONAL, MdSalUtils.createTopoIId(fabricId.getValue()),
            MdSalUtils.newTopo(fabricId.getValue()));

    CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit();

    return Futures.transform(future, (AsyncFunction<Void, RpcResult<ComposeFabricOutput>>) submitResult -> {
        RpcResultBuilder<ComposeFabricOutput> resultBuilder = RpcResultBuilder.<ComposeFabricOutput>success();
        ComposeFabricOutputBuilder outputBuilder = new ComposeFabricOutputBuilder();
        outputBuilder.setFabricId(fabricId);

        FabricInstanceCache.INSTANCE.retrieveFabric(fabricId).notifyFabricCreated(fabricNode);
        return Futures.immediateFuture(resultBuilder.withResult(outputBuilder.build()).build());
    });
}

From source file:org.opendaylight.groupbasedpolicy.endpoint.EndpointRpcRegistry.java

@Override
public Future<RpcResult<Void>> registerL3PrefixEndpoint(RegisterL3PrefixEndpointInput input) {

    if (input.getL3Context() == null) {
        return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
                .withError(ErrorType.RPC, "L3 Prefix Endpoint must have L3Context.").build());
    }/* w  w  w  . j av  a2  s  .c  om*/
    if (input.getIpPrefix() == null) {
        return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
                .withError(ErrorType.RPC, "L3 Prefix Endpoint must have ip-prefix.").build());
    }

    if (input.getTenant() == null) {
        return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
                .withError(ErrorType.RPC, "L3 Prefix Endpoint must have tenant.").build());
    }

    WriteTransaction t = dataProvider.newWriteOnlyTransaction();

    long timestamp = System.currentTimeMillis();

    // TODO: Convert IPPrefix into it's IPv4/IPv6 canonical form.
    // See org.apache.commons.net.util.SubnetUtils.SubnetInfo

    EndpointL3PrefixKey epL3PrefixKey = new EndpointL3PrefixKey(input.getIpPrefix(), input.getL3Context());

    EndpointL3Prefix epL3Prefix = buildL3PrefixEndpoint(input).setTimestamp(timestamp).build();
    InstanceIdentifier<EndpointL3Prefix> iid_l3prefix = InstanceIdentifier.builder(Endpoints.class)
            .child(EndpointL3Prefix.class, epL3PrefixKey).build();
    t.put(LogicalDatastoreType.OPERATIONAL, iid_l3prefix, epL3Prefix);

    ListenableFuture<Void> r = t.submit();
    return Futures.transform(r, futureTrans);
}

From source file:org.opendaylight.netconf.topology.impl.NetconfNodeManagerCallback.java

@Nonnull
@Override/*from   ww w . jav  a2  s  .  c  o  m*/
public ListenableFuture<Node> onNodeCreated(@Nonnull final NodeId nodeId, @Nonnull final Node configNode) {
    cachedContext = TypedActor.context();
    this.nodeId = nodeId.getValue();
    this.currentConfig = configNode;
    // set initial state before anything happens
    this.currentOperationalNode = getInitialState(nodeId, configNode);

    // connect magic, send config into the netconf pipeline through topo dispatcher
    final ListenableFuture<NetconfDeviceCapabilities> connectionFuture = topologyDispatcher.connectNode(nodeId,
            configNode);

    Futures.addCallback(connectionFuture, new FutureCallback<NetconfDeviceCapabilities>() {
        @Override
        public void onSuccess(@Nullable NetconfDeviceCapabilities result) {
            connectionStatusregistration = topologyDispatcher.registerConnectionStatusListener(nodeId,
                    nodeManager);
            sessionListener = topologyDispatcher.registerNetconfClientSessionListener(nodeId,
                    NetconfNodeManagerCallback.this);
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("Connection to device failed", t);
        }
    });

    final NetconfNode netconfNode = configNode.getAugmentation(NetconfNode.class);

    // transform future result into state that gets written into datastore
    return Futures.transform(connectionFuture, new Function<NetconfDeviceCapabilities, Node>() {
        @Nullable
        @Override
        public Node apply(NetconfDeviceCapabilities input) {
            // build state data
            currentOperationalNode = new NodeBuilder().setNodeId(nodeId)
                    .addAugmentation(NetconfNode.class, new NetconfNodeBuilder()
                            .setConnectionStatus(
                                    ConnectionStatus.Connected)
                            .setClusteredConnectionStatus(new ClusteredConnectionStatusBuilder()
                                    .setNodeStatus(Collections.singletonList(new NodeStatusBuilder()
                                            .setNode(clusterExtension.selfAddress().toString())
                                            .setStatus(Status.Connected).build()))
                                    .build())
                            .setHost(netconfNode.getHost()).setPort(netconfNode.getPort())
                            .setAvailableCapabilities(new AvailableCapabilitiesBuilder()
                                    .setAvailableCapability(new ArrayList<String>()).build())
                            .setUnavailableCapabilities(new UnavailableCapabilitiesBuilder()
                                    .setUnavailableCapability(new ArrayList<UnavailableCapability>()).build())
                            .build())
                    .build();
            return currentOperationalNode;
        }
    });
}

From source file:com.datastax.driver.mapping.Mapper.java

private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) {
    ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture,
            new AsyncFunction<BoundStatement, ResultSet>() {
                @Override//w w w.  j av  a2 s  .  co m
                public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception {
                    return session().executeAsync(bs);
                }
            });
    return Futures.transform(rsFuture, TO_NULL);
}

From source file:com.navercorp.redis.cluster.connection.RedisConnectionAsync.java

public static ListenableFuture<byte[]> BYTE(ListenableFuture<byte[]> f) {
    return Futures.transform(f, new Function<byte[], byte[]>() {
        @Override//from  w  w  w. j a  v a2s.  co  m
        public byte[] apply(byte[] buf) {
            return getBinaryBulkReply(buf);
        }
    });
}