Example usage for com.google.common.collect ImmutableList stream

List of usage examples for com.google.common.collect ImmutableList stream

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList stream.

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:org.apache.james.util.CompletableFutureUtil.java

public static <R, T> CompletableFuture<Stream<R>> chainAll(Stream<T> futureStream,
        Function<T, CompletableFuture<R>> transformationToChain) {
    ImmutableList<T> elements = futureStream.collect(ImmutableList.toImmutableList());
    ArrayList<R> results = new ArrayList<>(elements.size());

    CompletableFuture<Void> futureEmptyStream = CompletableFuture.completedFuture(null);

    BiFunction<CompletableFuture<?>, Supplier<CompletableFuture<R>>, CompletableFuture<?>> accumulator = (
            future, supplier) -> future.thenCompose(any -> supplier.get().thenAccept(results::add));

    BinaryOperator<CompletableFuture<?>> combiner = (f1, f2) -> f1.thenCompose(any -> f2);

    return elements.stream().map(t -> (Supplier<CompletableFuture<R>>) (() -> transformationToChain.apply(t)))
            .reduce(futureEmptyStream, accumulator, combiner).thenApply(any -> results.stream());
}

From source file:org.apache.beam.runners.core.construction.graph.GreedyPipelineFuser.java

private static ExecutableStage sanitizeDanglingPTransformInputs(ExecutableStage stage) {
    /* Possible inputs to a PTransform can only be those which are:
     * <ul>/*from  w w  w. ja  va 2  s . c  o  m*/
     *  <li>Explicit input PCollection to the stage
     *  <li>Outputs of a PTransform within the same stage
     *  <li>Timer PCollections
     *  <li>Side input PCollections
     *  <li>Explicit outputs from the stage
     * </ul>
     */
    Set<String> possibleInputs = new HashSet<>();
    possibleInputs.add(stage.getInputPCollection().getId());
    possibleInputs.addAll(
            stage.getOutputPCollections().stream().map(PCollectionNode::getId).collect(Collectors.toSet()));
    possibleInputs.addAll(
            stage.getSideInputs().stream().map(s -> s.collection().getId()).collect(Collectors.toSet()));
    possibleInputs.addAll(stage.getTransforms().stream()
            .flatMap(t -> t.getTransform().getOutputsMap().values().stream()).collect(Collectors.toSet()));
    Set<String> danglingInputs = stage.getTransforms().stream()
            .flatMap(t -> t.getTransform().getInputsMap().values().stream())
            .filter(in -> !possibleInputs.contains(in)).collect(Collectors.toSet());

    ImmutableList.Builder<PTransformNode> pTransformNodesBuilder = ImmutableList.builder();
    for (PTransformNode transformNode : stage.getTransforms()) {
        PTransform transform = transformNode.getTransform();
        Map<String, String> validInputs = transform.getInputsMap().entrySet().stream()
                .filter(e -> !danglingInputs.contains(e.getValue()))
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

        if (!validInputs.equals(transform.getInputsMap())) {
            // Dangling inputs found so recreate pTransform without the dangling inputs.
            transformNode = PipelineNode.pTransform(transformNode.getId(),
                    transform.toBuilder().clearInputs().putAllInputs(validInputs).build());
        }

        pTransformNodesBuilder.add(transformNode);
    }
    ImmutableList<PTransformNode> pTransformNodes = pTransformNodesBuilder.build();
    Components.Builder componentBuilder = stage.getComponents().toBuilder();
    // Update the pTransforms in components.
    componentBuilder.clearTransforms().putAllTransforms(pTransformNodes.stream()
            .collect(Collectors.toMap(PTransformNode::getId, PTransformNode::getTransform)));
    Map<String, PCollection> validPCollectionMap = stage.getComponents().getPcollectionsMap().entrySet()
            .stream().filter(e -> !danglingInputs.contains(e.getKey()))
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

    // Update pCollections in the components.
    componentBuilder.clearPcollections().putAllPcollections(validPCollectionMap);

    return ImmutableExecutableStage.of(componentBuilder.build(), stage.getEnvironment(),
            stage.getInputPCollection(), stage.getSideInputs(), stage.getUserStates(), stage.getTimers(),
            pTransformNodes, stage.getOutputPCollections());
}

