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:dk.ilios.spanner.internal.ExperimentingSpannerRun.java

/**
 * Schedule all the trials.//from   w  w w. j  ava  2  s.c o m
 * <p>
 * <p>This method arranges all the {@link ScheduledTrial trials} to run according to their
 * scheduling criteria.  The executor instance is responsible for enforcing max parallelism.
 */
private List<ListenableFuture<Trial.Result>> scheduleTrials(List<ScheduledTrial> trials,
        final ListeningExecutorService executor) {
    List<ListenableFuture<Trial.Result>> pendingTrials = Lists.newArrayList();
    List<ScheduledTrial> serialTrials = Lists.newArrayList();
    for (final ScheduledTrial scheduledTrial : trials) {
        if (scheduledTrial.policy() == TrialSchedulingPolicy.PARALLEL) {
            pendingTrials.add(executor.submit(scheduledTrial.trialTask()));
        } else {
            serialTrials.add(scheduledTrial);
        }
    }
    // A future representing the completion of all prior tasks. Futures.successfulAsList allows us
    // to ignore failure.
    ListenableFuture<?> previous = Futures.successfulAsList(pendingTrials);
    for (final ScheduledTrial scheduledTrial : serialTrials) {
        // each of these trials can only start after all prior trials have finished, so we use
        // Futures.transform to force the sequencing.
        ListenableFuture<Trial.Result> current = Futures.transform(previous,
                new AsyncFunction<Object, Trial.Result>() {
                    @Override
                    public ListenableFuture<Trial.Result> apply(Object ignored) {
                        return executor.submit(scheduledTrial.trialTask());
                    }
                });
        pendingTrials.add(current);
        // ignore failure of the prior task.
        previous = Futures.withFallback(current, FALLBACK_TO_NULL);
    }
    return pendingTrials;
}

From source file:org.glassfish.jersey.examples.rx.agent.ListenableFutureAgentResource.java

private ListenableFuture<List<Recommendation>> calculations(
        final ListenableFuture<List<Recommendation>> recommendations) {
    return Futures.transform(recommendations, new AsyncFunction<List<Recommendation>, List<Recommendation>>() {
        @Override/*www.j ava 2s  .c  om*/
        public ListenableFuture<List<Recommendation>> apply(final List<Recommendation> input) throws Exception {
            final RxWebTarget<RxListenableFutureInvoker> rxCalculations = RxListenableFuture.from(calculation);
            return Futures.successfulAsList(
                    Lists.transform(input, new Function<Recommendation, ListenableFuture<Recommendation>>() {
                        @Override
                        public ListenableFuture<Recommendation> apply(final Recommendation r) {
                            return Futures.transform(
                                    rxCalculations.resolveTemplate("from", "Moon")
                                            .resolveTemplate("to", r.getDestination()).request().rx()
                                            .get(Calculation.class),
                                    new AsyncFunction<Calculation, Recommendation>() {
                                        @Override
                                        public ListenableFuture<Recommendation> apply(final Calculation c)
                                                throws Exception {
                                            r.setPrice(c.getPrice());
                                            return Futures.immediateFuture(r);
                                        }
                                    });
                        }
                    }));
        }
    });
}

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

public SQLFuture<Cursor> executeKeyRanges(Context ctx, String query, String keyspace,
        Iterable<? extends KeyRange> keyRanges, @Nullable Map<String, ?> bindVars, TabletType tabletType,
        Query.ExecuteOptions.IncludedFields includedFields) throws SQLException {
    ExecuteKeyRangesRequest.Builder requestBuilder = ExecuteKeyRangesRequest.newBuilder()
            .setQuery(Proto.bindQuery(checkNotNull(query), bindVars)).setKeyspace(checkNotNull(keyspace))
            .addAllKeyRanges(checkNotNull(keyRanges)).setTabletType(checkNotNull(tabletType))
            .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields));

    if (ctx.getCallerId() != null) {
        requestBuilder.setCallerId(ctx.getCallerId());
    }/*from  w ww .  j a v  a 2s . co m*/

    return new SQLFuture<Cursor>(transformAsync(client.executeKeyRanges(ctx, requestBuilder.build()),
            new AsyncFunction<ExecuteKeyRangesResponse, Cursor>() {
                @Override
                public ListenableFuture<Cursor> apply(ExecuteKeyRangesResponse response) throws Exception {
                    Proto.checkError(response.getError());
                    return Futures.<Cursor>immediateFuture(new SimpleCursor(response.getResult()));
                }
            }, directExecutor()));
}

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

