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:org.glowroot.central.repo.GaugeValueDao.java

private ListenableFuture<ResultSet> rollupOneFromChildren(int rollupLevel, String agentRollupId,
        String gaugeName, List<String> childAgentRollups, long captureTime, int adjustedTTL) {
    List<ListenableFuture<ResultSet>> futures = Lists.newArrayList();
    for (String childAgentRollup : childAgentRollups) {
        BoundStatement boundStatement = readValueForRollupFromChildPS.bind();
        int i = 0;
        boundStatement.setString(i++, childAgentRollup);
        boundStatement.setString(i++, gaugeName);
        boundStatement.setTimestamp(i++, new Date(captureTime));
        futures.add(session.executeAsync(boundStatement));
    }//from   ww  w .  j  a v a 2 s.c  o m
    return Futures.transformAsync(Futures.allAsList(futures), new AsyncFunction<List<ResultSet>, ResultSet>() {
        @Override
        public ListenableFuture<ResultSet> apply(@Nullable List<ResultSet> results) throws Exception {
            checkNotNull(results);
            List<Row> rows = Lists.newArrayList();
            for (int i = 0; i < results.size(); i++) {
                Row row = results.get(i).one();
                if (row == null) {
                    // this is unexpected since TTL for "needs rollup" records is
                    // shorter than TTL for data
                    logger.warn(
                            "no gauge value table records found for agentRollupId={},"
                                    + " gaugeName={}, captureTime={}, level={}",
                            childAgentRollups.get(i), gaugeName, captureTime, rollupLevel);
                } else {
                    rows.add(row);
                }
            }
            if (rows.isEmpty()) {
                // warning(s) already logged above
                return Futures.immediateFuture(DummyResultSet.INSTANCE);
            }
            return rollupOneFromRows(rollupLevel, agentRollupId, gaugeName, captureTime, adjustedTTL, rows);
        }
    });
}

From source file:com.microsoft.intellij.helpers.o365.Office365ManagerImpl.java

private <E extends DirectoryObject, F extends ODataEntityFetcher<E, ? extends DirectoryObjectOperations>, O extends ODataOperations> ListenableFuture<List<E>> getAllObjects(
        final ODataCollectionFetcher<E, F, O> fetcher) {

    return Futures.transform(fetcher.read(), new AsyncFunction<List<E>, List<E>>() {
        @Override/*from ww  w.j  ava2s  .c om*/
        public ListenableFuture<List<E>> apply(List<E> entities) throws Exception {
            return Futures.successfulAsList(
                    Lists.transform(entities, new Function<E, ListenableFuture<? extends E>>() {
                        @Override
                        public ListenableFuture<? extends E> apply(E e) {
                            return fetcher.getById(e.getobjectId()).read();
                        }
                    }));
        }
    });
}

From source file:io.vitess.client.VTGateConn.java

public SQLFuture<List<SplitQueryResponse.Part>> splitQuery(Context ctx, String keyspace, String query,
        @Nullable Map<String, ?> bindVars, Iterable<String> splitColumns, int splitCount,
        int numRowsPerQueryPart, Algorithm algorithm) throws SQLException {
    SplitQueryRequest.Builder requestBuilder = SplitQueryRequest.newBuilder()
            .setKeyspace(checkNotNull(keyspace)).setQuery(Proto.bindQuery(checkNotNull(query), bindVars))
            .addAllSplitColumn(splitColumns).setSplitCount(splitCount)
            .setNumRowsPerQueryPart(numRowsPerQueryPart).setAlgorithm(algorithm);
    if (ctx.getCallerId() != null) {
        requestBuilder.setCallerId(ctx.getCallerId());
    }// ww w.jav a2 s . c  o m
    return new SQLFuture<List<SplitQueryResponse.Part>>(
            transformAsync(client.splitQuery(ctx, requestBuilder.build()),
                    new AsyncFunction<SplitQueryResponse, List<SplitQueryResponse.Part>>() {
                        @Override
                        public ListenableFuture<List<SplitQueryResponse.Part>> apply(
                                SplitQueryResponse response) throws Exception {
                            return Futures.<List<SplitQueryResponse.Part>>immediateFuture(
                                    response.getSplitsList());
                        }
                    }, directExecutor()));
}

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