From source file:com.spectralogic.dsbrowser.gui.services.ds3Panel.Ds3PanelService.java

public static Optional<ImmutableList<Bucket>> setSearchableBucket(
        final ObservableList<TreeItem<Ds3TreeTableValue>> selectedItem, final Session session,
        final TreeTableView<Ds3TreeTableValue> treeTableView) {
    try {//from w ww  .j a  v  a2s  .c om
        if (null != treeTableView) {
            ObservableList<TreeItem<Ds3TreeTableValue>> selectedItemTemp = selectedItem;
            if (null == selectedItemTemp) {
                selectedItemTemp = FXCollections.observableArrayList();
                if (null != treeTableView.getRoot() && null != treeTableView.getRoot().getValue()) {
                    selectedItemTemp.add(treeTableView.getRoot());
                }
            }
            final GetBucketsSpectraS3Request getBucketsSpectraS3Request = new GetBucketsSpectraS3Request();
            final GetBucketsSpectraS3Response response = session.getClient()
                    .getBucketsSpectraS3(getBucketsSpectraS3Request);
            final ImmutableList<Bucket> buckets = response.getBucketListResult().getBuckets().stream()
                    .collect(GuavaCollectors.immutableList());
            if (!Guard.isNullOrEmpty(selectedItemTemp)) {
                final ImmutableSet<String> bucketNameSet = selectedItemTemp.stream()
                        .map(item -> item.getValue().getBucketName()).collect(GuavaCollectors.immutableSet());
                return Optional
                        .ofNullable(buckets.stream().filter(bucket -> bucketNameSet.contains(bucket.getName()))
                                .collect(GuavaCollectors.immutableList()));
            } else {
                return Optional.ofNullable(buckets);
            }
        } else {
            throw new NullPointerException("TreeTableView can't be null");
        }
    } catch (final Exception e) {
        LOG.error("Something went wrong!", e);
        return Optional.empty();
    }
}

From source file:com.facebook.buck.cxx.CxxPrepareForLinkStep.java

public static CxxPrepareForLinkStep create(Path argFilePath, Path fileListPath,
        Iterable<Arg> linkerArgsToSupportFileList, Path output, ImmutableList<Arg> args, Linker linker,
        Path currentCellPath, SourcePathResolver resolver) {

    ImmutableList<Arg> allArgs = new ImmutableList.Builder<Arg>()
            .addAll(StringArg.from(linker.outputArgs(output.toString()))).addAll(args)
            .addAll(linkerArgsToSupportFileList).build();

    boolean hasLinkArgsToSupportFileList = linkerArgsToSupportFileList.iterator().hasNext();

    LOG.debug("Link command (pwd=%s): %s %s", currentCellPath.toString(),
            String.join("", linker.getCommandPrefix(resolver)),
            String.join(" ", CxxWriteArgsToFileStep.stringify(allArgs, currentCellPath)));

    CxxWriteArgsToFileStep createArgFileStep = new CxxWriteArgsToFileStep(argFilePath,
            hasLinkArgsToSupportFileList
                    ? allArgs.stream().filter(input -> !(input instanceof FileListableLinkerInputArg)).collect(
                            MoreCollectors.toImmutableList())
                    : allArgs,// w ww .  ja v  a2s  . c  om
            Optional.of(Javac.ARGFILES_ESCAPER), currentCellPath);

    if (!hasLinkArgsToSupportFileList) {
        LOG.verbose("linkerArgsToSupportFileList is empty, filelist feature is not supported");
        return new CxxPrepareForLinkStep(ImmutableList.of(createArgFileStep));
    }

    CxxWriteArgsToFileStep createFileListStep = new CxxWriteArgsToFileStep(fileListPath,
            allArgs.stream().filter(input -> input instanceof FileListableLinkerInputArg)
                    .collect(MoreCollectors.toImmutableList()),
            Optional.empty(), currentCellPath);

    return new CxxPrepareForLinkStep(ImmutableList.of(createArgFileStep, createFileListStep));
}

From source file:org.eclipse.milo.opcua.sdk.client.session.states.AbstractSessionState.java