public ListenableFuture<List<Document>> readIn(String database, String table, Identifier... ids) {
    ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(database, table);
    return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, List<Document>>() {
        @Override/*  www.j  a  v  a2s  .c  om*/
        public ListenableFuture<List<Document>> apply(AbstractDocumentRepository input) throws Exception {
            return input.readIn(ids);
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.opendaylight.faas.fabrics.vxlan.adapters.ovs.providers.FabricDeviceManager.java

@Override
public Future<RpcResult<Void>> addToVxlanFabric(final AddToVxlanFabricInput input) {
    Preconditions.checkNotNull(input);/*from  ww w  . java  2  s  . c o  m*/
    Preconditions.checkNotNull(input.getNodeId());
    Preconditions.checkNotNull(input.getFabricId());

    final RpcResult<Void> result = RpcResultBuilder.<Void>success().build();

    @SuppressWarnings("unchecked")
    final InstanceIdentifier<Node> deviceIId = (InstanceIdentifier<Node>) input.getNodeId();
    final FabricId fabricId = new FabricId(input.getFabricId());

    final Node bridgeNode = OvsSouthboundUtils.getOvsdbBridgeNode(deviceIId, databroker);

    Preconditions.checkNotNull(bridgeNode);

    if (!OvsSouthboundUtils.addVxlanTunnelPort(bridgeNode, databroker)) {
        LOG.error("can not create tunnel port!");
        return Futures.immediateFailedFuture(new RuntimeException("can not create tunnel port"));
    }

    if (!OvsSouthboundUtils.addVxlanGpeTunnelPort(bridgeNode, databroker)) {
        LOG.error("can not create tunnel port!");
        return Futures.immediateFailedFuture(new RuntimeException("can not create nsh tunnel port"));
    }

    FabricCapableDeviceBuilder deviceBuilder = new FabricCapableDeviceBuilder();
    AttributesBuilder attributesBuilder = new AttributesBuilder();

    attributesBuilder.setFabricId(input.getFabricId());

    InstanceIdentifier<Node> fabricpath = Constants.DOM_FABRICS_PATH.child(Node.class,
            new NodeKey(input.getFabricId()));
    attributesBuilder.setFabricRef(new NodeRef(fabricpath));

    deviceBuilder.setAttributes(attributesBuilder.build());

    @SuppressWarnings("unchecked")
    final InstanceIdentifier<FabricCapableDevice> path = ((InstanceIdentifier<Node>) input.getNodeId())
            .augmentation(FabricCapableDevice.class);

    WriteTransaction wt = databroker.newWriteOnlyTransaction();
    wt.merge(LogicalDatastoreType.OPERATIONAL, path, deviceBuilder.build(), true);
    addTp2Fabric(wt, bridgeNode, deviceIId, fabricId);

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

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

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void input) throws Exception {
            renderers.put(deviceIId, new DeviceRenderer(executor, databroker, deviceIId, bridgeNode, fabricId));

            return Futures.immediateFuture(result);
        }
    }, executor);

}

From source file:zipkin.storage.cassandra.CassandraSpanStore.java

/**
 * This fans out into a potentially large amount of requests related to the amount of annotations
 * queried. The returned future will fail if any of the inputs fail.
 *
 * <p>When {@link QueryRequest#serviceName service name} is unset, service names will be
 * fetched eagerly, implying an additional query.
 *///from w  w  w  . ja  v a2 s .c o m
