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:com.microsoft.intellij.helpers.o365.Office365ManagerImpl.java

@Override
@NotNull//from   w  ww .  j  a v  a 2  s. c  o m
public ListenableFuture<List<ServicePermissionEntry>> getO365PermissionsForApp(@NotNull final String objectId) {
    return requestFutureWithToken(new RequestCallback<ListenableFuture<List<ServicePermissionEntry>>>() {
        @Override
        public ListenableFuture<List<ServicePermissionEntry>> execute() throws Throwable {
            return Futures.transform(getApplicationByObjectId(objectId),
                    new AsyncFunction<Application, List<ServicePermissionEntry>>() {
                        @Override
                        public ListenableFuture<List<ServicePermissionEntry>> apply(Application application)
                                throws Exception {

                            final String[] filterAppIds = new String[] { ServiceAppIds.SHARE_POINT,
                                    ServiceAppIds.EXCHANGE, ServiceAppIds.AZURE_ACTIVE_DIRECTORY };

                            // build initial list of permission from the app's permissions
                            final List<ServicePermissionEntry> servicePermissions = getO365PermissionsFromResourceAccess(
                                    application.getrequiredResourceAccess(), filterAppIds);

                            // get permissions list from O365 service principals
                            return Futures.transform(getServicePrincipalsForO365(),
                                    new AsyncFunction<List<ServicePrincipal>, List<ServicePermissionEntry>>() {
                                        @Override
                                        public ListenableFuture<List<ServicePermissionEntry>> apply(
                                                List<ServicePrincipal> servicePrincipals) throws Exception {

                                            for (final ServicePrincipal servicePrincipal : servicePrincipals) {
                                                // lookup this service principal in app's list of resources; if it's not found add an entry
                                                ServicePermissionEntry servicePermissionEntry = Iterables.find(
                                                        servicePermissions,
                                                        new Predicate<ServicePermissionEntry>() {
                                                            @Override
                                                            public boolean apply(
                                                                    ServicePermissionEntry servicePermissionEntry) {
                                                                return servicePermissionEntry.getKey().getId()
                                                                        .equals(servicePrincipal.getappId());
                                                            }
                                                        }, null);

                                                if (servicePermissionEntry == null) {
                                                    servicePermissions.add(
                                                            servicePermissionEntry = new ServicePermissionEntry(
                                                                    new Office365Service(),
                                                                    new Office365PermissionList()));
                                                }

                                                Office365Service service = servicePermissionEntry.getKey();
                                                Office365PermissionList permissionList = servicePermissionEntry
                                                        .getValue();
                                                service.setId(servicePrincipal.getappId());
                                                service.setName(servicePrincipal.getdisplayName());

                                                List<OAuth2Permission> permissions = servicePrincipal
                                                        .getoauth2Permissions();
                                                for (final OAuth2Permission permission : permissions) {
                                                    // lookup permission in permissionList
                                                    Office365Permission office365Permission = Iterables.find(
                                                            permissionList,
                                                            new Predicate<Office365Permission>() {
                                                                @Override
                                                                public boolean apply(
                                                                        Office365Permission office365Permission) {
                                                                    return office365Permission.getId().equals(
                                                                            permission.getid().toString());
                                                                }
                                                            }, null);

                                                    if (office365Permission == null) {
                                                        permissionList.add(
                                                                office365Permission = new Office365Permission());
                                                        office365Permission.setEnabled(false);
                                                    }

                                                    office365Permission.setId(permission.getid().toString());
                                                    office365Permission.setName(
                                                            getPermissionDisplayName(permission.getvalue()));
                                                    office365Permission.setDescription(
                                                            permission.getuserConsentDisplayName());
                                                }
                                            }

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

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

private ListenableFuture<SyncgroupSpec> joinWithRetry(final Id listId, final int numTimes, final int limit) {
    final String debugString = (numTimes + 1) + "/" + limit + " for: " + listId;
    Log.d(TAG, "Join attempt " + debugString);
    if (numTimes + 1 == limit) { // final attempt!
        return joinListSyncgroup(listId);
    }//from w ww .  j  a  va  2s.  c  o m
    // Note: This can be easily converted to exponential backoff.
    final long startTime = System.currentTimeMillis();
    return Futures.catchingAsync(joinListSyncgroup(listId), SyncgroupJoinFailedException.class,
            new AsyncFunction<SyncgroupJoinFailedException, SyncgroupSpec>() {
                public ListenableFuture<SyncgroupSpec> apply(@Nullable SyncgroupJoinFailedException input) {
                    long failTime = System.currentTimeMillis();
                    long delay = Math.max(0, MIN_RETRY_DELAY + startTime - failTime);

                    Log.d(TAG, "Join failed. Sleeping " + debugString + " with delay " + delay);
                    return sExecutor.schedule(new Callable<SyncgroupSpec>() {

                        @Override
                        public SyncgroupSpec call() {
                            Log.d(TAG, "Sleep done. Retry " + debugString);

                            // If this errors, then we will not get another chance to
                            // see this syncgroup until the app is restarted.
                            try {
                                return joinWithRetry(listId, numTimes + 1, limit).get();
                            } catch (InterruptedException | ExecutionException e) {
                                return null;
                            }
                        }
                    }, delay, TimeUnit.MILLISECONDS);
                }
            });
}

From source file:com.google.devtools.build.lib.query2.engine.AbstractQueryEnvironment.java

@Override
public <T1, T2> QueryTaskFuture<T2> transformAsync(QueryTaskFuture<T1> future,
        final Function<T1, QueryTaskFuture<T2>> function) {
    return QueryTaskFutureImpl
            .ofDelegate(Futures.transformAsync((QueryTaskFutureImpl<T1>) future, new AsyncFunction<T1, T2>() {
                @Override/*from  w w  w  .j a v  a2  s.  co  m*/
                public ListenableFuture<T2> apply(T1 input) throws Exception {
                    return (QueryTaskFutureImpl<T2>) function.apply(input);
                }
            }, directExecutor()));
}

From source file:org.opendaylight.controller.features_service.impl.FeaturesServiceImpl.java

private void checkStatusAndInstallFeature(final InstallFeatureInput input,
        final SettableFuture<RpcResult<Void>> futureResult, final int tries) {
    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    ListenableFuture<Optional<Features>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL,
            FEATURE_SERVICE_IID);//  w w  w.  jav a  2s .com

    final ListenableFuture<Void> commitFuture = Futures.transform(readFuture,
            new AsyncFunction<Optional<Features>, Void>() {

                @Override
                public ListenableFuture<Void> apply(final Optional<Features> featuresData) throws Exception {

                    FeaturesServiceStatus featuresServiceStatus = FeaturesServiceStatus.Available;
                    if (featuresData.isPresent()) {
                        featuresServiceStatus = featuresData.get().getFeaturesServiceStatus();
                    }

                    LOG.debug("Read featuresServiceStatus status: {}", featuresServiceStatus);

                    if (featuresServiceStatus == FeaturesServiceStatus.Available) {

                        LOG.debug("Setting features service to unavailable (in use)");

                        tx.put(LogicalDatastoreType.OPERATIONAL, FEATURE_SERVICE_IID,
                                buildFeatures(FeaturesServiceStatus.Unavailable));
                        return tx.submit();
                    }

                    LOG.debug("Something went wrong while installing feature: " + input.getName());

                    return Futures.immediateFailedCheckedFuture(
                            new TransactionCommitFailedException("", makeFeaturesServiceInUseError()));
                }
            });

    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            // OK to install a feature
            currentInstallFeaturesTask.set(executor.submit(new InstallFeaturesTask(input, futureResult)));
        }

        @Override
        public void onFailure(final Throwable ex) {
            if (ex instanceof OptimisticLockFailedException) {

                // Another thread is likely trying to install a feature
                // simultaneously and updated the
                // status before us. Try reading the status again - if
                // another install is now in progress, we should
                // get FeaturesService.available and fail.

                if ((tries - 1) > 0) {
                    LOG.debug("Got OptimisticLockFailedException - trying again");
                    checkStatusAndInstallFeature(input, futureResult, tries - 1);
                } else {
                    futureResult.set(RpcResultBuilder.<Void>failed()
                            .withError(ErrorType.APPLICATION, ex.getMessage()).build());
                }

            } else {

                LOG.debug("Failed to commit FeaturesService status", ex);

                futureResult.set(RpcResultBuilder.<Void>failed()
                        .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());
            }
        }
    });
}

From source file:com.google.gerrit.server.index.ChangeBatchIndexer.java

public Result indexAll(ChangeIndex index, Iterable<Project.NameKey> projects, int numProjects, int numChanges,
        OutputStream progressOut, OutputStream verboseOut) {
    if (progressOut == null) {
        progressOut = NullOutputStream.INSTANCE;
    }//w  ww.j a va  2  s.  c  o  m
    PrintWriter verboseWriter = verboseOut != null ? new PrintWriter(verboseOut) : null;

    Stopwatch sw = Stopwatch.createStarted();
    final MultiProgressMonitor mpm = new MultiProgressMonitor(progressOut, "Reindexing changes");
    final Task projTask = mpm.beginSubTask("projects",
            numProjects >= 0 ? numProjects : MultiProgressMonitor.UNKNOWN);
    final Task doneTask = mpm.beginSubTask(null, numChanges >= 0 ? numChanges : MultiProgressMonitor.UNKNOWN);
    final Task failedTask = mpm.beginSubTask("failed", MultiProgressMonitor.UNKNOWN);

    final List<ListenableFuture<?>> futures = Lists.newArrayList();
    final AtomicBoolean ok = new AtomicBoolean(true);

    for (final Project.NameKey project : projects) {
        if (!updateMergeable(project)) {
            ok.set(false);
        }
        final ListenableFuture<?> future = executor.submit(
                reindexProject(indexerFactory.create(index), project, doneTask, failedTask, verboseWriter));
        futures.add(future);
        future.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    future.get();
                } catch (InterruptedException e) {
                    fail(project, e);
                } catch (ExecutionException e) {
                    fail(project, e);
                } catch (RuntimeException e) {
                    failAndThrow(project, e);
                } catch (Error e) {
                    failAndThrow(project, e);
                } finally {
                    projTask.update(1);
                }
            }

            private void fail(Project.NameKey project, Throwable t) {
                log.error("Failed to index project " + project, t);
                ok.set(false);
            }

            private void failAndThrow(Project.NameKey project, RuntimeException e) {
                fail(project, e);
                throw e;
            }

            private void failAndThrow(Project.NameKey project, Error e) {
                fail(project, e);
                throw e;
            }
        }, MoreExecutors.sameThreadExecutor());
    }

    try {
        mpm.waitFor(Futures.transform(Futures.successfulAsList(futures), new AsyncFunction<List<?>, Void>() {
            @Override
            public ListenableFuture<Void> apply(List<?> input) {
                mpm.end();
                return Futures.immediateFuture(null);
            }
        }));
    } catch (ExecutionException e) {
        log.error("Error in batch indexer", e);
        ok.set(false);
    }
    return new Result(sw, ok.get(), doneTask.getCount(), failedTask.getCount());
}

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

/**
 * This method calls the VTGate to execute list of queries as a batch.
 * <p>/*  w w  w.  j a v a2 s. c o  m*/
 * <p>If asTransaction is set to <code>true</code> then query execution will not change the session cookie.
 * Otherwise, query execution will become part of the session.</p>
 *
 * @param ctx           Context on user and execution deadline if any.
 * @param queryList     List of sql queries to be executed.
 * @param bindVarsList  <p>For each sql query it will provide a list of parameters to bind with.
 *                      If provided, should match the number of sql queries.</p>
 * @param asTransaction To execute query without impacting session cookie.
 * @param vtSession     Session to be used with the call.
 * @return SQL Future with List of Cursors
 * @throws SQLException If anything fails on query execution.
 */
public SQLFuture<List<CursorWithError>> executeBatch(Context ctx, List<String> queryList,
        @Nullable List<Map<String, ?>> bindVarsList, boolean asTransaction, final VTSession vtSession)
        throws SQLException {
    synchronized (this) {
        vtSession.checkCallIsAllowed("executeBatch");
        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");
        }

        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)).setSession(vtSession.getSession())
                .setAsTransaction(asTransaction);

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

        SQLFuture<List<CursorWithError>> call = 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 {
                                vtSession.setSession(response.getSession());
                                Proto.checkError(response.getError());
                                return Futures.immediateFuture(
                                        Proto.fromQueryResponsesToCursorList(response.getResultsList()));
                            }
                        }, directExecutor()));
        vtSession.setLastCall(call);
        return call;
    }
}

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