private static void transferSubscriptions(Fsm fsm, OpcUaSession session,
        CompletableFuture<OpcUaSession> sessionFuture) {

    OpcUaClient client = fsm.getClient();
    UaTcpStackClient stackClient = client.getStackClient();
    OpcUaSubscriptionManager subscriptionManager = client.getSubscriptionManager();
    ImmutableList<UaSubscription> subscriptions = subscriptionManager.getSubscriptions();

    if (subscriptions.isEmpty()) {
        fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
        return;//from  w  ww. java 2 s . c o m
    }

    UInteger[] subscriptionIdsArray = subscriptions.stream().map(UaSubscription::getSubscriptionId)
            .toArray(UInteger[]::new);

    TransferSubscriptionsRequest request = new TransferSubscriptionsRequest(
            client.newRequestHeader(session.getAuthenticationToken(), REQUEST_TIMEOUT), subscriptionIdsArray,
            true);

    LOGGER.debug("Sending TransferSubscriptionsRequest...");

    stackClient.<TransferSubscriptionsResponse>sendRequest(request).whenCompleteAsync((tsr, ex) -> {
        if (tsr != null) {
            List<TransferResult> results = l(tsr.getResults());

            client.getConfig().getExecutor().execute(() -> {
                for (int i = 0; i < results.size(); i++) {
                    TransferResult result = results.get(i);

                    if (!result.getStatusCode().isGood()) {
                        UaSubscription subscription = subscriptions.get(i);

                        subscriptionManager.transferFailed(subscription.getSubscriptionId(),
                                result.getStatusCode());
                    }
                }
            });

            if (LOGGER.isDebugEnabled()) {
                Stream<UInteger> subscriptionIds = subscriptions.stream()
                        .map(UaSubscription::getSubscriptionId);
                Stream<StatusCode> statusCodes = results.stream().map(TransferResult::getStatusCode);

                String[] ss = StreamUtils
                        .zip(subscriptionIds, statusCodes,
                                (i, s) -> String.format("id=%s/%s", i,
                                        StatusCodes.lookup(s.getValue()).map(sa -> sa[0]).orElse(s.toString())))
                        .toArray(String[]::new);

                LOGGER.debug("TransferSubscriptions results: {}", Arrays.toString(ss));
            }

            fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
        } else {
            StatusCode statusCode = UaException.extract(ex).map(UaException::getStatusCode)
                    .orElse(StatusCode.BAD);

            // Bad_ServiceUnsupported is the correct response when transfers aren't supported but
            // server implementations tend to interpret the spec in their own unique way...
            if (statusCode.getValue() == StatusCodes.Bad_NotImplemented
                    || statusCode.getValue() == StatusCodes.Bad_NotSupported
                    || statusCode.getValue() == StatusCodes.Bad_OutOfService
                    || statusCode.getValue() == StatusCodes.Bad_ServiceUnsupported) {

                LOGGER.debug("TransferSubscriptions not supported: {}", statusCode);

                client.getConfig().getExecutor().execute(() -> {
                    // transferFailed() will remove the subscription, but that is okay
                    // because the list from getSubscriptions() above is a copy.
                    for (UaSubscription subscription : subscriptions) {
                        subscriptionManager.transferFailed(subscription.getSubscriptionId(), statusCode);
                    }
                });

                fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
            } else {
                LOGGER.debug("TransferSubscriptions failed: {}", statusCode);

                fsm.fireEvent(new TransferFailureEvent(ex, session, sessionFuture));
            }
        }
    }, stackClient.getExecutorService());
}

From source file:com.facebook.buck.rust.RustCompileUtils.java