@Override
public ListenableFuture<List<List<Span>>> getTraces(final QueryRequest request) {
    // Over fetch on indexes as they don't return distinct (trace id, timestamp) rows.
    final int traceIndexFetchSize = request.limit * indexFetchMultiplier;
    ListenableFuture<Map<Long, Long>> traceIdToTimestamp;
    if (request.spanName != null) {
        traceIdToTimestamp = getTraceIdsBySpanName(request.serviceName, request.spanName, request.endTs * 1000,
                request.lookback * 1000, traceIndexFetchSize);
    } else if (request.serviceName != null) {
        traceIdToTimestamp = getTraceIdsByServiceNames(Collections.singletonList(request.serviceName),
                request.endTs * 1000, request.lookback * 1000, traceIndexFetchSize);
    } else {
        checkArgument(selectTraceIdsByServiceNames != null,
                "getTraces without serviceName requires Cassandra 2.2 or later");
        traceIdToTimestamp = transform(getServiceNames(), new AsyncFunction<List<String>, Map<Long, Long>>() {
            @Override
            public ListenableFuture<Map<Long, Long>> apply(List<String> serviceNames) {
                return getTraceIdsByServiceNames(serviceNames, request.endTs * 1000, request.lookback * 1000,
                        traceIndexFetchSize);
            }
        });
    }

    List<String> annotationKeys = CassandraUtil.annotationKeys(request);

    ListenableFuture<Set<Long>> traceIds;
    if (annotationKeys.isEmpty()) {
        // Simplest case is when there is no annotation query. Limit is valid since there's no AND
        // query that could reduce the results returned to less than the limit.
        traceIds = Futures.transform(traceIdToTimestamp, CassandraUtil.keyset());
    } else {
        // While a valid port of the scala cassandra span store (from zipkin 1.35), there is a fault.
        // each annotation key is an intersection, meaning we likely return < traceIndexFetchSize.
        List<ListenableFuture<Map<Long, Long>>> futureKeySetsToIntersect = new ArrayList<>();
        futureKeySetsToIntersect.add(traceIdToTimestamp);
        for (String annotationKey : annotationKeys) {
            futureKeySetsToIntersect.add(getTraceIdsByAnnotation(annotationKey, request.endTs * 1000,
                    request.lookback * 1000, traceIndexFetchSize));
        }
        // We achieve the AND goal, by intersecting each of the key sets.
        traceIds = Futures.transform(allAsList(futureKeySetsToIntersect), CassandraUtil.intersectKeySets());
    }
    return transform(traceIds, new AsyncFunction<Set<Long>, List<List<Span>>>() {
        @Override
        public ListenableFuture<List<List<Span>>> apply(Set<Long> traceIds) {
            traceIds = ImmutableSet.copyOf(Iterators.limit(traceIds.iterator(), request.limit));
            return transform(getSpansByTraceIds(traceIds, maxTraceCols),
                    new Function<List<Span>, List<List<Span>>>() {
                        @Override
                        public List<List<Span>> apply(List<Span> input) {
                            // Indexes only contain Span.traceId, so our matches are imprecise on Span.traceIdHigh
                            return FluentIterable.from(GroupByTraceId.apply(input, strictTraceId, true))
                                    .filter(new Predicate<List<Span>>() {
                                        @Override
                                        public boolean apply(List<Span> input) {
                                            return input.get(0).traceIdHigh == 0 || request.test(input);
                                        }
                                    }).toList();
                        }
                    });
        }

        @Override
        public String toString() {
            return "getSpansByTraceIds";
        }
    });
}

From source file:org.opendaylight.groupbasedpolicy.renderer.ofoverlay.PolicyManager.java

/**
 * @param  tableIDs - IDs of tables to delete
 * @return ListenableFuture<Void> - which will be filled when clearing is done
 *///  w w  w . j  a v a  2  s . c o  m
private ListenableFuture<Void> removeUnusedTables(final List<Short> tableIDs) {
    List<ListenableFuture<Void>> checkList = new ArrayList<>();
    final ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
    for (Short tableId : tableIDs) {
        for (NodeId nodeId : switchManager.getReadySwitches()) {
            final InstanceIdentifier<Table> tablePath = FlowUtils.createTablePath(nodeId, tableId);
            checkList.add(deleteTableIfExists(rwTx, tablePath));
        }
    }
    ListenableFuture<List<Void>> allAsListFuture = Futures.allAsList(checkList);
    return Futures.transform(allAsListFuture, new AsyncFunction<List<Void>, Void>() {

        @Override
        public ListenableFuture<Void> apply(List<Void> readyToSubmit) {
            return rwTx.submit();
        }
    });
}

From source file:com.google.caliper.runner.ExperimentingCaliperRun.java

/**
 * Schedule all the trials./*from  w  ww.j  av a  2  s  . c  om*/
 *
 * <p>This method arranges all the {@link ScheduledTrial trials} to run according to their
 * scheduling criteria.  The executor instance is responsible for enforcing max parallelism.
 */
