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.google.gapid.views.CommandTree.java

private ListenableFuture<TreePath> getTreePath(CommandStream.Node node, List<Object> path,
        Iterator<Long> indices) {
    ListenableFuture<CommandStream.Node> load = models.commands.load(node);
    if (!indices.hasNext()) {
        TreePath result = new TreePath(path.toArray());
        // Ensure the last node in the path is loaded.
        return (load == null) ? Futures.immediateFuture(result) : Futures.transform(load, ignored -> result);
    }//from  w ww.j  a  v  a 2s.  c o  m
    return (load == null) ? getTreePathForLoadedNode(node, path, indices)
            : Futures.transformAsync(load, loaded -> getTreePathForLoadedNode(loaded, path, indices));
}

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

@Override
public Future<RpcResult<Void>> registerEndpoint(RegisterEndpointInput input) {
    long timestamp = System.currentTimeMillis();

    // TODO: Replicate RPC feedback implemented in L3Prefix register for
    // unmet requirements.
    WriteTransaction t = dataProvider.newWriteOnlyTransaction();

    if (input.getL2Context() != null && input.getMacAddress() != null) {
        Endpoint ep = buildEndpoint(input).setTimestamp(timestamp).build();

        EndpointKey key = new EndpointKey(ep.getL2Context(), ep.getMacAddress());
        t.put(LogicalDatastoreType.OPERATIONAL, IidFactory.endpointIid(key), ep, true);
    }//  w  ww  .  jav a 2  s .  c o m
    if (input.getL3Address() != null) {
        for (L3Address l3addr : input.getL3Address()) {
            EndpointL3Key key3 = new EndpointL3Key(l3addr.getIpAddress(), l3addr.getL3Context());
            EndpointL3 ep3 = buildEndpointL3(input).setIpAddress(key3.getIpAddress())
                    .setL3Context(key3.getL3Context()).setTimestamp(timestamp).build();
            t.put(LogicalDatastoreType.OPERATIONAL, IidFactory.l3EndpointIid(key3), ep3, true);
        }
    }
    ListenableFuture<Void> r = t.submit();
    return Futures.transform(r, futureTrans);
}

From source file:com.google.cloud.bigtable.grpc.BigtableDataGrpcClient.java

/** {@inheritDoc} */
@Override//from  w  w w . j  av a  2 s  .  c  o m
public ListenableFuture<List<Row>> readRowsAsync(ReadRowsRequest request) {
    return Futures.transform(getStreamingFuture(request, readRowsAsync, request.getTableName()),
            ROW_TRANSFORMER);
}

From source file:org.opendaylight.bgpcep.pcep.topology.provider.Stateful07TopologySessionListener.java

private ListenableFuture<OperationResult> triggerLspSyncronization(final TriggerSyncArgs input) {
    LOG.trace("Trigger Lsp Resynchronization {}", input);

    // Make sure the LSP exists
    final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
    final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
    if (f == null) {
        return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
    }//from w ww .j av a  2  s. co m
    return Futures.transform(f, new ResyncLspFunction(input));
}

From source file:io.v.v23.rpc.ReflectInvoker.java

private static ListenableFuture<Object[]> prepareReply(final ServerMethod m, Object resultFuture) {
    if (resultFuture == null) {
        return Futures.immediateFailedFuture(new VException(String
                .format("Server method %s returned NULL ListenableFuture.", m.getReflectMethod().getName())));
    }/*from  w  w  w  . j  av a  2  s.c  om*/
    if (!(resultFuture instanceof ListenableFuture)) {
        return Futures.immediateFailedFuture(new VException(String
                .format("Server method %s didn't return a ListenableFuture.", m.getReflectMethod().getName())));
    }
    return Futures.transform((ListenableFuture<?>) resultFuture, new AsyncFunction<Object, Object[]>() {
        @Override
        public ListenableFuture<Object[]> apply(Object result) throws Exception {
            Type[] resultTypes = m.getResultTypes();
            switch (resultTypes.length) {
            case 0:
                return Futures.immediateFuture(new Object[0]); // Void
            case 1:
                return Futures.immediateFuture(new Object[] { result });
            default: { // Multiple return values.
                Class<?> returnType = (Class<?>) m.getReturnType();
                Field[] fields = returnType.getFields();
                Object[] reply = new Object[fields.length];
                for (int i = 0; i < fields.length; i++) {
                    try {
                        reply[i] = result != null ? fields[i].get(result) : null;
                    } catch (IllegalAccessException e) {
                        throw new VException("Couldn't get field: " + e.getMessage());
                    }
                }
                return Futures.immediateFuture(reply);
            }
            }
        }
    });
}