private ListenableFuture<List<Recommendation>> forecasts(
        final ListenableFuture<List<Recommendation>> recommendations) {
    return Futures.transform(recommendations, new AsyncFunction<List<Recommendation>, List<Recommendation>>() {
        @Override/*from w w w .j  a  va2  s.  c  o m*/
        public ListenableFuture<List<Recommendation>> apply(final List<Recommendation> input) throws Exception {
            final RxWebTarget<RxListenableFutureInvoker> rxForecast = RxListenableFuture.from(forecast);
            return Futures.successfulAsList(
                    Lists.transform(input, new Function<Recommendation, ListenableFuture<Recommendation>>() {
                        @Override
                        public ListenableFuture<Recommendation> apply(final Recommendation r) {
                            return Futures.transform(
                                    rxForecast.resolveTemplate("destination", r.getDestination()).request().rx()
                                            .get(Forecast.class),
                                    new AsyncFunction<Forecast, Recommendation>() {
                                        @Override
                                        public ListenableFuture<Recommendation> apply(final Forecast f)
                                                throws Exception {
                                            r.setForecast(f.getForecast());
                                            return Futures.immediateFuture(r);
                                        }
                                    });
                        }
                    }));
        }
    });
}

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

@Override
public Future<RpcResult<Void>> locateEndpoint(LocateEndpointInput input) {

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

    if (input == null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("endpoint can not be empty!"));
    }// w  w  w  .j av  a2 s. co  m
    final Uuid epId = input.getEndpointId();

    if (epId == null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("endpoint can not be empty!"));
    }
    final FabricId fabricid = input.getFabricId();
    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricid);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(new IllegalArgumentException("fabric is not exist!"));
    }

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    EndpointBuilder epBuilder = new EndpointBuilder();
    LocationBuilder locBuilder = new LocationBuilder(input.getLocation());
    epBuilder.setEndpointUuid(epId);
    epBuilder.setLocation(locBuilder.build());

    final InstanceIdentifier<Endpoint> eppath = Constants.DOM_ENDPOINTS_PATH.child(Endpoint.class,
            new EndpointKey(epId));
    trans.merge(LogicalDatastoreType.OPERATIONAL, eppath, epBuilder.build());

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

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

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void input) throws Exception {
            return Futures.immediateFuture(result);
        }
    }, executor);
}

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