private List<ListenableFuture<TrialResult>> scheduleTrials(List<ScheduledTrial> trials,
        final ListeningExecutorService executor) {
    List<ListenableFuture<TrialResult>> pendingTrials = Lists.newArrayList();
    List<ScheduledTrial> serialTrials = Lists.newArrayList();
    for (final ScheduledTrial scheduledTrial : trials) {
        if (scheduledTrial.policy() == TrialSchedulingPolicy.PARALLEL) {
            pendingTrials.add(executor.submit(scheduledTrial.trialTask()));
        } else {
            serialTrials.add(scheduledTrial);
        }
    }
    // A future representing the completion of all prior tasks. Futures.successfulAsList allows us
    // to ignore failure.
    ListenableFuture<?> previous = Futures.successfulAsList(pendingTrials);
    for (final ScheduledTrial scheduledTrial : serialTrials) {
        // each of these trials can only start after all prior trials have finished, so we use
        // Futures.transform to force the sequencing.
        ListenableFuture<TrialResult> current = Futures.transform(previous,
                new AsyncFunction<Object, TrialResult>() {
                    @Override
                    public ListenableFuture<TrialResult> apply(Object ignored) {
                        return executor.submit(scheduledTrial.trialTask());
                    }
                });
        pendingTrials.add(current);
        // ignore failure of the prior task.
        previous = Futures.withFallback(current, FALLBACK_TO_NULL);
    }
    return pendingTrials;
}

From source file:com.orangerhymelabs.helenus.cassandra.document.historical.HistoricalDocumentRepository.java

public ListenableFuture<HistoricalDocument> upsert(HistoricalDocument entity) {
    ListenableFuture<ResultSet> future = submitUpsert(entity);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, HistoricalDocument>() {
        @Override/*  ww  w  .ja  v a 2s  .c o m*/
        public ListenableFuture<HistoricalDocument> apply(ResultSet result) throws Exception {
            if (result.wasApplied()) {
                return Futures.immediateFuture(entity);
            }

            //TODO: This doesn't provide any informational value... what should it be?
            return Futures.immediateFailedFuture(new StorageException(String
                    .format("Table %s failed to store document: %s", table.toDbTable(), entity.toString())));
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.opendaylight.toaster.impl.ToasterProvider.java

private void checkStatusAndMakeToast(final MakeToastInput input,
        final SettableFuture<RpcResult<Void>> futureResult, final int tries) {
    LOG.info("checkStatusAndMakeToast");
    final ReadWriteTransaction tx = dataService.newReadWriteTransaction();
    ListenableFuture<Optional<Toaster>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, TOASTER_IID);
    final ListenableFuture<Void> commitFuture = Futures.transform(readFuture,
            new AsyncFunction<Optional<Toaster>, Void>() {
                @Override//from  w  w w .j  ava 2 s  . c o m
                public ListenableFuture<Void> apply(final Optional<Toaster> toasterData) throws Exception {
                    Toaster.ToasterStatus toasterStatus = Toaster.ToasterStatus.Up;
                    if (toasterData.isPresent()) {
                        toasterStatus = toasterData.get().getToasterStatus();
                    }
                    LOG.debug("Read toaster status: {}", toasterStatus);
                    if (toasterStatus == Toaster.ToasterStatus.Up) {
                        if (outOfBread()) {
                            LOG.debug("Toaster is out of bread");
                            return Futures.immediateFailedCheckedFuture(
                                    new TransactionCommitFailedException("", makeToasterOutOBreadError()));
                        }
                        LOG.debug("Setting Toaster status to Down");
                        tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID,
                                buildToaster(Toaster.ToasterStatus.Down));
                        return tx.submit();
                    }
                    LOG.debug("Oops - already making toast!");
                    return Futures.immediateFailedCheckedFuture(
                            new TransactionCommitFailedException("", makeToasterInUseError()));
                }
            });
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
        }

        @Override
        public void onFailure(final Throwable ex) {
            if (ex instanceof OptimisticLockFailedException) {
                if ((tries - 1) > 0) {
                    LOG.debug("Got OptimisticLockFailedException - try again");
                    checkStatusAndMakeToast(input, futureResult, tries - 1);
                } else {
                    futureResult.set(RpcResultBuilder.<Void>failed()
                            .withError(RpcError.ErrorType.APPLICATION, ex.getMessage()).build());
                }
            } else {
                LOG.debug("Failed to commit Toaster status", ex);
                futureResult.set(RpcResultBuilder.<Void>failed()
                        .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());
            }
        }
    });
}