Example usage for com.google.common.util.concurrent AsyncFunction AsyncFunction

List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction

Introduction

In this page you can find the example usage for com.google.common.util.concurrent AsyncFunction AsyncFunction.

Prototype

AsyncFunction

Source Link

Usage

From source file:io.v.todos.persistence.syncbase.SyncbaseTodoList.java

public ListenableFuture<Void> updateListTimestamp() {
    ListenableFuture<io.v.todos.model.ListSpec> get = mList.get(getVContext(), LIST_METADATA_ROW_NAME,
            ListSpec.class);
    return Futures.transformAsync(get, new AsyncFunction<Object, Void>() {
        @Override//  www.j  a  v a 2s .c  om
        public ListenableFuture<Void> apply(Object oldValue) throws Exception {
            ListSpec listSpec = (ListSpec) oldValue;
            listSpec.setUpdatedAt(System.currentTimeMillis());
            return mList.put(getVContext(), LIST_METADATA_ROW_NAME, listSpec);
        }
    });
}

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. j  a  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:io.vitess.client.VTGateTx.java

public SQLFuture<List<CursorWithError>> executeBatch(Context ctx, List<String> queryList,
        @Nullable List<Map<String, ?>> bindVarsList, TabletType tabletType,
        Query.ExecuteOptions.IncludedFields includedFields) throws SQLException {
    List<Query.BoundQuery> queries = new ArrayList<>();

    if (null != bindVarsList && bindVarsList.size() != queryList.size()) {
        throw new SQLDataException("Size of SQL Query list does not match the bind variables list");
    }// w w w. ja  v  a2s  .c o  m

    for (int i = 0; i < queryList.size(); ++i) {
        queries.add(i, Proto.bindQuery(checkNotNull(queryList.get(i)),
                bindVarsList == null ? null : bindVarsList.get(i)));
    }

    Vtgate.ExecuteBatchRequest.Builder requestBuilder = Vtgate.ExecuteBatchRequest.newBuilder()
            .addAllQueries(checkNotNull(queries)).setKeyspaceShard(keyspace)
            .setTabletType(checkNotNull(tabletType)).setSession(session)
            .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields));

    if (ctx.getCallerId() != null) {
        requestBuilder.setCallerId(ctx.getCallerId());
    }

    return new SQLFuture<>(transformAsync(client.executeBatch(ctx, requestBuilder.build()),
            new AsyncFunction<Vtgate.ExecuteBatchResponse, List<CursorWithError>>() {
                @Override
                public ListenableFuture<List<CursorWithError>> apply(Vtgate.ExecuteBatchResponse response)
                        throws Exception {
                    setSession(response.getSession());
                    Proto.checkError(response.getError());
                    return Futures
                            .immediateFuture(Proto.fromQueryResponsesToCursorList(response.getResultsList()));
                }
            }, directExecutor()));
}

From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentService.java

public ListenableFuture<Boolean> exists(String database, String table, Identifier id) {
    ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(database, table);
    return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, Boolean>() {
        @Override//from w w w.j  a v a2s .c  o  m
        public ListenableFuture<Boolean> apply(AbstractDocumentRepository input) throws Exception {
            return input.exists(new Identifier(id));
        }
    }, MoreExecutors.directExecutor());
}

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/*  w  w  w  . j  a  va  2 s . 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);
    }
}

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/* ww w  .  jav  a 2  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:io.vitess.client.VTGateConn.java

public SQLFuture<List<CursorWithError>> executeBatch(Context ctx, List<String> queryList,
        @Nullable List<Map<String, ?>> bindVarsList, TabletType tabletType, boolean asTransaction,
        Query.ExecuteOptions.IncludedFields includedFields) throws SQLException {
    List<Query.BoundQuery> queries = new ArrayList<>();

    if (null != bindVarsList && bindVarsList.size() != queryList.size()) {
        throw new SQLDataException("Size of SQL Query list does not match the bind variables list");
    }//from   w  ww .  java 2 s.co m

    for (int i = 0; i < queryList.size(); ++i) {
        queries.add(i, Proto.bindQuery(checkNotNull(queryList.get(i)),
                bindVarsList == null ? null : bindVarsList.get(i)));
    }

    Vtgate.ExecuteBatchRequest.Builder requestBuilder = Vtgate.ExecuteBatchRequest.newBuilder()
            .addAllQueries(checkNotNull(queries)).setKeyspaceShard(keyspace)
            .setTabletType(checkNotNull(tabletType)).setAsTransaction(asTransaction)
            .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields));

    if (ctx.getCallerId() != null) {
        requestBuilder.setCallerId(ctx.getCallerId());
    }

    return new SQLFuture<>(transformAsync(client.executeBatch(ctx, requestBuilder.build()),
            new AsyncFunction<Vtgate.ExecuteBatchResponse, List<CursorWithError>>() {
                @Override
                public ListenableFuture<List<CursorWithError>> apply(Vtgate.ExecuteBatchResponse response)
                        throws Exception {
                    Proto.checkError(response.getError());
                    return Futures
                            .immediateFuture(Proto.fromQueryResponsesToCursorList(response.getResultsList()));
                }
            }, directExecutor()));
}

From source file:com.spotify.futures.FuturesExtra.java

/**
 * Transform the input futures into a single future, using the provided
 * transform function. The transformation follows the same semantics as as
 * {@link Futures#transform(ListenableFuture, AsyncFunction)} and the input
 * futures are combined using {@link Futures#allAsList}.
 *
 * @param a a ListenableFuture to combine
 * @param b a ListenableFuture to combine
 * @param c a ListenableFuture to combine
 * @param function the implementation of the transform
 * @return a ListenableFuture holding the result of function.apply()
 *//* w w  w. j a  va 2s .com*/