protected static RustCompileRule createBuild(BuildTarget target, String crateName, BuildRuleParams params,
        BuildRuleResolver resolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder,
        CxxPlatform cxxPlatform, RustBuckConfig rustConfig, ImmutableList<String> extraFlags,
        ImmutableList<String> extraLinkerFlags, Iterable<Arg> linkerInputs, CrateType crateType,
        Linker.LinkableDepType depType, boolean rpath, ImmutableSortedSet<SourcePath> sources,
        SourcePath rootModule) throws NoSuchBuildTargetException {
    ImmutableSortedSet<BuildRule> ruledeps = params.getDeps();
    ImmutableList.Builder<Arg> linkerArgs = ImmutableList.builder();

    Stream.concat(rustConfig.getLinkerArgs(cxxPlatform).stream(), extraLinkerFlags.stream()).map(StringArg::new)
            .forEach(linkerArgs::add);/*w  w w .ja v  a2 s  .c  om*/

    linkerArgs.addAll(linkerInputs);

    ImmutableList.Builder<Arg> args = ImmutableList.builder();

    String relocModel;
    if (crateType.isPic()) {
        relocModel = "pic";
    } else {
        relocModel = "static";
    }

    Stream.of(Stream.of(String.format("--crate-name=%s", crateName),
            String.format("--crate-type=%s", crateType), String.format("-Crelocation-model=%s", relocModel)),
            extraFlags.stream()).flatMap(x -> x).map(StringArg::new).forEach(args::add);

    // Find direct and transitive Rust deps. This could end up with a lot of redundant
    // parameters (lots of rlibs in one directory), but Arg isn't comparable, so we can't
    // put it in a Set.
    new AbstractBreadthFirstTraversal<BuildRule>(ruledeps) {
        private final ImmutableSet<BuildRule> empty = ImmutableSet.of();

        @Override
        public Iterable<BuildRule> visit(BuildRule rule) {
            ImmutableSet<BuildRule> deps = empty;
            if (rule instanceof RustLinkable) {
                deps = rule.getDeps();
                Arg arg = ((RustLinkable) rule).getLinkerArg(ruledeps.contains(rule), cxxPlatform, depType);

                args.add(arg);
            }
            return deps;
        }
    }.start();

    // A native crate output is no longer intended for consumption by the Rust toolchain;
    // it's either an executable, or a native library that C/C++ can link with. Rust DYLIBs
    // also need all dependencies available.
    if (crateType.needAllDeps()) {
        ImmutableList<Arg> nativeArgs = NativeLinkables.getTransitiveNativeLinkableInput(cxxPlatform, ruledeps,
                depType, RustLinkable.class::isInstance, RustLinkable.class::isInstance).getArgs();

        // Add necessary rpaths if we're dynamically linking with things
        // XXX currently breaks on paths containing commas, which all of ours do: see
        // https://github.com/rust-lang/rust/issues/38795
        if (rpath && depType == Linker.LinkableDepType.SHARED) {
            args.add(new StringArg("-Crpath"));
        }

        linkerArgs.addAll(nativeArgs);

        // Also let rustc know about libraries as native deps (in case someone is using #[link]
        // even though it won't generally work with Buck)
        nativeArgs.stream().filter(HasSourcePath.class::isInstance).map(sp -> (HasSourcePath) sp)
                .map(sp -> sp.getPathResolver().getRelativePath(sp.getPath()).getParent())
                .map(dir -> String.format("-Lnative=%s", dir)).map(StringArg::new).forEach(args::add);
    }

    // If we want shared deps or are building a dynamic rlib, make sure we prefer
    // dynamic dependencies (esp to get dynamic dependency on standard libs)
    if (depType == Linker.LinkableDepType.SHARED || crateType == CrateType.DYLIB) {
        args.add(new StringArg("-Cprefer-dynamic"));
    }

    String filename = crateType.filenameFor(crateName, cxxPlatform);

    return resolver.addToIndex(RustCompileRule.from(ruleFinder, params.copyWithBuildTarget(target),
            pathResolver, filename, rustConfig.getRustCompiler().resolve(resolver),
            rustConfig.getLinkerProvider(cxxPlatform, cxxPlatform.getLd().getType()).resolve(resolver),
            args.build(), linkerArgs.build(), sources, rootModule));
}

From source file:com.google.devtools.build.lib.rules.cpp.CppLinkstampCompileHelper.java

