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.SyntheticResultDao.java

private ListenableFuture<ResultSet> rollupOne(int rollupLevel, String agentRollupId, String syntheticMonitorId,
        long from, long to, int adjustedTTL) throws Exception {
    BoundStatement boundStatement = readResultForRollupPS.get(rollupLevel - 1).bind();
    int i = 0;//from   w w w . j  a  v a2  s.com
    boundStatement.setString(i++, agentRollupId);
    boundStatement.setString(i++, syntheticMonitorId);
    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 synthetic result table records found for"
                                + " agentRollupId={}, syntheticMonitorId={}, from={}, to={}," + " level={}",
                                agentRollupId, syntheticMonitorId, from, to, rollupLevel);
                        return Futures.immediateFuture(DummyResultSet.INSTANCE);
                    }
                    return rollupOneFromRows(rollupLevel, agentRollupId, syntheticMonitorId, to, adjustedTTL,
                            results);
                }
            });
}

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

private ListenableFuture<AbstractDocumentRepository> acquireRepositoryFor(String database, String table) {
    Identifier cacheKey = new Identifier(database, table);
    AbstractDocumentRepository repo = repoCache.get(cacheKey);

    if (repo != null) {
        return Futures.immediateFuture(repo);
    }/*from w w w . ja  v  a  2  s  .  c  om*/

    ListenableFuture<Table> futureTable = tables.read(database, table);
    return Futures.transformAsync(futureTable, new AsyncFunction<Table, AbstractDocumentRepository>() {
        @Override
        public ListenableFuture<AbstractDocumentRepository> apply(Table input) throws Exception {
            AbstractDocumentRepository repo = factory.newInstance(input);
            repoCache.put(cacheKey, repo);
            return Futures.immediateFuture(repo);
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.datastax.driver.mapping.Mapper.java

private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) {
    ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture,
            new AsyncFunction<BoundStatement, ResultSet>() {
                @Override/*from   www .jav a2  s. c  om*/
                public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception {
                    return session().executeAsync(bs);
                }
            });
    return Futures.transform(rsFuture, TO_NULL);
}

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

public synchronized SQLFuture<List<Cursor>> executeBatchShards(Context ctx,
        Iterable<? extends BoundShardQuery> queries, TabletType tabletType,
        Query.ExecuteOptions.IncludedFields includedFields) throws SQLException {
    checkCallIsAllowed("executeBatchShards");
    ExecuteBatchShardsRequest.Builder requestBuilder = ExecuteBatchShardsRequest.newBuilder()
            .addAllQueries(queries).setTabletType(tabletType).setSession(session)
            .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields));

    if (ctx.getCallerId() != null) {
        requestBuilder.setCallerId(ctx.getCallerId());
    }/*from  w  w  w  .j  a  va 2  s .  c o m*/

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

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

/**
* Execute multiple keyspace ID queries as a batch.
*
* @param asTransaction If true, automatically create a transaction (per shard) that encloses all
*        the batch queries./*from w w  w.  j  a v a2  s.c  om*/
*/
public SQLFuture<List<Cursor>> executeBatchShards(Context ctx, Iterable<? extends BoundShardQuery> queries,
        TabletType tabletType, boolean asTransaction, Query.ExecuteOptions.IncludedFields includedFields)
        throws SQLException {
    ExecuteBatchShardsRequest.Builder requestBuilder = ExecuteBatchShardsRequest.newBuilder()
            .addAllQueries(checkNotNull(queries)).setTabletType(checkNotNull(tabletType))
            .setAsTransaction(asTransaction)
            .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields));

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

    return new SQLFuture<List<Cursor>>(transformAsync(client.executeBatchShards(ctx, requestBuilder.build()),
            new AsyncFunction<ExecuteBatchShardsResponse, List<Cursor>>() {
                @Override
                public ListenableFuture<List<Cursor>> apply(ExecuteBatchShardsResponse response)
                        throws Exception {
                    Proto.checkError(response.getError());
                    return Futures.<List<Cursor>>immediateFuture(Proto.toCursorList(response.getResultsList()));
                }
            }, directExecutor()));
}

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