public static <Z, A, B, C> ListenableFuture<Z> asyncTransform3(ListenableFuture<A> a, ListenableFuture<B> b,
        ListenableFuture<C> c, final AsyncFunction3<Z, ? super A, ? super B, ? super C> function) {
    return transform(Arrays.asList(a, b, c), new AsyncFunction<List<Object>, Z>() {
        @Override
        public ListenableFuture<Z> apply(List<Object> results) throws Exception {
            return function.apply((A) results.get(0), (B) results.get(1), (C) results.get(2));
        }
    });
}

From source file:zipkin.storage.elasticsearch.NativeClient.java

@Override
protected BulkSpanIndexer bulkSpanIndexer() {
    return new SpanBytesBulkSpanIndexer() {
        final List<IndexRequestBuilder> indexRequests = new LinkedList<>();
        final Set<String> indices = new LinkedHashSet<>();

        @Override/*from   ww w.j  ava  2  s. c om*/
        protected void add(String index, byte[] spanBytes) {
            indexRequests.add(client.prepareIndex(index, SPAN).setSource(spanBytes));
            if (flushOnWrites)
                indices.add(index);
        }

        // Creates a bulk request when there is more than one span to store
        @Override
        public ListenableFuture<Void> execute() {
            ListenableFuture<?> future;
            if (indexRequests.size() == 1) {
                future = toGuava(indexRequests.get(0).execute());
            } else {
                BulkRequestBuilder request = client.prepareBulk();
                for (IndexRequestBuilder span : indexRequests) {
                    request.add(span);
                }
                future = toGuava(request.execute());
            }
            if (!indices.isEmpty()) {
                future = transform(future, new AsyncFunction() {
                    @Override
                    public ListenableFuture apply(Object input) {
                        return toGuava(client.admin().indices()
                                .prepareFlush(indices.toArray(new String[indices.size()])).execute());
                    }
                });
            }

            return transform(future, TO_VOID);
        }
    };
}

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

@Override
public Future<RpcResult<Void>> rmGateway(RmGatewayInput input) {
    FabricId fabricId = input.getFabricId();
    final NodeId routerId = input.getLogicalRouter();
    IpAddress gwIp = input.getIpAddress();

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }//from ww  w .ja v  a  2 s  . co m

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    TpId tpOnRouter = null;
    NodeId lswId = null;
    TpId tpOnSwitch = null;
    Link link = null;

    tpOnRouter = new TpId(String.valueOf(gwIp.getValue()));
    if (tpOnRouter != null) {
        link = findGWLink(trans, fabricId, tpOnRouter, routerId);
        trans.delete(LogicalDatastoreType.OPERATIONAL, MdSalUtils.createLinkIId(fabricId, link.getLinkId()));
    }
    if (link != null) {
        lswId = link.getDestination().getDestNode();
        tpOnSwitch = link.getDestination().getDestTp();
        trans.delete(LogicalDatastoreType.OPERATIONAL,
                MdSalUtils.createLogicPortIId(fabricId, lswId, tpOnSwitch));
    }

    final NodeId flswid = lswId == null ? null : lswId;

    trans.delete(LogicalDatastoreType.OPERATIONAL,
            MdSalUtils.createLogicPortIId(fabricId, routerId, tpOnRouter));

    return Futures.transform(trans.submit(), new AsyncFunction<Void, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception {
            fabricObj.notifyGatewayRemoved(flswid, routerId);

            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }
    }, executor);
}