@Override
public Future<RpcResult<Void>> rmNodeFromFabric(RmNodeFromFabricInput input) {
    final RpcResult<Void> result = RpcResultBuilder.<Void>success().build();

    FabricId fabricId = input.getFabricId();
    final NodeRef device = input.getNodeRef();

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(new IllegalArgumentException("fabric is not exist!"));
    }// w ww  .  j  av a  2s .  com

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    // del fabric attribute
    InstanceIdentifier<DeviceNodes> devicepath = Constants.DOM_FABRICS_PATH
            .child(Node.class, new NodeKey(fabricId)).augmentation(FabricNode.class)
            .child(FabricAttribute.class).child(DeviceNodes.class, new DeviceNodesKey(device));

    trans.delete(LogicalDatastoreType.OPERATIONAL, devicepath);

    // del node attribute
    @SuppressWarnings("unchecked")
    InstanceIdentifier<Node> noderef = (InstanceIdentifier<Node>) device.getValue();
    NodeId deviceid = noderef.firstKeyOf(Node.class).getNodeId();
    TopologyId topoid = noderef.firstKeyOf(Topology.class).getTopologyId();
    InstanceIdentifier<SupportingNode> suplNodeIid = MdSalUtils.createFNodeIId(input.getFabricId())
            .child(SupportingNode.class, new SupportingNodeKey(deviceid, topoid));

    trans.delete(LogicalDatastoreType.OPERATIONAL, suplNodeIid);

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

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

        @SuppressWarnings("unchecked")
        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception {
            fabricObj.notifyDeviceRemoved((InstanceIdentifier<Node>) device.getValue());
            return Futures.immediateFuture(result);
        }
    });
}

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 d a ListenableFuture to combine
 * @param e a ListenableFuture to combine
 * @param f a ListenableFuture to combine
 * @param function the implementation of the transform
 * @return a ListenableFuture holding the result of function.apply()
 */// www .  j  a  va2 s.co  m
public static <Z, A, B, C, D, E, F> ListenableFuture<Z> asyncTransform6(ListenableFuture<A> a,
        ListenableFuture<B> b, ListenableFuture<C> c, ListenableFuture<D> d, ListenableFuture<E> e,
        ListenableFuture<F> f,
        final AsyncFunction6<Z, ? super A, ? super B, ? super C, ? super D, ? super E, ? super F> function) {
    return transform(Arrays.asList(a, b, c, d, e, f), 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),
                    (D) results.get(3), (E) results.get(4), (F) results.get(5));
        }
    });
}

From source file:com.microsoft.intellij.helpers.o365.Office365ManagerImpl.java

@Override
@NotNull//from w  ww  .j  av  a2s . c o  m
public ListenableFuture<Application> registerApplication(@NotNull final Application application) {
    return requestFutureWithToken(new RequestCallback<ListenableFuture<Application>>() {
        @Override
        public ListenableFuture<Application> execute() throws Throwable {
            // register the app and then create a service principal for the app if there isn't already one
            return Futures.transform(getDirectoryClient().getapplications().add(application),
                    new AsyncFunction<Application, Application>() {
                        @Override
                        public ListenableFuture<Application> apply(final Application application)
                                throws Exception {
                            return Futures.transform(getServicePrincipalsForApp(application),
                                    new AsyncFunction<List<ServicePrincipal>, Application>() {
                                        @Override
                                        public ListenableFuture<Application> apply(
                                                List<ServicePrincipal> servicePrincipals) throws Exception {
                                            if (servicePrincipals.size() == 0) {
                                                return createServicePrincipalForApp(application);
                                            }

                                            return Futures.immediateFuture(application);
                                        }
                                    });
                        }
                    });
        }
    });
}

From source file:io.vitess.client.VTGateConn.java

public SQLFuture<SrvKeyspace> getSrvKeyspace(Context ctx, String keyspace) throws SQLException {
    GetSrvKeyspaceRequest.Builder requestBuilder = GetSrvKeyspaceRequest.newBuilder()
            .setKeyspace(checkNotNull(keyspace));
    return new SQLFuture<SrvKeyspace>(transformAsync(client.getSrvKeyspace(ctx, requestBuilder.build()),
            new AsyncFunction<GetSrvKeyspaceResponse, SrvKeyspace>() {
                @Override//from   w ww. j a va 2s  .  co m
                public ListenableFuture<SrvKeyspace> apply(GetSrvKeyspaceResponse response) throws Exception {
                    return Futures.<SrvKeyspace>immediateFuture(response.getSrvKeyspace());
                }
            }, directExecutor()));
}

From source file:org.glowroot.central.repo.GaugeValueDao.java

private ListenableFuture<ResultSet> rollupOne(int rollupLevel, String agentRollupId, String gaugeName,
        long from, long to, int adjustedTTL) throws Exception {
    BoundStatement boundStatement = readValueForRollupPS.get(rollupLevel - 1).bind();
    int i = 0;// w  w w.ja va2 s .  co  m
    boundStatement.setString(i++, agentRollupId);
    boundStatement.setString(i++, gaugeName);
    boundStatement.setTimestamp(i++, new Date(from));
    boundStatement.setTimestamp(i++, new Date(to));
    return Futures.transformAsync(session.executeAsync(boundStatement),
            new AsyncFunction<ResultSet, ResultSet>() {
                @Override
                public ListenableFuture<ResultSet> apply(@Nullable ResultSet results) throws Exception {
                    checkNotNull(results);
                    if (results.isExhausted()) {
                        // this is unexpected since TTL for "needs rollup" records is shorter
                        // than TTL for data
                        logger.warn(
                                "no gauge value table records found for agentRollupId={},"
                                        + " gaugeName={}, from={}, to={}, level={}",
                                agentRollupId, gaugeName, from, to, rollupLevel);
                        return Futures.immediateFuture(DummyResultSet.INSTANCE);
                    }
                    return rollupOneFromRows(rollupLevel, agentRollupId, gaugeName, to, adjustedTTL, results);
                }
            });
}

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

