Example usage for com.google.common.collect ImmutableSet.Builder addAll

List of usage examples for com.google.common.collect ImmutableSet.Builder addAll

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet.Builder addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:org.lanternpowered.server.data.value.AbstractValueContainer.java

@Override
default Set<Key<?>> getKeys() {
    ImmutableSet.Builder<Key<?>> keys = ImmutableSet.builder();
    keys.addAll(this.getRawValueMap().keySet());
    List<DataManipulator<?, ?>> manipulators = this.getRawAdditionalManipulators();
    if (manipulators != null) {
        manipulators.forEach(manipulator -> keys.addAll(manipulator.getKeys()));
    }/*from   www  . ja v a  2 s .c  o  m*/
    return keys.build();
}

From source file:org.elasticsearch.cluster.block.ClusterBlocks.java

public ClusterBlockException indicesBlockedException(ClusterBlockLevel level, String[] indices) {
    boolean indexIsBlocked = false;
    for (String index : indices) {
        if (indexBlocked(level, index)) {
            indexIsBlocked = true;//w w w . ja v a 2 s .  c  om
        }
    }
    if (!indexIsBlocked) {
        return null;
    }
    ImmutableSet.Builder<ClusterBlock> builder = ImmutableSet.builder();
    builder.addAll(global(level));
    for (String index : indices) {
        ImmutableSet<ClusterBlock> indexBlocks = indices(level).get(index);
        if (indexBlocks != null) {
            builder.addAll(indexBlocks);
        }
    }
    return new ClusterBlockException(builder.build());
}

From source file:google.registry.tools.GetLrpTokenCommand.java

@Override
public void run() throws Exception {
    checkArgument((tokenString == null) == (assignee != null),
            "Exactly one of either token or assignee must be specified.");
    ImmutableSet.Builder<LrpTokenEntity> tokensBuilder = new ImmutableSet.Builder<>();
    if (tokenString != null) {
        LrpTokenEntity token = ofy().load().key(Key.create(LrpTokenEntity.class, tokenString)).now();
        if (token != null) {
            tokensBuilder.add(token);//  www. j  a  va 2  s.com
        }
    } else {
        tokensBuilder.addAll(ofy().load().type(LrpTokenEntity.class).filter("assignee", assignee));
    }

    ImmutableSet<LrpTokenEntity> tokens = tokensBuilder.build();
    if (!tokens.isEmpty()) {
        for (LrpTokenEntity token : tokens) {
            System.out.println(token);
            if (includeHistory && token.getRedemptionHistoryEntry() != null) {
                System.out
                        .println(ofy().load().key(token.getRedemptionHistoryEntry()).now().toHydratedString());
            }
        }
    } else {
        System.out.println("Token not found.");
    }
}

From source file:com.android.manifmerger.XmlAttribute.java

/**
 * Handles tools: namespace attributes presence in both documents.
 * @param higherPriority the higherPriority attribute
 *//*from   w w  w  .  jav a 2s  .c  o  m*/
private void handleBothToolsAttributePresent(XmlAttribute higherPriority) {

    // do not merge tools:node attributes, the higher priority one wins.
    if (getName().getLocalName().equals(NodeOperationType.NODE_LOCAL_NAME)) {
        return;
    }

    // everything else should be merged, duplicates should be eliminated.
    Splitter splitter = Splitter.on(',');
    ImmutableSet.Builder<String> targetValues = ImmutableSet.builder();
    targetValues.addAll(splitter.split(higherPriority.getValue()));
    targetValues.addAll(splitter.split(getValue()));
    higherPriority.getXml().setValue(Joiner.on(',').join(targetValues.build()));
}

From source file:com.facebook.buck.parser.ParserNg.java

private ImmutableSet<BuildTarget> resolveTargetSpecs(PerBuildState state, Cell cell,
        Iterable<? extends TargetNodeSpec> specs)
        throws BuildFileParseException, BuildTargetException, IOException, InterruptedException {

    ImmutableSet.Builder<BuildTarget> targets = ImmutableSet.builder();

    for (TargetNodeSpec spec : specs) {
        targets.addAll(resolveTargetSpec(state, cell, spec));
    }/* ww w . j  a va 2 s  . c o m*/

    return targets.build();
}

From source file:com.google.devtools.build.lib.analysis.featurecontrol.FeaturePolicyLoader.java

/**
 * Evaluates, recursively, the given package group. Returns {@code null} in the case of missing
 * Skyframe dependencies.//from w  w w .ja v a2  s.  c o  m
 */