From source file:org.thingsboard.server.dao.asset.BaseAssetService.java

@Override
public ListenableFuture<List<EntitySubtype>> findAssetTypesByTenantId(TenantId tenantId) {
    log.trace("Executing findAssetTypesByTenantId, tenantId [{}]", tenantId);
    validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
    ListenableFuture<List<EntitySubtype>> tenantAssetTypes = assetDao
            .findTenantAssetTypesAsync(tenantId.getId());
    return Futures.transform(tenantAssetTypes, assetTypes -> {
        assetTypes.sort(Comparator.comparing(EntitySubtype::getType));
        return assetTypes;
    });//from   w  w w  . j  av a 2s .c om
}

From source file:com.spotify.asyncdatastoreclient.Datastore.java

/**
 * Execute a allocate ids statement./*from  w  w  w .  j  a  va2  s  .c o  m*/
 *
 * @param statement the statement to execute.
 * @return the result of the allocate ids request.
 */
public ListenableFuture<AllocateIdsResult> executeAsync(final AllocateIds statement) {
    final ListenableFuture<Response> httpResponse;
    try {
        final DatastoreV1.AllocateIdsRequest.Builder request = DatastoreV1.AllocateIdsRequest.newBuilder()
                .addAllKey(statement.getPb(config.getNamespace()));
        final ProtoHttpContent payload = new ProtoHttpContent(request.build());
        httpResponse = ListenableFutureAdapter.asGuavaFuture(prepareRequest("allocateIds", payload).execute());
    } catch (final Exception e) {
        return Futures.immediateFailedFuture(new DatastoreException(e));
    }
    return Futures.transform(httpResponse, (Response response) -> {
        if (!isSuccessful(response.getStatusCode())) {
            throw new DatastoreException(response.getStatusCode(), response.getResponseBody());
        }
        final DatastoreV1.AllocateIdsResponse allocate = DatastoreV1.AllocateIdsResponse
                .parseFrom(streamResponse(response));
        return Futures.immediateFuture(AllocateIdsResult.build(allocate));
    });
}

From source file:org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils.java

