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:com.sk89q.worldguard.bukkit.commands.region.MemberCommands.java

@Command(aliases = { "addowner", "addowner",
        "ao" }, usage = "<id> <owners...>", flags = "nw:", desc = "Add an owner to a region", min = 2)
public void addOwner(CommandContext args, CommandSender sender) throws CommandException {
    warnAboutSaveFailures(sender);//from w w w.  java2s  .c om

    World world = checkWorld(args, sender, 'w'); // Get the world

    Player player = null;
    LocalPlayer localPlayer = null;
    if (sender instanceof Player) {
        player = (Player) sender;
        localPlayer = plugin.wrapPlayer(player);
    }

    String id = args.getString(0);

    RegionManager manager = checkRegionManager(plugin, world);
    ProtectedRegion region = checkExistingRegion(manager, id, true);

    id = region.getId();

    Boolean flag = region.getFlag(DefaultFlag.BUYABLE);
    DefaultDomain owners = region.getOwners();

    if (localPlayer != null) {
        if (flag != null && flag && owners != null && owners.size() == 0) {
            // TODO: Move this to an event
            if (!plugin.hasPermission(player, "worldguard.region.unlimited")) {
                int maxRegionCount = plugin.getGlobalStateManager().get(world).getMaxRegionCount(player);
                if (maxRegionCount >= 0 && manager.getRegionCountOfPlayer(localPlayer) >= maxRegionCount) {
                    throw new CommandException("You already own the maximum allowed amount of regions.");
                }
            }
            plugin.checkPermission(sender, "worldguard.region.addowner.unclaimed." + id.toLowerCase());
        } else {
            // Check permissions
            if (!getPermissionModel(sender).mayAddOwners(region)) {
                throw new CommandPermissionsException();
            }
        }
    }

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

    // Then add it to the owners
    ListenableFuture<DefaultDomain> future = Futures.transform(plugin.getExecutorService().submit(resolver),
            resolver.createAddAllFunction(region.getOwners()));

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

From source file:org.apache.beam.runners.core.fn.SdkHarnessClient.java

/**
 * Start a new bundle for the given {@link
 * org.apache.beam.fn.v1.BeamFnApi.ProcessBundleDescriptor} identifier.
 *
 * <p>The input channels for the returned {@link ActiveBundle} are derived from the
 * instructions in the {@link org.apache.beam.fn.v1.BeamFnApi.ProcessBundleDescriptor}.
 *///w  w w  .  j a  v a2 s  .c  o m
public ActiveBundle newBundle(String processBundleDescriptorId) {
    String bundleId = idGenerator.getId();

    // TODO: acquire an input receiver from appropriate FnDataService
    FnDataReceiver dataReceiver = new FnDataReceiver() {
        @Override
        public void accept(Object input) throws Exception {
            throw new UnsupportedOperationException("Placeholder FnDataReceiver cannot accept data.");
        }

        @Override
        public void close() throws IOException {
            // noop
        }
    };

    ListenableFuture<BeamFnApi.InstructionResponse> genericResponse = fnApiControlClient
            .handle(BeamFnApi.InstructionRequest.newBuilder().setProcessBundle(BeamFnApi.ProcessBundleRequest
                    .newBuilder().setProcessBundleDescriptorReference(processBundleDescriptorId)).build());

    ListenableFuture<BeamFnApi.ProcessBundleResponse> specificResponse = Futures.transform(genericResponse,
            new Function<BeamFnApi.InstructionResponse, BeamFnApi.ProcessBundleResponse>() {
                @Override
                public BeamFnApi.ProcessBundleResponse apply(BeamFnApi.InstructionResponse input) {
                    return input.getProcessBundle();
                }
            });

    return ActiveBundle.create(bundleId, specificResponse, dataReceiver);
}

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

/**
 * @param task of rpc//from   ww  w  . j a  v  a2 s . c o m
 * @param originalResult original result
 * @param <T> R
 * @param <I> I
 * @return chained result with barrier
 */
public static <T extends TransactionAware, I extends DataContainer> ListenableFuture<RpcResult<T>> chainFutureBarrier(
        final OFRpcTask<I, RpcResult<T>> task, final ListenableFuture<RpcResult<T>> originalResult) {

    ListenableFuture<RpcResult<T>> chainResult = originalResult;
    if (MoreObjects.firstNonNull(task.isBarrier(), Boolean.FALSE)) {

        chainResult = Futures.transform(originalResult, new AsyncFunction<RpcResult<T>, RpcResult<T>>() {

            @Override
            public ListenableFuture<RpcResult<T>> apply(final RpcResult<T> input) throws Exception {
                if (input.isSuccessful()) {
                    RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrierRpc = TaskUtil
                            .sendBarrier(task.getSession(), task.getCookie(), task.getMessageService());
                    ListenableFuture<RpcResult<T>> barrierTxResult = Futures.transform(
                            sendBarrierRpc.getOutput(),
                            transformBarrierToTransactionAware(input, sendBarrierRpc.getInput()));
                    return barrierTxResult;
                } else {
                    return Futures.immediateFuture(input);
                }
            }

        });
    }

    return chainResult;
}

From source file:org.opendaylight.controller.sal.connect.netconf.sal.tx.WriteCandidateTx.java

@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
    final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(),
            new Function<RpcResult<TransactionStatus>, Void>() {
                @Override/*from  w  w  w .j  a  v  a 2  s .  co m*/
                public Void apply(final RpcResult<TransactionStatus> input) {
                    return null;
                }
            });

    return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
        @Override
        public TransactionCommitFailedException apply(final Exception input) {
            return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed",
                    input);
        }
    });
}

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