@Override
public Future<RpcResult<CreateLogicalSwitchOutput>> createLogicalSwitch(final CreateLogicalSwitchInput input) {
    final RpcResultBuilder<CreateLogicalSwitchOutput> resultBuilder = RpcResultBuilder
            .<CreateLogicalSwitchOutput>success();
    final CreateLogicalSwitchOutputBuilder outputBuilder = new CreateLogicalSwitchOutputBuilder();

    FabricId fabricId = input.getFabricId();
    String name = input.getName();

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }/* w w w  .  j  a  va2  s  . c  o m*/

    final String uuid = UUID.randomUUID().toString();
    final NodeId newNodeId = new NodeId(name == null ? uuid : name);
    final InstanceIdentifier<Node> newRouterIId = MdSalUtils.createNodeIId(fabricId.getValue(), newNodeId);

    NodeBuilder nodeBuilder = new NodeBuilder();
    nodeBuilder.setKey(new NodeKey(newNodeId));
    nodeBuilder.setNodeId(newNodeId);

    nodeBuilder.setSupportingNode(createDefaultSuplNode(fabricId));

    LswAttributeBuilder lswAttr = new LswAttributeBuilder();
    lswAttr.setName(input.getName());
    lswAttr.setLswUuid(new Uuid(uuid));
    fabricObj.buildLogicalSwitch(newNodeId, lswAttr, input);

    LogicalSwitchAugmentBuilder lswCtx = new LogicalSwitchAugmentBuilder();
    lswCtx.setLswAttribute(lswAttr.build());

    nodeBuilder.addAugmentation(LogicalSwitchAugment.class, lswCtx.build());

    final Node lsw = nodeBuilder.build();
    WriteTransaction trans = dataBroker.newWriteOnlyTransaction();
    trans.put(LogicalDatastoreType.OPERATIONAL, newRouterIId, lsw);

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

        @Override
        public ListenableFuture<RpcResult<CreateLogicalSwitchOutput>> apply(Void submitResult)
                throws Exception {

            outputBuilder.setLswUuid(new Uuid(uuid));
            outputBuilder.setName(input.getName());
            outputBuilder.setNodeId(newNodeId);
            fabricObj.notifyLogicSwitchCreated(newNodeId, lsw);
            return Futures.immediateFuture(resultBuilder.withResult(outputBuilder.build()).build());
        }
    }, executor);
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskFactory.java

/**
 * Recursive helper method for {@link OFRpcTaskFactory#createAddFlowTask(OFRpcTaskContext, AddFlowInput, SwitchConnectionDistinguisher)}
 * and {@link OFRpcTaskFactory#createUpdateFlowTask(OFRpcTaskContext, UpdateFlowInput, SwitchConnectionDistinguisher, ReadWriteTransaction)} to chain results
 * of multiple flowmods./*  w  ww . ja  v  a  2  s. c  o  m*/
 * The next flowmod gets executed if the earlier one is successful.
 * All the flowmods should have the same xid, in-order to cross-reference
 * the notification
 * @param taskContext task context
 * @param ofFlowModInputs list of flow mod as input
 * @param index  starting index
 * @param cookie switch connection distinguisher
 * @return listenable future with update flow output
 *
 */
protected static ListenableFuture<RpcResult<UpdateFlowOutput>> chainFlowMods(
        final List<FlowModInputBuilder> ofFlowModInputs, final int index, final OFRpcTaskContext taskContext,
        final SwitchConnectionDistinguisher cookie) {

    Future<RpcResult<UpdateFlowOutput>> resultFromOFLib = createResultForFlowMod(taskContext,
            ofFlowModInputs.get(index), cookie);

    ListenableFuture<RpcResult<UpdateFlowOutput>> result = JdkFutureAdapters
            .listenInPoolThread(resultFromOFLib);

    if (ofFlowModInputs.size() > index + 1) {
        // there are more flowmods to chain
        return Futures.transform(result,
                new AsyncFunction<RpcResult<UpdateFlowOutput>, RpcResult<UpdateFlowOutput>>() {
                    @Override
                    public ListenableFuture<RpcResult<UpdateFlowOutput>> apply(
                            RpcResult<UpdateFlowOutput> input) throws Exception {
                        if (input.isSuccessful()) {
                            return chainFlowMods(ofFlowModInputs, index + 1, taskContext, cookie);
                        } else {
                            LOG.warn("Flowmod failed. Any chained flowmods are ignored. xid:{}",
                                    ofFlowModInputs.get(index).getXid());
                            return Futures.immediateFuture(input);
                        }
                    }
                });
    } else {
        return result;
    }
}