private static CcToolchainVariables getVariables(RuleContext ruleContext, Artifact sourceFile,
        Artifact outputFile, String labelReplacement, String outputReplacement,
        Iterable<String> additionalLinkstampDefines, ImmutableList<Artifact> buildInfoHeaderArtifacts,
        FeatureConfiguration featureConfiguration, CppConfiguration cppConfiguration,
        CcToolchainProvider ccToolchainProvider, boolean needsPic, String fdoBuildStamp,
        boolean codeCoverageEnabled) {
    // TODO(b/34761650): Remove all this hardcoding by separating a full blown compile action.
    Preconditions.checkArgument(featureConfiguration.actionIsConfigured(CppCompileAction.LINKSTAMP_COMPILE));

    return CompileBuildVariables.setupVariablesOrReportRuleError(ruleContext, featureConfiguration,
            ccToolchainProvider, sourceFile.getExecPathString(), outputFile.getExecPathString(),
            /* gcnoFile= */ null, /* dwoFile= */ null, /* ltoIndexingFile= */ null,
            buildInfoHeaderArtifacts.stream().map(Artifact::getExecPathString)
                    .collect(ImmutableList.toImmutableList()),
            CcCompilationHelper.getCoptsFromOptions(cppConfiguration, sourceFile.getExecPathString()),
            /* cppModuleMap= */ null, needsPic, /* fakeOutputFile= */ null, fdoBuildStamp,
            /* dotdFileExecPath= */ null, /* variablesExtensions= */ ImmutableList.of(),
            /* additionalBuildVariables= */ ImmutableMap.of(), /* directModuleMaps= */ ImmutableList.of(),
            /* includeDirs= */ ImmutableList.of(PathFragment.create(".")),
            /* quoteIncludeDirs= */ ImmutableList.of(), /* systemIncludeDirs= */ ImmutableList.of(),
            computeAllLinkstampDefines(labelReplacement, outputReplacement, additionalLinkstampDefines,
                    cppConfiguration, fdoBuildStamp, codeCoverageEnabled));
}

From source file:com.facebook.buck.jvm.java.AnnotationProcessorFactory.java

public List<Processor> createProcessors(ImmutableList<JavacPluginJsr199Fields> fields) {
    return fields.stream().map(this::createProcessorsWithCommonClasspath).flatMap(Function.identity())
            .collect(Collectors.toList());
}

From source file:com.facebook.buck.cxx.CxxDescriptionEnhancer.java