public synchronized SQLFuture<Cursor> executeKeyspaceIds(Context ctx, String query, String keyspace,
        Iterable<byte[]> keyspaceIds, Map<String, ?> bindVars, TabletType tabletType,
        Query.ExecuteOptions.IncludedFields includedFields) throws SQLException {
    checkCallIsAllowed("executeKeyspaceIds");
    ExecuteKeyspaceIdsRequest.Builder requestBuilder = ExecuteKeyspaceIdsRequest.newBuilder()
            .setQuery(Proto.bindQuery(query, bindVars)).setKeyspace(keyspace)
            .addAllKeyspaceIds(Iterables.transform(keyspaceIds, Proto.BYTE_ARRAY_TO_BYTE_STRING))
            .setTabletType(tabletType).setSession(session)
            .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields));

    if (ctx.getCallerId() != null) {
        requestBuilder.setCallerId(ctx.getCallerId());
    }/* w  ww  . jav a2  s .com*/

    SQLFuture<Cursor> call = new SQLFuture<>(
            transformAsync(client.executeKeyspaceIds(ctx, requestBuilder.build()),
                    new AsyncFunction<ExecuteKeyspaceIdsResponse, Cursor>() {
                        @Override
                        public ListenableFuture<Cursor> apply(ExecuteKeyspaceIdsResponse response)
                                throws Exception {
                            setSession(response.getSession());
                            Proto.checkError(response.getError());
                            return Futures.<Cursor>immediateFuture(new SimpleCursor(response.getResult()));
                        }
                    }, directExecutor()));
    lastCall = call;
    return call;
}

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

public ListenableFuture<Document> read(String database, String table, Identifier id) {
    ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(database, table);
    return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, Document>() {
        @Override/*  w w  w .  ja va  2s  .  co  m*/
        public ListenableFuture<Document> apply(AbstractDocumentRepository input) throws Exception {
            return input.read(new Identifier(id));
        }
    }, MoreExecutors.directExecutor());
}