Object invoke(Object[] args) {

    BoundStatement bs = statement.bind();

    for (int i = 0; i < args.length; i++) {
        paramMappers[i].setValue(bs, args[i]);
    }//from   ww  w.  j  a  v a2s  .com

    if (consistency != null)
        bs.setConsistencyLevel(consistency);
    if (fetchSize > 0)
        bs.setFetchSize(fetchSize);
    if (tracing)
        bs.enableTracing();
    if (idempotent != null)
        bs.setIdempotent(idempotent);

    if (returnStatement)
        return bs;

    if (async) {
        ListenableFuture<ResultSet> future = session.executeAsync(bs);
        if (returnMapper == null)
            return future;

        return mapOne ? Futures.transform(future, returnMapper.mapOneFunctionWithoutAliases)
                : Futures.transform(future, returnMapper.mapAllFunctionWithoutAliases);
    } else {
        ResultSet rs = session.execute(bs);
        if (returnMapper == null)
            return rs;

        Result<?> result = returnMapper.map(rs);
        return mapOne ? result.one() : result;
    }
}

From source file:co.cask.cdap.explore.client.AbstractExploreClient.java

@Override
public ListenableFuture<Void> addPartition(final Id.DatasetInstance datasetInstance, final PartitionKey key,
        final String path) {
    ListenableFuture<ExploreExecutionResult> futureResults = getResultsFuture(new HandleProducer() {
        @Override//from  w  w w  . jav  a  2  s.c o m
        public QueryHandle getHandle() throws ExploreException, SQLException {
            return doAddPartition(datasetInstance, key, path);
        }
    });

    // Exceptions will be thrown in case of an error in the futureHandle
    return Futures.transform(futureResults, Functions.<Void>constant(null));
}

From source file:io.v.x.jni.test.fortune.FortuneServerImpl.java

@Override
public ListenableFuture<MultipleStreamingGetOut> multipleStreamingGet(final VContext context, ServerCall call,
        final ServerStream<String, Boolean> stream) {
    final SettableFuture<MultipleStreamingGetOut> future = SettableFuture.create();
    final AtomicInteger numSent = new AtomicInteger(0);
    Futures.addCallback(InputChannels.withCallback(stream, new InputChannelCallback<Boolean>() {
        @Override//from w ww .j  a v  a 2s .  c  o  m
        public ListenableFuture<Void> onNext(Boolean result) {
            if (lastAddedFortune == null) {
                return Futures.immediateFailedFuture(new NoFortunesException(context));
            }
            return Futures.transform(stream.send(lastAddedFortune), new Function<Void, Void>() {
                @Override
                public Void apply(Void input) {
                    numSent.incrementAndGet();
                    return null;
                }
            });
        }
    }), new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            MultipleStreamingGetOut ret = new MultipleStreamingGetOut();
            ret.total = numSent.get();
            ret.another = numSent.get();
            future.set(ret);
        }

        @Override
        public void onFailure(Throwable t) {
            future.setException(t);
        }
    });
    return future;
}

From source file:org.opendaylight.openflowplugin.impl.services.SalMetersBatchServiceImpl.java

@Override
public Future<RpcResult<UpdateMetersBatchOutput>> updateMetersBatch(final UpdateMetersBatchInput input) {
    final List<BatchUpdateMeters> batchUpdateMeters = input.getBatchUpdateMeters();
    LOG.trace("Updating meters @ {} : {}", PathUtil.extractNodeId(input.getNode()), batchUpdateMeters.size());

    final ArrayList<ListenableFuture<RpcResult<UpdateMeterOutput>>> resultsLot = new ArrayList<>();
    for (BatchUpdateMeters batchMeter : batchUpdateMeters) {
        final UpdateMeterInput updateMeterInput = new UpdateMeterInputBuilder(input)
                .setOriginalMeter(new OriginalMeterBuilder(batchMeter.getOriginalBatchedMeter()).build())
                .setUpdatedMeter(new UpdatedMeterBuilder(batchMeter.getUpdatedBatchedMeter()).build())
                .setMeterRef(createMeterRef(input.getNode(), batchMeter)).setNode(input.getNode()).build();
        resultsLot.add(JdkFutureAdapters.listenInPoolThread(salMeterService.updateMeter(updateMeterInput)));
    }/*from   www . j a va2  s . c o m*/

    final Iterable<Meter> meters = Iterables.transform(batchUpdateMeters,
            new Function<BatchUpdateMeters, Meter>() {
                @Nullable
                @Override
                public Meter apply(@Nullable final BatchUpdateMeters input) {
                    return input.getUpdatedBatchedMeter();
                }
            });

    final ListenableFuture<RpcResult<List<BatchFailedMetersOutput>>> commonResult = Futures.transform(
            Futures.allAsList(resultsLot),
            MeterUtil.<UpdateMeterOutput>createCumulativeFunction(meters, batchUpdateMeters.size()));

    ListenableFuture<RpcResult<UpdateMetersBatchOutput>> updateMetersBulkFuture = Futures
            .transform(commonResult, MeterUtil.METER_UPDATE_TRANSFORM);

    if (input.isBarrierAfter()) {
        updateMetersBulkFuture = BarrierUtil.chainBarrier(updateMetersBulkFuture, input.getNode(),
                transactionService, MeterUtil.METER_UPDATE_COMPOSING_TRANSFORM);
    }

    return updateMetersBulkFuture;
}