@Nullable
private static Iterable<PackageSpecification> getAllPackageSpecificationsForPackageGroup(
        ConfigurationEnvironment env, Label packageGroupLabel, String feature)
        throws InvalidConfigurationException, InterruptedException {
    String context = feature + " feature policy";
    Label actualPackageGroupLabel = RedirectChaser.followRedirects(env, packageGroupLabel, context);
    if (actualPackageGroupLabel == null) {
        return null;
    }

    ImmutableSet.Builder<PackageSpecification> packages = new ImmutableSet.Builder<>();
    Set<Label> alreadyVisitedPackageGroups = new LinkedHashSet<>();
    Queue<Label> packageGroupsToVisit = new ArrayDeque<>();
    packageGroupsToVisit.add(actualPackageGroupLabel);
    alreadyVisitedPackageGroups.add(actualPackageGroupLabel);

    while (!packageGroupsToVisit.isEmpty()) {
        Target target;
        try {
            // This is guaranteed to succeed, because the RedirectChaser was used to get this label,
            // and it will throw an InvalidConfigurationException if the target doesn't exist.
            target = env.getTarget(packageGroupsToVisit.remove());
        } catch (NoSuchPackageException | NoSuchTargetException impossible) {
            throw new AssertionError(impossible);
        }
        if (target == null) {
            return null;
        }

        if (!(target instanceof PackageGroup)) {
            throw new InvalidConfigurationException(
                    target.getLabel() + " is not a package_group in " + context);
        }

        PackageGroup packageGroup = (PackageGroup) target;

        packages.addAll(packageGroup.getPackageSpecifications());

        for (Label include : packageGroup.getIncludes()) {
            Label actualInclude = RedirectChaser.followRedirects(env, include, context);
            if (actualInclude == null) {
                return null;
            }

            if (alreadyVisitedPackageGroups.add(actualInclude)) {
                packageGroupsToVisit.add(actualInclude);
            }
        }
    }

    return packages.build();
}

From source file:org.caleydo.view.domino.api.model.typed.MultiTypedSet.java

@Override
public Set<TypedID> asInhomogenous() {
    if (ids instanceof Single)
        return new SingleTypedIDSet(((Single) ids).set);
    ImmutableSet.Builder<TypedID> b = ImmutableSet.builder();
    for (int i = 0; i < depth(); ++i) {
        IDType idType = idTypes[i];//  w  ww . j  a  va  2  s  .  c o  m
        // select just the slice and map to typed id
        b.addAll(Collections2.transform(ids, Functions.compose(TypedID.toTypedId(idType), slice(i))));
    }
    return b.build();
}