private static ListenableFuture<List<RpcResult<List<MultipartReply>>>> createDeviceFeaturesForOF13(
        final DeviceContext deviceContext, final DeviceState deviceState,
        final boolean switchFeaturesMandatory) {

    final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = getNodeStaticInfo(
            MultipartType.OFPMPDESC, deviceContext, deviceState.getNodeInstanceIdentifier(),
            deviceState.getVersion());//from ww w  .  ja va 2  s .c om

    //first process description reply, write data to DS and write consequent data if successful
    return Futures.transform(replyDesc,
            new AsyncFunction<RpcResult<List<MultipartReply>>, List<RpcResult<List<MultipartReply>>>>() {
                @Override
                public ListenableFuture<List<RpcResult<List<MultipartReply>>>> apply(
                        final RpcResult<List<MultipartReply>> rpcResult) throws Exception {

                    translateAndWriteReply(MultipartType.OFPMPDESC, deviceContext,
                            deviceState.getNodeInstanceIdentifier(), rpcResult.getResult());

                    final ListenableFuture<RpcResult<List<MultipartReply>>> replyMeterFeature = getNodeStaticInfo(
                            MultipartType.OFPMPMETERFEATURES, deviceContext,
                            deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());

                    createSuccessProcessingCallback(MultipartType.OFPMPMETERFEATURES, deviceContext,
                            deviceState.getNodeInstanceIdentifier(), replyMeterFeature);

                    final ListenableFuture<RpcResult<List<MultipartReply>>> replyGroupFeatures = getNodeStaticInfo(
                            MultipartType.OFPMPGROUPFEATURES, deviceContext,
                            deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
                    createSuccessProcessingCallback(MultipartType.OFPMPGROUPFEATURES, deviceContext,
                            deviceState.getNodeInstanceIdentifier(), replyGroupFeatures);

                    final ListenableFuture<RpcResult<List<MultipartReply>>> replyTableFeatures = getNodeStaticInfo(
                            MultipartType.OFPMPTABLEFEATURES, deviceContext,
                            deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
                    createSuccessProcessingCallback(MultipartType.OFPMPTABLEFEATURES, deviceContext,
                            deviceState.getNodeInstanceIdentifier(), replyTableFeatures);

                    final ListenableFuture<RpcResult<List<MultipartReply>>> replyPortDescription = getNodeStaticInfo(
                            MultipartType.OFPMPPORTDESC, deviceContext, deviceState.getNodeInstanceIdentifier(),
                            deviceState.getVersion());
                    createSuccessProcessingCallback(MultipartType.OFPMPPORTDESC, deviceContext,
                            deviceState.getNodeInstanceIdentifier(), replyPortDescription);
                    if (switchFeaturesMandatory) {
                        return Futures.allAsList(Arrays.asList(replyMeterFeature, replyGroupFeatures,
                                replyTableFeatures, replyPortDescription));
                    } else {
                        return Futures.successfulAsList(Arrays.asList(replyMeterFeature, replyGroupFeatures,
                                replyTableFeatures, replyPortDescription));
                    }
                }
            });

}

From source file:org.opendaylight.vpnservice.natservice.internal.VpnFloatingIpHandler.java

void cleanupFibEntries(final BigInteger dpnId, final String vpnName, final String externalIp,
        final long label) {
    //Remove Prefix from BGP
    String rd = NatUtil.getVpnRd(dataBroker, vpnName);
    removePrefixFromBGP(rd, externalIp + "/32");

    //Remove custom FIB routes

    //Future<RpcResult<java.lang.Void>> removeFibEntry(RemoveFibEntryInput input);
    RemoveFibEntryInput input = new RemoveFibEntryInputBuilder().setVpnName(vpnName).setSourceDpid(dpnId)
            .setIpAddress(externalIp).setServiceId(label).build();
    Future<RpcResult<Void>> future = fibService.removeFibEntry(input);

    ListenableFuture<RpcResult<Void>> labelFuture = Futures.transform(
            JdkFutureAdapters.listenInPoolThread(future),
            new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {

                @Override/*from  ww w  .j av  a2  s  . c  o m*/
                public ListenableFuture<RpcResult<Void>> apply(RpcResult<Void> result) throws Exception {
                    //Release label
                    if (result.isSuccessful()) {
                        removeTunnelTableEntry(dpnId, label);
                        removeLFibTableEntry(dpnId, label);
                        RemoveVpnLabelInput labelInput = new RemoveVpnLabelInputBuilder().setVpnName(vpnName)
                                .setIpPrefix(externalIp).build();
                        Future<RpcResult<Void>> labelFuture = vpnService.removeVpnLabel(labelInput);
                        return JdkFutureAdapters.listenInPoolThread(labelFuture);
                    } else {
                        String errMsg = String.format(
                                "RPC call to remove custom FIB entries on dpn %s for prefix %s Failed - %s",
                                dpnId, externalIp, result.getErrors());
                        LOG.error(errMsg);
                        return Futures.immediateFailedFuture(new RuntimeException(errMsg));
                    }
                }
            });

    Futures.addCallback(labelFuture, new FutureCallback<RpcResult<Void>>() {

        @Override
        public void onFailure(Throwable error) {
            LOG.error("Error in removing the label or custom fib entries", error);
        }

        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                LOG.debug("Successfully removed the label for the prefix {} from VPN {}", externalIp, vpnName);
            } else {
                LOG.error("Error in removing the label for prefix {} from VPN {}, {}", externalIp, vpnName,
                        result.getErrors());
            }
        }
    });
}

From source file:org.opendaylight.didm.identification.impl.DeviceIdentificationManager.java

private void setDeviceType(String deviceType, InstanceIdentifier<Node> path) {
    final InstanceIdentifier<DeviceType> deviceTypePath = path.augmentation(DeviceType.class);
    final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();

    tx.merge(LogicalDatastoreType.OPERATIONAL, deviceTypePath,
            new DeviceTypeBuilder().setDeviceType(deviceType).build());

    LOG.debug("Setting node '{}' device type to '{}'", path, deviceType);
    CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();

    // chain the result of the write with the expected rpc future.
    ListenableFuture<RpcResult<Void>> transform = Futures.transform(submitFuture,
            new AsyncFunction<Void, RpcResult<Void>>() {
                @Override/*from   ww  w.  j a  v  a 2s. c  o  m*/
                public ListenableFuture<RpcResult<Void>> apply(Void result) throws Exception {
                    return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
                }
            });

    // add a callback so we can log any exceptions on the write attempt
    Futures.addCallback(submitFuture, new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("Failed to write DeviceType to: {}", deviceTypePath, t);
        }
    });

    try {
        transform.get();
    } catch (Exception e) {
        LOG.error("Failed to write DeviceType to path: {}", path, e);
    }
}