public static CxxLinkAndCompileRules createBuildRulesForCxxBinary(BuildRuleParams params,
        BuildRuleResolver resolver, CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform,
        ImmutableMap<String, CxxSource> srcs, ImmutableMap<Path, SourcePath> headers,
        Iterable<? extends BuildRule> deps, Optional<StripStyle> stripStyle,
        Optional<LinkerMapMode> flavoredLinkerMapMode, Linker.LinkableDepType linkStyle,
        ImmutableList<String> preprocessorFlags,
        PatternMatchedCollection<ImmutableList<String>> platformPreprocessorFlags,
        ImmutableMap<CxxSource.Type, ImmutableList<String>> langPreprocessorFlags,
        ImmutableSortedSet<FrameworkPath> frameworks, ImmutableSortedSet<FrameworkPath> libraries,
        ImmutableList<String> compilerFlags,
        ImmutableMap<CxxSource.Type, ImmutableList<String>> langCompilerFlags,
        PatternMatchedCollection<ImmutableList<String>> platformCompilerFlags,
        Optional<SourcePath> prefixHeader, Optional<SourcePath> precompiledHeader,
        ImmutableList<String> linkerFlags, PatternMatchedCollection<ImmutableList<String>> platformLinkerFlags,
        Optional<Linker.CxxRuntimeType> cxxRuntimeType, ImmutableList<String> includeDirs,
        Optional<Boolean> xcodePrivateHeadersSymlinks) throws NoSuchBuildTargetException {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver sourcePathResolver = new SourcePathResolver(ruleFinder);
    //    TODO(beefon): should be:
    //    Path linkOutput = getLinkOutputPath(
    //        createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode),
    //        params.getProjectFilesystem());

    BuildTarget target = params.getBuildTarget();
    if (flavoredLinkerMapMode.isPresent()) {
        target = target.withAppendedFlavors(flavoredLinkerMapMode.get().getFlavor());
    }/*from w w  w. j  a va 2 s  .  c  o  m*/
    Path linkOutput = getBinaryOutputPath(target, params.getProjectFilesystem(),
            cxxPlatform.getBinaryExtension());
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();
    CommandTool.Builder executableBuilder = new CommandTool.Builder();

    // Setup the header symlink tree and combine all the preprocessor input from this rule
    // and all dependencies.
    boolean shouldCreatePrivateHeadersSymlinks = xcodePrivateHeadersSymlinks.orElse(true);
    HeaderSymlinkTree headerSymlinkTree = requireHeaderSymlinkTree(params, resolver, sourcePathResolver,
            cxxPlatform, headers, HeaderVisibility.PRIVATE, shouldCreatePrivateHeadersSymlinks);
    Optional<SymlinkTree> sandboxTree = Optional.empty();
    if (cxxBuckConfig.sandboxSources()) {
        sandboxTree = createSandboxTree(params, resolver, cxxPlatform);
    }
    ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput = collectCxxPreprocessorInput(params, cxxPlatform,
            CxxFlags.getLanguageFlags(
                    preprocessorFlags, platformPreprocessorFlags, langPreprocessorFlags, cxxPlatform),
            ImmutableList.of(headerSymlinkTree), frameworks,
            CxxPreprocessables.getTransitiveCxxPreprocessorInput(cxxPlatform,
                    RichStream.from(deps).filter(CxxPreprocessorDep.class::isInstance).toImmutableList()),
            includeDirs, sandboxTree);

    // Generate and add all the build rules to preprocess and compile the source to the
    // resolver and get the `SourcePath`s representing the generated object files.
    ImmutableMap<CxxPreprocessAndCompile, SourcePath> objects = CxxSourceRuleFactory
            .requirePreprocessAndCompileRules(params, resolver, sourcePathResolver, ruleFinder, cxxBuckConfig,
                    cxxPlatform, cxxPreprocessorInput,
                    CxxFlags.getLanguageFlags(compilerFlags, platformCompilerFlags, langCompilerFlags,
                            cxxPlatform),
                    prefixHeader, precompiledHeader, srcs,
                    linkStyle == Linker.LinkableDepType.STATIC ? CxxSourceRuleFactory.PicType.PDC
                            : CxxSourceRuleFactory.PicType.PIC,
                    sandboxTree);

    // Build up the linker flags, which support macro expansion.
    ImmutableList<String> resolvedLinkerFlags = CxxFlags.getFlags(linkerFlags, platformLinkerFlags,
            cxxPlatform);
    argsBuilder.addAll(resolvedLinkerFlags.stream().map(MacroArg.toMacroArgFunction(MACRO_HANDLER,
            params.getBuildTarget(), params.getCellRoots(), resolver)::apply).iterator());

    // Special handling for dynamically linked binaries.
    if (linkStyle == Linker.LinkableDepType.SHARED) {

        // Create a symlink tree with for all shared libraries needed by this binary.
        SymlinkTree sharedLibraries = requireSharedLibrarySymlinkTree(params, resolver, sourcePathResolver,
                cxxPlatform, deps, NativeLinkable.class::isInstance);

        // Embed a origin-relative library path into the binary so it can find the shared libraries.
        // The shared libraries root is absolute. Also need an absolute path to the linkOutput

        Path absLinkOut = params.getBuildTarget().getCellPath().resolve(linkOutput);

        argsBuilder.addAll(StringArg.from(Linkers.iXlinker("-rpath",
                String.format("%s/%s", cxxPlatform.getLd().resolve(resolver).origin(),
                        absLinkOut.getParent().relativize(sharedLibraries.getRoot()).toString()))));

        // Add all the shared libraries and the symlink tree as inputs to the tool that represents
        // this binary, so that users can attach the proper deps.
        executableBuilder.addDep(sharedLibraries);
        executableBuilder.addInputs(sharedLibraries.getLinks().values());
    }

    // Add object files into the args.
    ImmutableList<SourcePathArg> objectArgs = SourcePathArg.from(sourcePathResolver, objects.values()).stream()
            .map(input -> {
                Preconditions.checkArgument(input instanceof SourcePathArg);
                return (SourcePathArg) input;
            }).collect(MoreCollectors.toImmutableList());
    argsBuilder.addAll(FileListableLinkerInputArg.from(objectArgs));

    BuildTarget linkRuleTarget = createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode);

    CxxLink cxxLink = createCxxLinkRule(params, resolver, cxxBuckConfig, cxxPlatform,
            RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(), linkStyle, frameworks,
            libraries, cxxRuntimeType, sourcePathResolver, ruleFinder, linkOutput, argsBuilder, linkRuleTarget);

    BuildRule binaryRuleForExecutable;
    Optional<CxxStrip> cxxStrip = Optional.empty();
    if (stripStyle.isPresent()) {
        BuildRuleParams cxxParams = params;
        if (flavoredLinkerMapMode.isPresent()) {
            cxxParams = params.withFlavor(flavoredLinkerMapMode.get().getFlavor());
        }
        CxxStrip stripRule = createCxxStripRule(cxxParams, resolver, stripStyle.get(), sourcePathResolver,
                cxxLink, cxxPlatform);
        cxxStrip = Optional.of(stripRule);
        binaryRuleForExecutable = stripRule;
    } else {
        binaryRuleForExecutable = cxxLink;
    }

    // Add the output of the link as the lone argument needed to invoke this binary as a tool.
    executableBuilder.addArg(new SourcePathArg(sourcePathResolver,
            new BuildTargetSourcePath(binaryRuleForExecutable.getBuildTarget())));

    return new CxxLinkAndCompileRules(cxxLink, cxxStrip, ImmutableSortedSet.copyOf(objects.keySet()),
            executableBuilder.build());
}

