Example usage for com.google.common.util.concurrent Futures transform

List of usage examples for com.google.common.util.concurrent Futures transform

Introduction

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

Prototype

public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
        Function<? super I, ? extends O> function) 

Source Link

Document

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future .

Usage

From source file:net.oneandone.troilus.MutationQuery.java

protected ListenableFuture<Statement> mergeStatements(ListenableFuture<Statement> statementFuture,
        ListenableFuture<ImmutableSet<Statement>> cascadingStatmentsFuture) {
    ListenableFuture<ImmutableSet<Statement>> statementsFuture = ListenableFutures
            .join(cascadingStatmentsFuture, statementFuture, getExecutor());

    Function<ImmutableSet<Statement>, Statement> statementsBatcher = new Function<ImmutableSet<Statement>, Statement>() {

        public Statement apply(ImmutableSet<Statement> statements) {
            BatchStatement batchStatement = new BatchStatement(Type.LOGGED);
            for (Statement statement : statements) {
                batchStatement.add(statement);
            }//from  w  ww. jav a 2s.c om
            return batchStatement;
        };
    };
    return Futures.transform(statementsFuture, statementsBatcher);
}

From source file:org.thingsboard.server.dao.nosql.CassandraAbstractModelDao.java

protected ListenableFuture<List<D>> findListByStatementAsync(TenantId tenantId, Statement statement) {
    if (statement != null) {
        statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
        ResultSetFuture resultSetFuture = executeAsyncRead(tenantId, statement);
        return Futures.transform(resultSetFuture, new Function<ResultSet, List<D>>() {
            @Nullable/*  w ww  . jav a 2 s. c  om*/
            @Override
            public List<D> apply(@Nullable ResultSet resultSet) {
                Result<E> result = getMapper().map(resultSet);
                if (result != null) {
                    List<E> entities = result.all();
                    return DaoUtil.convertDataList(entities);
                } else {
                    return Collections.emptyList();
                }
            }
        });
    }
    return Futures.immediateFuture(Collections.emptyList());
}

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.legacy.sharded.adapter.ShardedDOMDataBrokerDelegatingWriteTransaction.java

@Override
public ListenableFuture<RpcResult<TransactionStatus>> commit() {
    return Futures.transform(submit(),
            (AsyncFunction<Void, RpcResult<TransactionStatus>>) input -> SUCCESS_FUTURE);
}

From source file:org.thingsboard.rule.engine.metadata.TbEntityGetAttrNode.java

private ListenableFuture<List<KvEntry>> getAttributesAsync(TbContext ctx, EntityId entityId) {
    ListenableFuture<List<AttributeKvEntry>> latest = ctx.getAttributesService().find(ctx.getTenantId(),
            entityId, SERVER_SCOPE, config.getAttrMapping().keySet());
    return Futures.transform(latest, l -> l.stream().map(i -> (KvEntry) i).collect(Collectors.toList()));
}

From source file:org.opendaylight.protocol.bgp.openconfig.impl.moduleconfig.TableTypesFunction.java

@Override
public ListenableFuture<List<T>> apply(final List<AfiSafi> afiSafis) {
    final ListenableFuture<Optional<Service>> readFuture = configModuleWriter
            .readConfigService(new ServiceKey(BgpTableType.class), rTx);
    return Futures.transform(readFuture, new AsyncFunction<Optional<Service>, List<T>>() {

        @Override//from w  w w.  j  a  v a2 s . c om
        public ListenableFuture<List<T>> apply(final Optional<Service> maybeService) {
            if (maybeService.isPresent()) {
                final Service service = maybeService.get();
                final List<ListenableFuture<Optional<Module>>> modulesFuture = new ArrayList<>();
                final Map<String, String> moduleNameToService = new HashMap<>();
                for (final Instance instance : service.getInstance()) {
                    final String moduleName = OpenConfigUtil.getModuleName(instance.getProvider());
                    modulesFuture.add(configModuleWriter
                            .readModuleConfiguration(new ModuleKey(moduleName, BgpTableTypeImpl.class), rTx));
                    moduleNameToService.put(moduleName, instance.getName());
                }
                return Futures.transform(Futures.successfulAsList(modulesFuture),
                        new ModulesToLocalTablesFunction(afiSafis, moduleNameToService));
            }
            return Futures.immediateFailedFuture(
                    new IllegalStateException("No BgpTableType service present in configuration."));
        }

    });
}

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