@Override
public Future<RpcResult<Void>> rmLogicalSwitch(RmLogicalSwitchInput input) {

    final FabricId fabricId = input.getFabricId();
    NodeId nodeid = input.getNodeId();//from  w w  w  . ja  va 2  s . c  om

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }

    final InstanceIdentifier<Node> lswIId = MdSalUtils.createNodeIId(fabricId.getValue(), nodeid);

    ReadOnlyTransaction trans = dataBroker.newReadOnlyTransaction();

    CheckedFuture<Optional<Node>, ReadFailedException> readFuture = trans.read(LogicalDatastoreType.OPERATIONAL,
            lswIId);

    return Futures.transform(readFuture, new AsyncFunction<Optional<Node>, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Optional<Node> optional) throws Exception {

            if (optional.isPresent()) {
                Node lsw = optional.get();
                fabricObj.notifyLogicSwitchRemoved(lsw);

                WriteTransaction wt = dataBroker.newWriteOnlyTransaction();
                wt.delete(LogicalDatastoreType.OPERATIONAL, lswIId);
                MdSalUtils.wrapperSubmit(wt, executor);
            }

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

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

private ListenableFuture<List<View>> getTableViews(String database, String table) {
    Identifier tableId = new Identifier(database, table);
    List<View> cachedViews = viewsByTable.get(tableId);

    if (cachedViews != null) {
        return Futures.immediateFuture(cachedViews);
    }//  w w  w . ja v  a  2s .  c  o m

    ListenableFuture<List<View>> allViews = views.readAll(database, table);
    return Futures.transformAsync(allViews, new AsyncFunction<List<View>, List<View>>() {
        @Override
        public ListenableFuture<List<View>> apply(List<View> input) {
            List<View> cachedViews = new ArrayList<>();
            cachedViews.addAll(input);
            viewsByTable.put(tableId, cachedViews);
            return Futures.immediateFuture(input);
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.trinity.foundation.display.x11.impl.XWindow.java

@Override
public ListenableFuture<Rectangle> getGeometry() {
    final int winId = getWindowId();

    final ListenableFuture<xcb_get_geometry_cookie_t> geometryRequest = this.xExecutor
            .submit(new Callable<xcb_get_geometry_cookie_t>() {
                @Override/* www. jav  a2 s . com*/
                public xcb_get_geometry_cookie_t call() {
                    LOG.debug("[winId={}] get geometry request.", winId);

                    return xcb_get_geometry(getConnectionRef(), winId);
                }
            });

    return transform(geometryRequest, new AsyncFunction<xcb_get_geometry_cookie_t, Rectangle>() {
        @Override
        public ListenableFuture<Rectangle> apply(final xcb_get_geometry_cookie_t input) {
            return getGeometryReply(input);
        }
    });
}

From source file:com.microsoftopentechnologies.intellij.helpers.o365.Office365RestAPIManager.java

@Override
public ListenableFuture<List<ServicePermissionEntry>> getO365PermissionsForApp(final String objectId)
        throws ParseException {
    return requestWithToken(new RequestCallback<List<ServicePermissionEntry>>() {
        @Override/*ww w  .  j a va2s  .co m*/
        public ListenableFuture<List<ServicePermissionEntry>> execute() throws ParseException {
            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:org.opendaylight.toaster.ToasterImpl.java

/**
 * Read the ToasterStatus and, if currently Up, try to write the status to
 * Down. If that succeeds, then we essentially have an exclusive lock and
 * can proceed to make toast./*from  w  w  w. java 2  s  .c  o m*/
 */
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
                public ListenableFuture<Void> apply(final Optional<Toaster> toasterData) throws Exception {

                    ToasterStatus toasterStatus = ToasterStatus.Up;
                    if (toasterData.isPresent()) {
                        toasterStatus = toasterData.get().getToasterStatus();
                    }

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

                    if (toasterStatus == ToasterStatus.Up) {
                        if (outOfBread()) {
                            LOG.debug("Toaster is out of bread");
                            return Futures.immediateFailedCheckedFuture(
                                    new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
                        }

                        LOG.debug("Setting Toaster status to Down");

                        // We're not currently making toast - try to update the status to Down
                        // to indicate we're going to make toast. This acts as a lock to prevent
                        // concurrent toasting.
                        tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
                        return tx.submit();
                    }

                    LOG.debug("Oops - already making toast!");

                    // Return an error since we are already making toast. This will get
                    // propagated to the commitFuture below which will interpret the null
                    // TransactionStatus in the RpcResult as an error condition.
                    return Futures.immediateFailedCheckedFuture(
                            new TransactionCommitFailedException("", makeToasterInUseError()));
                }
            });

    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            // OK to make toast
            currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
        }

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

                // Another thread is likely trying to make toast simultaneously and updated the
                // status before us. Try reading the status again - if another make toast is
                // now in progress, we should get ToasterStatus.Down and fail.

                if ((tries - 1) > 0) {
                    LOG.debug("Got OptimisticLockFailedException - trying again");

                    checkStatusAndMakeToast(input, futureResult, tries - 1);
                } else {
                    futureResult.set(RpcResultBuilder.<Void>failed()
                            .withError(ErrorType.APPLICATION, ex.getMessage()).build());
                }

            } else {

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

                // Probably already making toast.
                futureResult.set(RpcResultBuilder.<Void>failed()
                        .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());
            }
        }
    });
}