From source file:org.opendaylight.openflowplugin.impl.services.SalGroupsBatchServiceImpl.java

@Override
public Future<RpcResult<UpdateGroupsBatchOutput>> updateGroupsBatch(final UpdateGroupsBatchInput input) {
    final List<BatchUpdateGroups> batchUpdateGroups = input.getBatchUpdateGroups();
    LOG.trace("Updating groups @ {} : {}", PathUtil.extractNodeId(input.getNode()), batchUpdateGroups.size());

    final ArrayList<ListenableFuture<RpcResult<UpdateGroupOutput>>> resultsLot = new ArrayList<>();
    for (BatchUpdateGroups batchGroup : batchUpdateGroups) {
        final UpdateGroupInput updateGroupInput = new UpdateGroupInputBuilder(input)
                .setOriginalGroup(new OriginalGroupBuilder(batchGroup.getOriginalBatchedGroup()).build())
                .setUpdatedGroup(new UpdatedGroupBuilder(batchGroup.getUpdatedBatchedGroup()).build())
                .setGroupRef(createGroupRef(input.getNode(), batchGroup)).setNode(input.getNode()).build();
        resultsLot.add(JdkFutureAdapters.listenInPoolThread(salGroupService.updateGroup(updateGroupInput)));
    }// ww  w .  jav  a  2 s .c  o  m

    final Iterable<Group> groups = Iterables.transform(batchUpdateGroups,
            new Function<BatchUpdateGroups, Group>() {
                @Nullable
                @Override
                public Group apply(@Nullable final BatchUpdateGroups input) {
                    return input.getUpdatedBatchedGroup();
                }
            });

    final ListenableFuture<RpcResult<List<BatchFailedGroupsOutput>>> commonResult = Futures.transform(
            Futures.allAsList(resultsLot),
            GroupUtil.<UpdateGroupOutput>createCumulatingFunction(groups, batchUpdateGroups.size()));

    ListenableFuture<RpcResult<UpdateGroupsBatchOutput>> updateGroupsBulkFuture = Futures
            .transform(commonResult, GroupUtil.GROUP_UPDATE_TRANSFORM);

    if (input.isBarrierAfter()) {
        updateGroupsBulkFuture = BarrierUtil.chainBarrier(updateGroupsBulkFuture, input.getNode(),
                transactionService, GroupUtil.GROUP_UPDATE_COMPOSING_TRANSFORM);
    }

    return updateGroupsBulkFuture;
}

From source file:org.thingsboard.server.service.script.RemoteJsInvokeService.java

@Override
protected ListenableFuture<UUID> doEval(UUID scriptId, String functionName, String scriptBody) {
    JsInvokeProtos.JsCompileRequest jsRequest = JsInvokeProtos.JsCompileRequest.newBuilder()
            .setScriptIdMSB(scriptId.getMostSignificantBits())
            .setScriptIdLSB(scriptId.getLeastSignificantBits()).setFunctionName(functionName)
            .setScriptBody(scriptBody).build();

    JsInvokeProtos.RemoteJsRequest jsRequestWrapper = JsInvokeProtos.RemoteJsRequest.newBuilder()
            .setCompileRequest(jsRequest).build();

    log.trace("Post compile request for scriptId [{}]", scriptId);
    ListenableFuture<JsInvokeProtos.RemoteJsResponse> future = kafkaTemplate.post(scriptId.toString(),
            jsRequestWrapper);//  w w w .  j  a  v a2s .com
    return Futures.transform(future, response -> {
        JsInvokeProtos.JsCompileResponse compilationResult = response.getCompileResponse();
        UUID compiledScriptId = new UUID(compilationResult.getScriptIdMSB(),
                compilationResult.getScriptIdLSB());
        if (compilationResult.getSuccess()) {
            scriptIdToNameMap.put(scriptId, functionName);
            scriptIdToBodysMap.put(scriptId, scriptBody);
            return compiledScriptId;
        } else {
            log.debug("[{}] Failed to compile script due to [{}]: {}", compiledScriptId,
                    compilationResult.getErrorCode().name(), compilationResult.getErrorDetails());
            throw new RuntimeException(compilationResult.getErrorDetails());
        }
    });
}