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 = { "addmember", "addmember", "addmem",
        "am" }, usage = "<id> <members...>", flags = "nw:", desc = "Add a member to a region", min = 2)
public void addMember(CommandContext args, CommandSender sender) throws CommandException {
    warnAboutSaveFailures(sender);/* w w  w.j  a v a  2  s.c  om*/

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

    id = region.getId();

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

    // Resolve members 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 members
    ListenableFuture<DefaultDomain> future = Futures.transform(plugin.getExecutorService().submit(resolver),
            resolver.createAddAllFunction(region.getMembers()));

    AsyncCommandHelper.wrap(future, plugin, sender).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:com.android.camera.one.v2.initialization.PreviewStarter.java

/**
 * See {@link OneCamera#startPreview}./*w w w  .  ja  va  2s  .  c  om*/
 *
 * @param surface The preview surface to use.
 */
public ListenableFuture<Void> startPreview(final Surface surface) {
    // When we have the preview surface, start the capture session.
    List<Surface> surfaceList = new ArrayList<>();

    // Workaround of the face detection failure on Nexus 5 and L. (b/21039466)
    // Need to create a capture session with the single preview stream first
    // to lock it as the first stream. Then resend the another session with preview
    // and JPEG stream.
    if (ApiHelper.isLorLMr1() && ApiHelper.IS_NEXUS_5) {
        surfaceList.add(surface);
        mCaptureSessionCreator.createCaptureSession(surfaceList);
        surfaceList.addAll(mOutputSurfaces);
    } else {
        surfaceList.addAll(mOutputSurfaces);
        surfaceList.add(surface);
    }

    final ListenableFuture<CameraCaptureSessionProxy> sessionFuture = mCaptureSessionCreator
            .createCaptureSession(surfaceList);

    return Futures.transform(sessionFuture, new AsyncFunction<CameraCaptureSessionProxy, Void>() {
        @Override
        public ListenableFuture<Void> apply(CameraCaptureSessionProxy captureSession) throws Exception {
            mSessionListener.onCameraCaptureSessionCreated(captureSession, surface);
            return Futures.immediateFuture(null);
        }
    });
}

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

private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readConfigurationData(
        final YangInstanceIdentifier path) {
    final ListenableFuture<DOMRpcResult> configRunning = netconfOps.getConfigRunning(loggingCallback,
            Optional.fromNullable(path));

    final ListenableFuture<Optional<NormalizedNode<?, ?>>> transformedFuture = Futures.transform(configRunning,
            new Function<DOMRpcResult, Optional<NormalizedNode<?, ?>>>() {
                @Override//from w  ww . j  a  va 2  s .  c om
                public Optional<NormalizedNode<?, ?>> apply(final DOMRpcResult result) {
                    checkReadSuccess(result, path);

                    final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataNode = findDataNode(
                            result);
                    return NormalizedNodes.findNode(dataNode, path.getPathArguments());
                }
            });

    return MappingCheckedFuture.create(transformedFuture, ReadFailedException.MAPPER);
}

From source file:org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc.java

@Nonnull
@Override//www. j a v  a  2 s.  c  om
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
        @Nullable final NormalizedNode<?, ?> input) {
    final NetconfMessage message = transformer.toRpcRequest(type, input);
    final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult = listener
            .sendRequest(message, type.getLastComponent());

    final ListenableFuture<DOMRpcResult> transformed = Futures.transform(delegateFutureWithPureResult,
            new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
                @Override
                public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
                    if (input.isSuccessful()) {
                        return transformer.toRpcResult(input.getResult(), type);
                    } else {
                        return new DefaultDOMRpcResult(input.getErrors());
                    }
                }
            });

    return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
        @Nullable
        @Override
        public DOMRpcException apply(@Nullable final Exception e) {
            return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s", type);
        }
    });
}

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

@Override
public ListenableFuture<Result> executeAsync() {
    ListenableFuture<Result> future = super.executeAsync();

    Function<Result, Result> validateLwtIfFunction = new Function<Result, Result>() {
        @Override//from  w w w  .  ja v a 2s  .co  m
        public Result apply(Result result) {
            if (isLwt() && !result.wasApplied()) {
                throw new IfConditionException(result, "duplicated entry");
            }
            return result;
        }
    };
    return Futures.transform(future, validateLwtIfFunction);
}

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