From source file:com.facebook.buck.features.rust.RustCompileRule.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext buildContext, BuildableContext buildableContext) {

    Path outputdir = getOutputDir(getBuildTarget(), getProjectFilesystem());
    Path output = getOutput();/*from   w  ww.  j  a  va2  s  . c  o m*/

    if (filename.isPresent()) {
        buildableContext.recordArtifact(output);
    }

    SourcePathResolver resolver = buildContext.getSourcePathResolver();

    Path argFilePath = getProjectFilesystem().getRootPath()
            .resolve(BuildTargetPaths.getScratchPath(getProjectFilesystem(), getBuildTarget(), "%s.argsfile"));
    Path fileListPath = getProjectFilesystem().getRootPath().resolve(
            BuildTargetPaths.getScratchPath(getProjectFilesystem(), getBuildTarget(), "%s__filelist.txt"));

    return new ImmutableList.Builder<Step>()
            .addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath.fromCellRelativePath(
                    buildContext.getBuildCellRootPath(), getProjectFilesystem(), scratchDir)))
            .add(new SymlinkFilesIntoDirectoryStep(getProjectFilesystem(), getProjectFilesystem().getRootPath(),
                    srcs.stream().map(resolver::getRelativePath).collect(ImmutableList.toImmutableList()),
                    scratchDir))
            .addAll(MakeCleanDirectoryStep
                    .of(BuildCellRelativePath.fromCellRelativePath(buildContext.getBuildCellRootPath(),
                            getProjectFilesystem(), getOutputDir(getBuildTarget(), getProjectFilesystem()))))
            .addAll(CxxPrepareForLinkStep.create(argFilePath, fileListPath, linker.fileList(fileListPath),
                    output, linkerArgs, linker, getBuildTarget().getCellPath(), resolver))
            .add(new ShellStep(getProjectFilesystem().getRootPath()) {

                @Override
                protected ImmutableList<String> getShellCommandInternal(ExecutionContext executionContext) {
                    ImmutableList<String> linkerCmd = linker.getCommandPrefix(resolver);
                    ImmutableList.Builder<String> cmd = ImmutableList.builder();

                    // Accumulate Args into set to dedup them while retaining their order,
                    // since there are often many duplicates for things like library paths.
                    //
                    // NOTE: this means that all logical args should be a single string on the command
                    // line (ie "-Lfoo", not ["-L", "foo"])
                    ImmutableSet.Builder<String> dedupArgs = ImmutableSet.builder();

                    dedupArgs.addAll(Arg.stringify(depArgs, buildContext.getSourcePathResolver()));

                    Path src = scratchDir.resolve(resolver.getRelativePath(rootModule));
                    cmd.addAll(compiler.getCommandPrefix(resolver));
                    if (executionContext.getAnsi().isAnsiTerminal()) {
                        cmd.add("--color=always");
                    }

                    remapSrcPaths.addRemapOption(cmd, workingDirectory.toString(), scratchDir + "/");

                    // Generate a target-unique string to distinguish distinct crates with the same
                    // name.
                    String metadata = RustCompileUtils.hashForTarget(RustCompileRule.this.getBuildTarget());

                    cmd.add(String.format("-Clinker=%s", linkerCmd.get(0)))
                            .add(String.format("-Clink-arg=@%s", argFilePath))
                            .add(String.format("-Cmetadata=%s", metadata))
                            .add(String.format("-Cextra-filename=-%s", metadata))
                            .addAll(Arg.stringify(args, buildContext.getSourcePathResolver()))
                            .addAll(dedupArgs.build()).add("--out-dir", outputdir.toString())
                            .add(src.toString());

                    return cmd.build();
                }

                /*
                 * Make sure all stderr output from rustc is emitted, since its either a warning or an
                 * error. In general Rust code should have zero warnings, or all warnings as errors.
                 * Regardless, respect requests for silence.
                 */
                @Override
                protected boolean shouldPrintStderr(Verbosity verbosity) {
                    return !verbosity.isSilent();
                }

                @Override
                public ImmutableMap<String, String> getEnvironmentVariables(ExecutionContext context) {
                    ImmutableMap.Builder<String, String> env = ImmutableMap.builder();
                    env.putAll(compiler.getEnvironment(buildContext.getSourcePathResolver()));

                    Path root = getProjectFilesystem().getRootPath();
                    Path basePath = getBuildTarget().getBasePath();

                    // These need to be set as absolute paths - the intended use
                    // is within an `include!(concat!(env!("..."), "...")`
                    // invocation in Rust source, and if the path isn't absolute
                    // it will be treated as relative to the current file including
                    // it. The trailing '/' is also to assist this use-case.
                    env.put("RUSTC_BUILD_CONTAINER", root.resolve(scratchDir) + "/");
                    env.put("RUSTC_BUILD_CONTAINER_BASE_PATH",
                            root.resolve(scratchDir.resolve(basePath)) + "/");

                    return env.build();
                }

                @Override
                public String getShortName() {
                    return "rust-build";
                }
            }).build();
}

From source file:com.hortonworks.streamline.streams.runtime.processor.RuleProcessorRuntime.java

private void buildStreamToRulesRuntime() {
    Map<String, List<RuleRuntime>> map = new HashMap<>();
    for (RuleRuntime rr : rulesRuntime) {
        for (String streamId : rr.getRule().getStreams()) {
            List<RuleRuntime> ruleRuntimes = map.get(streamId);
            if (ruleRuntimes == null) {
                ruleRuntimes = new ArrayList<>();
                map.put(streamId, ruleRuntimes);
            }/*from   w  ww  . ja v  a 2 s . c  o  m*/
            ruleRuntimes.add(rr);
        }
    }
    streamToRuleRuntimes = ImmutableMap.copyOf(map);
    ImmutableSet.Builder<RuleRuntime> builder = ImmutableSet.builder();
    for (List<RuleRuntime> ruleRuntimes : streamToRuleRuntimes.values()) {
        builder.addAll(ruleRuntimes);
    }
    allRuleRuntimes = builder.build().asList();
}

From source file:com.facebook.buck.features.go.GoDescriptors.java