@Override
public Future<RpcResult<java.lang.Void>> cancelToast() {
    LOG.info("cancelToast");
    final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
    final ReadWriteTransaction tx = broker.newReadWriteTransaction();
    ListenableFuture<Optional<Toaster>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, TOASTER_IID);

    //Optional<Toaster>ListenableFuture??VoidListenableFuture
    final ListenableFuture<Void> commitFuture = Futures.transform(readFuture,
            new AsyncFunction<Optional<Toaster>, Void>() {

                @Override//from ww  w . j a v  a  2  s  . co m
                public ListenableFuture<Void> apply(final Optional<Toaster> toasterData) throws Exception {
                    //?toastertasterStatus
                    ToasterStatus toasterStatus = ToasterStatus.Down;
                    if (toasterData.isPresent()) {
                        toasterStatus = toasterData.get().getToasterStatus();
                    }

                    //???Up
                    if (toasterStatus == ToasterStatus.Down) {
                        //Down?
                        LOG.info("the toaster is not running!");
                        return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("",
                                RpcResultBuilder.newWarning(ErrorType.APPLICATION, "not-in-use",
                                        "Toaster is not running", null, null, null)));
                    } else {
                        //up??down?
                        tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID,
                                new ToasterBuilder().setToasterStatus(ToasterStatus.Down).build());
                        return tx.submit();
                    }
                }
            });

    //callback
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            // data store?makeToast
            LOG.info("******Task was canceled.******");
        }

        @Override
        public void onFailure(final Throwable ex) {
            LOG.debug("Failed to commit Toaster status", ex);
        }
    });
    return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
}

From source file:org.opendaylight.yangtools.yang.model.repo.util.SchemaSourceTransformer.java

@Override
public CheckedFuture<D, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
    final CheckedFuture<S, SchemaSourceException> f = provider.getSchemaSource(sourceIdentifier, srcClass);
    return Futures.makeChecked(Futures.transform(f, function), MAPPER);
}

From source file:com.sk89q.worldguard.commands.region.MemberCommands.java

@Command(aliases = { "addmember", "addmember", "addmem",
        "am" }, usage = "<id> <members...>", flags = "nw:", desc = "Add a member to a region", min = 2)
public void addMember(CommandContext args, Actor sender) throws CommandException {
    warnAboutSaveFailures(sender);//from   w  w  w .  ja  v a  2s  .c o  m

    World world = checkWorld(args, sender, 'w'); // Get the world
    String id = args.getString(0);
    RegionManager manager = checkRegionManager(world);
    ProtectedRegion region = checkExistingRegion(manager, id, true);

    // Check permissions
    if (!getPermissionModel(sender).mayAddMembers(region)) {
        throw new CommandPermissionsException();
    }

    // Resolve members asynchronously
    DomainInputResolver resolver = new DomainInputResolver(WorldGuard.getInstance().getProfileService(),
            args.getParsedPaddedSlice(1, 0));
    resolver.setLocatorPolicy(args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_ONLY);

    // Then add it to the members
    ListenableFuture<DefaultDomain> future = Futures.transform(
            WorldGuard.getInstance().getExecutorService().submit(resolver),
            resolver.createAddAllFunction(region.getMembers()));

    AsyncCommandHelper.wrap(future, worldGuard.getSupervisor(), sender, worldGuard.getExceptionConverter())
            .formatUsing(region.getId(), world.getName())
            .registerWithSupervisor("Adding members to the region '%s' on '%s'")
            .sendMessageAfterDelay("(Please wait... querying player names...)")
            .thenRespondWith("Region '%s' updated with new members.", "Failed to add new members");
}

From source file:de.ii.xtraplatform.ogc.api.gml.parser.GMLParser.java

public void parseStream(ListenableFuture<InputStream> inputStream, String ns, String ft)
        throws ExecutionException {

    ListenableFuture<SMInputCursor> rootFuture = Futures.transform(inputStream,
            new Function<InputStream, SMInputCursor>() {
                @Override/* w  ww .j  av a  2  s.  c  o m*/
                public SMInputCursor apply(InputStream i) {
                    try {
                        return staxFactory.rootElementCursor(i).advance();
                    } catch (IllegalStateException | XMLStreamException ex) {
                        LOGGER.debug("Error parsing WFS GetFeature (IOException) {}", ex.getMessage());
                    }

                    return null;
                }
            });

    parseRoot(rootFuture, ns, ft);
}

From source file:org.apache.twill.internal.AbstractExecutionServiceController.java

@Override
public Future<? extends ServiceController> terminate() {
    stop();/*from w  ww  .  j av a  2s .co m*/

    return Futures.transform(terminationFuture, new Function<State, ServiceController>() {
        @Override
        public ServiceController apply(State input) {
            return AbstractExecutionServiceController.this;
        }
    });
}