private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readConfigurationData(
        final YangInstanceIdentifier path) {
    final ListenableFuture<RpcResult<CompositeNode>> future = rpc.invokeRpc(NETCONF_GET_CONFIG_QNAME,
            NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, CONFIG_SOURCE_RUNNING,
                    toFilterStructure(path)));

    final ListenableFuture<Optional<NormalizedNode<?, ?>>> transformedFuture = Futures.transform(future,
            new Function<RpcResult<CompositeNode>, Optional<NormalizedNode<?, ?>>>() {
                @Override//from  w  ww.j  a v  a 2  s.c  o m
                public Optional<NormalizedNode<?, ?>> apply(final RpcResult<CompositeNode> result) {
                    checkReadSuccess(result, path);

                    final CompositeNode data = result.getResult().getFirstCompositeByName(NETCONF_DATA_QNAME);
                    final CompositeNode node = (CompositeNode) NetconfMessageTransformUtil.findNode(data, path);

                    return data == null ? Optional.<NormalizedNode<?, ?>>absent() : transform(path, node);
                }
            });

    return MappingCheckedFuture.create(transformedFuture, ReadFailedException.MAPPER);
}

From source file:org.opendaylight.bgpcep.pcep.topology.provider.TopologyRPCs.java

@Override
public Future<RpcResult<RemoveLspOutput>> removeLsp(final RemoveLspInput input) {
    return Futures.transform(manager.removeLsp(input),
            new Function<OperationResult, RpcResult<RemoveLspOutput>>() {
                @Override/*from www .  ja v a 2 s  . c o  m*/
                public RpcResult<RemoveLspOutput> apply(final OperationResult input) {
                    return SuccessfulRpcResult.create(new RemoveLspOutputBuilder(input).build());
                }
            });
}

From source file:android.support.test.espresso.web.action.JavascriptEvaluation.java

/**
 * Evaluates a script on a given WebView.
 *
 * Scripts are only evaluated when a WebView is deemed sane. That is:
 * <ul>//  www . j  a  va  2s  .  co m
 * <li>The WebView's back/forward list's last item agrees with the WebView</li>
 * <li>The WebView's reported content height is non-zero</li>
 * <li>The WebView's reported progress is 100</li>
 * <li>The document.documentElement object for the DOM of the selected window is non-null</li>
 * <ul>
 *
 * Scripts are evaluated on the WebKit/Chromium thread (that is - not the Main thread).
 * A Future is returned which contains the result of the evaluation.
 */
static ListenableFuture<Evaluation> evaluate(final WebView view, final String script,
        final List<? extends Object> arguments, @Nullable final WindowReference window) {
    UnpreparedScript unprepared = new UnpreparedScript(view, script, arguments, window);
    SanitizerTask sanitizer = new SanitizerTask(unprepared);
    view.post(sanitizer);
    ListenableFuture<PreparedScript> preparedScript = Futures.transform(sanitizer, SCRIPT_PREPARER);
    ListenableFuture<String> rawEvaluation = Futures.transform(preparedScript, RAW_EVALUATOR);
    ListenableFuture<Evaluation> parsedEvaluation = Futures.transform(rawEvaluation, DECODE_EVALUATION);
    return parsedEvaluation;
}

From source file:com.microsoft.azure.keyvault.extensions.KeyVaultKeyResolver.java

private ListenableFuture<IKey> resolveKeyFromSecretAsync(String kid) {

    ListenableFuture<SecretBundle> futureCall = client.getSecretAsync(kid, null);
    return Futures.transform(futureCall, new FutureKeyFromSecret());
}

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

@Nonnull
@Override//  w ww.j  a  v a2 s  .  c  o m
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
        @Nullable final NormalizedNode<?, ?> input) {
    final NetconfMessage message = transformer.toRpcRequest(type, input);
    final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult = listener
            .sendRequest(message, type.getLastComponent());

    final ListenableFuture<DOMRpcResult> transformed = Futures.transform(delegateFutureWithPureResult,
            new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
                @Override
                public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
                    if (input.isSuccessful()) {
                        return transformer.toRpcResult(input.getResult(), type);
                    } else {
                        // TODO check whether the listener sets errors properly
                        return new DefaultDOMRpcResult(input.getErrors());
                    }
                }
            });

    return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
        @Nullable
        @Override
        public DOMRpcException apply(@Nullable final Exception e) {
            // FIXME what other possible exceptions are there ?
            return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s", type);
        }
    });
}