From source file:com.google.devtools.build.lib.analysis.skylark.SkylarkAttr.java

private static Attribute.Builder<?> createAttribute(Type<?> type, SkylarkDict<String, Object> arguments,
        FuncallExpression ast, Environment env, String name) throws EvalException {
    Attribute.Builder<?> builder = Attribute.attr(name, type);

    Object defaultValue = arguments.get(DEFAULT_ARG);
    if (!EvalUtils.isNullOrNone(defaultValue)) {
        if (defaultValue instanceof UserDefinedFunction) {
            // Computed attribute. Non label type attributes already caused a type check error.
            SkylarkCallbackFunction callback = new SkylarkCallbackFunction((UserDefinedFunction) defaultValue,
                    ast, env);/*ww w . ja v a 2s . c om*/
            // SkylarkComputedDefaultTemplate needs to know the names of all attributes that it depends
            // on. However, this method does not know anything about other attributes.
            // We solve this problem by asking the SkylarkCallbackFunction for the parameter names used
            // in the function definition, which must be the names of attributes used by the callback.
            builder.value(new SkylarkComputedDefaultTemplate(type, callback.getParameterNames(), callback,
                    ast.getLocation()));
        } else if (defaultValue instanceof SkylarkLateBoundDefault) {
            builder.value((SkylarkLateBoundDefault) defaultValue);
        } else {
            builder.defaultValue(defaultValue, env.getGlobals().getTransitiveLabel(), DEFAULT_ARG);
        }
    }

    for (String flag : SkylarkList.castSkylarkListOrNoneToList(arguments.get(FLAGS_ARG), String.class,
            FLAGS_ARG)) {
        builder.setPropertyFlag(flag);
    }

    if (containsNonNoneKey(arguments, MANDATORY_ARG) && (Boolean) arguments.get(MANDATORY_ARG)) {
        builder.setPropertyFlag("MANDATORY");
    }

    // TODO(laurentlb): Deprecated, remove in August 2016 (use allow_empty instead).
    if (containsNonNoneKey(arguments, NON_EMPTY_ARG) && (Boolean) arguments.get(NON_EMPTY_ARG)) {
        builder.setPropertyFlag("NON_EMPTY");
    }

    if (containsNonNoneKey(arguments, ALLOW_EMPTY_ARG) && !(Boolean) arguments.get(ALLOW_EMPTY_ARG)) {
        builder.setPropertyFlag("NON_EMPTY");
    }

    if (containsNonNoneKey(arguments, EXECUTABLE_ARG) && (Boolean) arguments.get(EXECUTABLE_ARG)) {
        builder.setPropertyFlag("EXECUTABLE");
        if (!containsNonNoneKey(arguments, CONFIGURATION_ARG)) {
            throw new EvalException(ast.getLocation(),
                    "cfg parameter is mandatory when executable=True is provided. Please see "
                            + "https://www.bazel.build/versions/master/docs/skylark/rules.html#configurations "
                            + "for more details.");
        }
    }

    // TODO(laurentlb): Deprecated, remove in August 2016 (use allow_single_file).
    if (containsNonNoneKey(arguments, SINGLE_FILE_ARG) && (Boolean) arguments.get(SINGLE_FILE_ARG)) {
        if (containsNonNoneKey(arguments, ALLOW_SINGLE_FILE_ARG)) {
            throw new EvalException(ast.getLocation(),
                    "Cannot specify both single_file (deprecated) and allow_single_file");
        }
        builder.setPropertyFlag("SINGLE_ARTIFACT");
    }

    if (containsNonNoneKey(arguments, ALLOW_FILES_ARG)
            && containsNonNoneKey(arguments, ALLOW_SINGLE_FILE_ARG)) {
        throw new EvalException(ast.getLocation(), "Cannot specify both allow_files and allow_single_file");
    }

    if (containsNonNoneKey(arguments, ALLOW_FILES_ARG)) {
        Object fileTypesObj = arguments.get(ALLOW_FILES_ARG);
        setAllowedFileTypes(ALLOW_FILES_ARG, fileTypesObj, ast, builder);
    } else if (containsNonNoneKey(arguments, ALLOW_SINGLE_FILE_ARG)) {
        Object fileTypesObj = arguments.get(ALLOW_SINGLE_FILE_ARG);
        setAllowedFileTypes(ALLOW_SINGLE_FILE_ARG, fileTypesObj, ast, builder);
        builder.setPropertyFlag("SINGLE_ARTIFACT");
    } else if (type.getLabelClass() == LabelClass.DEPENDENCY) {
        builder.allowedFileTypes(FileTypeSet.NO_FILE);
    }

    Object ruleClassesObj = arguments.get(ALLOW_RULES_ARG);
    if (ruleClassesObj != null && ruleClassesObj != Runtime.NONE) {
        builder.allowedRuleClasses(SkylarkList.castSkylarkListOrNoneToList(ruleClassesObj, String.class,
                "allowed rule classes for attribute definition"));
    }

    List<Object> values = SkylarkList.castSkylarkListOrNoneToList(arguments.get(VALUES_ARG), Object.class,
            VALUES_ARG);
    if (!Iterables.isEmpty(values)) {
        builder.allowedValues(new AllowedValueSet(values));
    }

    if (containsNonNoneKey(arguments, PROVIDERS_ARG)) {
        Object obj = arguments.get(PROVIDERS_ARG);
        SkylarkType.checkType(obj, SkylarkList.class, PROVIDERS_ARG);
        ImmutableList<ImmutableSet<SkylarkProviderIdentifier>> providersList = buildProviderPredicate(
                (SkylarkList<?>) obj, PROVIDERS_ARG, ast.getLocation());

        // If there is at least one empty set, there is no restriction.
        if (providersList.stream().noneMatch(ImmutableSet::isEmpty)) {
            builder.mandatoryProvidersList(providersList);
        }
    }

    if (containsNonNoneKey(arguments, CONFIGURATION_ARG)) {
        Object trans = arguments.get(CONFIGURATION_ARG);
        if (trans.equals("data")) {
            builder.cfg(ConfigurationTransition.DATA);
        } else if (trans.equals("host")) {
            builder.cfg(ConfigurationTransition.HOST);
        } else if (trans instanceof SplitTransition<?>) {
            builder.cfg((SplitTransition<?>) trans);
        } else if (trans instanceof SplitTransitionProvider) {
            builder.cfg((SplitTransitionProvider) trans);
        } else if (!trans.equals("target")) {
            throw new EvalException(ast.getLocation(), "cfg must be either 'data', 'host', or 'target'.");
        }
    }

    if (containsNonNoneKey(arguments, ASPECTS_ARG)) {
        Object obj = arguments.get(ASPECTS_ARG);
        SkylarkType.checkType(obj, SkylarkList.class, ASPECTS_ARG);

        List<SkylarkAspect> aspects = ((SkylarkList<?>) obj).getContents(SkylarkAspect.class, "aspects");
        for (SkylarkAspect aspect : aspects) {
            if (!aspect.isExported()) {
                throw new EvalException(ast.getLocation(),
                        "Aspects should be top-level values in extension files that define them.");
            }
            builder.aspect(aspect, ast.getLocation());
        }
    }

    return builder;
}