static GoBinary createGoBinaryRule(BuildTarget buildTarget, ProjectFilesystem projectFilesystem,
        BuildRuleParams params, ActionGraphBuilder graphBuilder, GoBuckConfig goBuckConfig,
        Linker.LinkableDepType linkStyle, Optional<GoLinkStep.LinkMode> linkMode, ImmutableSet<SourcePath> srcs,
        ImmutableSortedSet<SourcePath> resources, List<String> compilerFlags, List<String> assemblerFlags,
        List<String> linkerFlags, List<String> externalLinkerFlags, GoPlatform platform) {

    ImmutableList.Builder<BuildRule> extraDeps = ImmutableList.builder();

    GoCompile library = GoDescriptors.createGoCompileRule(
            buildTarget.withAppendedFlavors(InternalFlavor.of("compile"), platform.getFlavor()),
            projectFilesystem, params, graphBuilder, goBuckConfig, Paths.get("main"), srcs, compilerFlags,
            assemblerFlags, platform,//from w ww  .  j  av a  2s  .c  o m
            params.getDeclaredDeps().get().stream().map(BuildRule::getBuildTarget)
                    .collect(ImmutableList.toImmutableList()),
            ImmutableList.of(), Collections.singletonList(ListType.GoFiles));
    graphBuilder.addToIndex(library);
    extraDeps.add(library);

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
    BuildTarget target = createTransitiveSymlinkTreeTarget(buildTarget);
    SymlinkTree symlinkTree = makeSymlinkTree(target, projectFilesystem, ruleFinder, pathResolver,
            requireTransitiveGoLinkables(
                    buildTarget, graphBuilder, platform, params.getDeclaredDeps().get().stream()
                            .map(BuildRule::getBuildTarget).collect(ImmutableList.toImmutableList()),
                    /* includeSelf */ false));
    graphBuilder.addToIndex(symlinkTree);
    extraDeps.add(symlinkTree);

    LOG.verbose("Symlink tree for linking of %s: %s", buildTarget, symlinkTree);

    // find all the CGoLibraries being in direct or non direct dependency to
    // declared deps
    Iterable<BuildRule> cgoLinkables = getCgoLinkableDeps(library.getBuildDeps());
    ImmutableSet.Builder<String> extraFlags = ImmutableSet.builder();

    if (linkStyle == Linker.LinkableDepType.SHARED) {
        // Create a symlink tree with for all shared libraries needed by this binary.
        SymlinkTree sharedLibraries = graphBuilder.addToIndex(CxxDescriptionEnhancer
                .createSharedLibrarySymlinkTree(buildTarget, projectFilesystem, graphBuilder, ruleFinder,
                        platform.getCxxPlatform(), cgoLinkables, r -> Optional.empty()));
        extraDeps.add(sharedLibraries);

        // 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 absBinaryDir = buildTarget.getCellPath()
                .resolve(BuildTargetPaths.getGenPath(projectFilesystem, buildTarget, "%s"));

        extraFlags.addAll(Linkers.iXlinker("-rpath",
                String.format("%s/%s", platform.getCxxPlatform().getLd().resolve(graphBuilder).origin(),
                        absBinaryDir.relativize(sharedLibraries.getRoot()).toString())));
    }

    ImmutableList<Arg> cxxLinkerArgs = getCxxLinkerArgs(graphBuilder, platform.getCxxPlatform(), cgoLinkables,
            linkStyle, StringArg.from(Iterables.concat(platform.getExternalLinkerFlags(), extraFlags.build(),
                    externalLinkerFlags)));

    // collect build rules from args (required otherwise referenced sources
    // won't build before linking)
    for (Arg arg : cxxLinkerArgs) {
        if (HasSourcePath.class.isInstance(arg)) {
            SourcePath pth = ((HasSourcePath) arg).getPath();
            extraDeps.addAll(ruleFinder.filterBuildRuleInputs(pth));
        }
    }

    if (!linkMode.isPresent()) {
        linkMode = Optional
                .of((cxxLinkerArgs.size() > 0) ? GoLinkStep.LinkMode.EXTERNAL : GoLinkStep.LinkMode.INTERNAL);
    }

    Linker cxxLinker = platform.getCxxPlatform().getLd().resolve(graphBuilder);
    return new GoBinary(buildTarget, projectFilesystem,
            params.withDeclaredDeps(ImmutableSortedSet.<BuildRule>naturalOrder()
                    .addAll(ruleFinder.filterBuildRuleInputs(symlinkTree.getLinks().values()))
                    .addAll(extraDeps.build()).addAll(BuildableSupport.getDepsCollection(cxxLinker, ruleFinder))
                    .build()).withoutExtraDeps(),
            resources, symlinkTree, library, platform.getLinker(), cxxLinker, linkMode.get(),
            ImmutableList.copyOf(linkerFlags), cxxLinkerArgs, platform);
}