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

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

Introduction

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

Prototype

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

Source Link

Document

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).

Usage

From source file:com.facebook.buck.apple.AppleCxxPlatforms.java

@VisibleForTesting
static AppleCxxPlatform buildWithExecutableChecker(ProjectFilesystem filesystem, AppleSdk targetSdk,
        String minVersion, String targetArchitecture, final AppleSdkPaths sdkPaths, BuckConfig buckConfig,
        AppleConfig appleConfig, ExecutableFinder executableFinder, Optional<ProcessExecutor> processExecutor,
        Optional<AppleToolchain> swiftToolChain) {
    AppleCxxPlatform.Builder platformBuilder = AppleCxxPlatform.builder();

    ImmutableList.Builder<Path> toolSearchPathsBuilder = ImmutableList.builder();
    // Search for tools from most specific to least specific.
    toolSearchPathsBuilder.add(sdkPaths.getSdkPath().resolve(USR_BIN))
            .add(sdkPaths.getSdkPath().resolve("Developer").resolve(USR_BIN))
            .add(sdkPaths.getPlatformPath().resolve("Developer").resolve(USR_BIN));
    for (Path toolchainPath : sdkPaths.getToolchainPaths()) {
        toolSearchPathsBuilder.add(toolchainPath.resolve(USR_BIN));
    }//from  w  w w. ja v a  2  s. com
    if (sdkPaths.getDeveloperPath().isPresent()) {
        toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve(USR_BIN));
        toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve("Tools"));
    }

    // TODO(bhamiltoncx): Add more and better cflags.
    ImmutableList.Builder<String> cflagsBuilder = ImmutableList.builder();
    cflagsBuilder.add("-isysroot", sdkPaths.getSdkPath().toString());
    cflagsBuilder.add("-arch", targetArchitecture);
    cflagsBuilder.add(targetSdk.getApplePlatform().getMinVersionFlagPrefix() + minVersion);

    if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) {
        cflagsBuilder.add("-fembed-bitcode");
    }

    ImmutableList.Builder<String> ldflagsBuilder = ImmutableList.builder();
    ldflagsBuilder.addAll(Linkers.iXlinker("-sdk_version", targetSdk.getVersion(), "-ObjC"));
    if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) {
        ldflagsBuilder
                .addAll(Linkers.iXlinker("-bitcode_verify", "-bitcode_hide_symbols", "-bitcode_symbol_map"));
    }

    // Populate Xcode version keys from Xcode's own Info.plist if available.
    Optional<String> xcodeBuildVersion = Optional.empty();
    Optional<Path> developerPath = sdkPaths.getDeveloperPath();
    if (developerPath.isPresent()) {
        Path xcodeBundlePath = developerPath.get().getParent();
        if (xcodeBundlePath != null) {
            File xcodeInfoPlistPath = xcodeBundlePath.resolve("Info.plist").toFile();
            try {
                NSDictionary parsedXcodeInfoPlist = (NSDictionary) PropertyListParser.parse(xcodeInfoPlistPath);

                NSObject xcodeVersionObject = parsedXcodeInfoPlist.objectForKey("DTXcode");
                if (xcodeVersionObject != null) {
                    Optional<String> xcodeVersion = Optional.of(xcodeVersionObject.toString());
                    platformBuilder.setXcodeVersion(xcodeVersion);
                }
            } catch (IOException e) {
                LOG.debug("Error reading Xcode's info plist %s; ignoring Xcode versions", xcodeInfoPlistPath);
            } catch (PropertyListFormatException | ParseException | ParserConfigurationException
                    | SAXException e) {
                LOG.debug("Error in parsing %s; ignoring Xcode versions", xcodeInfoPlistPath);
            }
        }

        // Get the Xcode build version as reported by `xcodebuild -version`.  This is
        // different than the build number in the Info.plist, sigh.
        if (processExecutor.isPresent()) {
            xcodeBuildVersion = appleConfig
                    .getXcodeBuildVersionSupplier(developerPath.get(), processExecutor.get()).get();
            platformBuilder.setXcodeBuildVersion(xcodeBuildVersion);
            LOG.debug("Xcode build version is: " + xcodeBuildVersion.orElse("<absent>"));
        }
    }

    ImmutableList.Builder<String> versions = ImmutableList.builder();
    versions.add(targetSdk.getVersion());

    ImmutableList<String> toolchainVersions = targetSdk.getToolchains().stream().map(AppleToolchain::getVersion)
            .flatMap(Optionals::toStream).collect(MoreCollectors.toImmutableList());
    if (toolchainVersions.isEmpty()) {
        if (!xcodeBuildVersion.isPresent()) {
            throw new HumanReadableException("Failed to read toolchain versions and Xcode version.");
        }
        versions.add(xcodeBuildVersion.get());
    } else {
        versions.addAll(toolchainVersions);
    }

    String version = Joiner.on(':').join(versions.build());

    ImmutableList<Path> toolSearchPaths = toolSearchPathsBuilder.build();

    Tool clangPath = VersionedTool.of(getToolPath("clang", toolSearchPaths, executableFinder), "apple-clang",
            version);

    Tool clangXxPath = VersionedTool.of(getToolPath("clang++", toolSearchPaths, executableFinder),
            "apple-clang++", version);

    Tool ar = VersionedTool.of(getToolPath("ar", toolSearchPaths, executableFinder), "apple-ar", version);

    Tool ranlib = VersionedTool.builder().setPath(getToolPath("ranlib", toolSearchPaths, executableFinder))
            .setName("apple-ranlib").setVersion(version).build();

    Tool strip = VersionedTool.of(getToolPath("strip", toolSearchPaths, executableFinder), "apple-strip",
            version);

    Tool nm = VersionedTool.of(getToolPath("nm", toolSearchPaths, executableFinder), "apple-nm", version);

    Tool actool = VersionedTool.of(getToolPath("actool", toolSearchPaths, executableFinder), "apple-actool",
            version);

    Tool ibtool = VersionedTool.of(getToolPath("ibtool", toolSearchPaths, executableFinder), "apple-ibtool",
            version);

    Tool momc = VersionedTool.of(getToolPath("momc", toolSearchPaths, executableFinder), "apple-momc", version);

    Tool xctest = VersionedTool.of(getToolPath("xctest", toolSearchPaths, executableFinder), "apple-xctest",
            version);

    Tool dsymutil = VersionedTool.of(getToolPath("dsymutil", toolSearchPaths, executableFinder),
            "apple-dsymutil", version);

    Tool lipo = VersionedTool.of(getToolPath("lipo", toolSearchPaths, executableFinder), "apple-lipo", version);

    Tool lldb = VersionedTool.of(getToolPath("lldb", toolSearchPaths, executableFinder), "lldb", version);

    Optional<Path> stubBinaryPath = targetSdk.getApplePlatform().getStubBinaryPath()
            .map(input -> sdkPaths.getSdkPath().resolve(input));

    CxxBuckConfig config = new CxxBuckConfig(buckConfig);

    ImmutableFlavor targetFlavor = ImmutableFlavor
            .of(ImmutableFlavor.replaceInvalidCharacters(targetSdk.getName() + "-" + targetArchitecture));

    ImmutableBiMap.Builder<Path, Path> sanitizerPaths = ImmutableBiMap.builder();
    sanitizerPaths.put(sdkPaths.getSdkPath(), Paths.get("APPLE_SDKROOT"));
    sanitizerPaths.put(sdkPaths.getPlatformPath(), Paths.get("APPLE_PLATFORM_DIR"));
    if (sdkPaths.getDeveloperPath().isPresent()) {
        sanitizerPaths.put(sdkPaths.getDeveloperPath().get(), Paths.get("APPLE_DEVELOPER_DIR"));
    }

    DebugPathSanitizer compilerDebugPathSanitizer = new PrefixMapDebugPathSanitizer(
            config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizerPaths.build(),
            filesystem.getRootPath().toAbsolutePath(), CxxToolProvider.Type.CLANG);
    DebugPathSanitizer assemblerDebugPathSanitizer = new MungingDebugPathSanitizer(
            config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizerPaths.build());

    ImmutableList<String> cflags = cflagsBuilder.build();

    ImmutableMap.Builder<String, String> macrosBuilder = ImmutableMap.builder();
    macrosBuilder.put("SDKROOT", sdkPaths.getSdkPath().toString());
    macrosBuilder.put("PLATFORM_DIR", sdkPaths.getPlatformPath().toString());
    macrosBuilder.put("CURRENT_ARCH", targetArchitecture);
    if (sdkPaths.getDeveloperPath().isPresent()) {
        macrosBuilder.put("DEVELOPER_DIR", sdkPaths.getDeveloperPath().get().toString());
    }
    ImmutableMap<String, String> macros = macrosBuilder.build();

    Optional<String> buildVersion = Optional.empty();
    Path platformVersionPlistPath = sdkPaths.getPlatformPath().resolve("version.plist");
    try (InputStream versionPlist = Files.newInputStream(platformVersionPlistPath)) {
        NSDictionary versionInfo = (NSDictionary) PropertyListParser.parse(versionPlist);
        if (versionInfo != null) {
            NSObject productBuildVersion = versionInfo.objectForKey("ProductBuildVersion");
            if (productBuildVersion != null) {
                buildVersion = Optional.of(productBuildVersion.toString());
            } else {
                LOG.warn("In %s, missing ProductBuildVersion. Build version will be unset for this platform.",
                        platformVersionPlistPath);
            }
        } else {
            LOG.warn("Empty version plist in %s. Build version will be unset for this platform.",
                    platformVersionPlistPath);
        }
    } catch (NoSuchFileException e) {
        LOG.warn("%s does not exist. Build version will be unset for this platform.", platformVersionPlistPath);
    } catch (PropertyListFormatException | SAXException | ParserConfigurationException | ParseException
            | IOException e) {
        // Some other error occurred, print the exception since it may contain error details.
        LOG.warn(e, "Failed to parse %s. Build version will be unset for this platform.",
                platformVersionPlistPath);
    }

    PreprocessorProvider aspp = new PreprocessorProvider(new ConstantToolProvider(clangPath),
            CxxToolProvider.Type.CLANG);
    CompilerProvider as = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG);
    PreprocessorProvider cpp = new PreprocessorProvider(new ConstantToolProvider(clangPath),
            CxxToolProvider.Type.CLANG);
    CompilerProvider cc = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG);
    PreprocessorProvider cxxpp = new PreprocessorProvider(new ConstantToolProvider(clangXxPath),
            CxxToolProvider.Type.CLANG);
    CompilerProvider cxx = new CompilerProvider(new ConstantToolProvider(clangXxPath),
            CxxToolProvider.Type.CLANG);
    ImmutableList.Builder<String> whitelistBuilder = ImmutableList.builder();
    whitelistBuilder.add("^" + Pattern.quote(sdkPaths.getSdkPath().toString()) + "\\/.*");
    for (Path toolchainPath : sdkPaths.getToolchainPaths()) {
        whitelistBuilder.add("^" + Pattern.quote(toolchainPath.toString()) + "\\/.*");
    }
    HeaderVerification headerVerification = config.getHeaderVerification()
            .withAdditionalWhitelist(whitelistBuilder.build());

    CxxPlatform cxxPlatform = CxxPlatforms.build(targetFlavor, Platform.MACOS, config, as, aspp, cc, cxx, cpp,
            cxxpp, new DefaultLinkerProvider(LinkerProvider.Type.DARWIN, new ConstantToolProvider(clangXxPath)),
            ImmutableList.<String>builder().addAll(cflags).addAll(ldflagsBuilder.build()).build(), strip,
            new BsdArchiver(ar), ranlib, new PosixNmSymbolNameTool(nm), cflagsBuilder.build(),
            ImmutableList.of(), cflags, ImmutableList.of(), "dylib", "%s.dylib", "a", "o",
            compilerDebugPathSanitizer, assemblerDebugPathSanitizer, macros, Optional.empty(),
            headerVerification);

    ApplePlatform applePlatform = targetSdk.getApplePlatform();
    ImmutableList.Builder<Path> swiftOverrideSearchPathBuilder = ImmutableList.builder();
    AppleSdkPaths.Builder swiftSdkPathsBuilder = AppleSdkPaths.builder().from(sdkPaths);
    if (swiftToolChain.isPresent()) {
        swiftOverrideSearchPathBuilder.add(swiftToolChain.get().getPath().resolve(USR_BIN));
        swiftSdkPathsBuilder.setToolchainPaths(ImmutableList.of(swiftToolChain.get().getPath()));
    }
    Optional<SwiftPlatform> swiftPlatform = getSwiftPlatform(applePlatform.getName(),
            targetArchitecture + "-apple-" + applePlatform.getSwiftName().orElse(applePlatform.getName())
                    + minVersion,
            version, swiftSdkPathsBuilder.build(),
            swiftOverrideSearchPathBuilder.addAll(toolSearchPaths).build(), executableFinder);

    platformBuilder.setCxxPlatform(cxxPlatform).setSwiftPlatform(swiftPlatform).setAppleSdk(targetSdk)
            .setAppleSdkPaths(sdkPaths).setMinVersion(minVersion).setBuildVersion(buildVersion)
            .setActool(actool).setIbtool(ibtool).setMomc(momc)
            .setCopySceneKitAssets(
                    getOptionalTool("copySceneKitAssets", toolSearchPaths, executableFinder, version))
            .setXctest(xctest).setDsymutil(dsymutil).setLipo(lipo).setStubBinary(stubBinaryPath).setLldb(lldb)
            .setCodesignAllocate(
                    getOptionalTool("codesign_allocate", toolSearchPaths, executableFinder, version));

    return platformBuilder.build();
}

From source file:com.github.rinde.rinsim.scenario.measure.Metrics.java

static ImmutableList<Double> measureLoad(Scenario s, int numVehicles) {
    final TravelTimes tt = ScenarioGenerator.createTravelTimes(s);
    final ImmutableList.Builder<LoadPart> loadParts = ImmutableList.builder();
    for (final TimedEvent te : s.getEvents()) {
        if (te instanceof AddParcelEvent) {
            loadParts.addAll(measureLoad((AddParcelEvent) te, tt));
        }/*from  ww  w.  j a v a2 s.  c  o m*/
    }
    return sum(0, loadParts.build(), numVehicles);
}

From source file:org.apache.calcite.rel.metadata.RelMdCollation.java

/** Helper method to determine a {@link Join}'s collation assuming that it
 * uses a merge-join algorithm.//from   www  .  j  a  v  a2 s .c o m
 *
 * <p>If the inputs are sorted on other keys <em>in addition to</em> the join
 * key, the result preserves those collations too. */
public static List<RelCollation> mergeJoin(RelMetadataQuery mq, RelNode left, RelNode right,
        ImmutableIntList leftKeys, ImmutableIntList rightKeys) {
    final ImmutableList.Builder<RelCollation> builder = ImmutableList.builder();

    final ImmutableList<RelCollation> leftCollations = mq.collations(left);
    assert RelCollations.contains(leftCollations,
            leftKeys) : "cannot merge join: left input is not sorted on left keys";
    builder.addAll(leftCollations);

    final ImmutableList<RelCollation> rightCollations = mq.collations(right);
    assert RelCollations.contains(rightCollations,
            rightKeys) : "cannot merge join: right input is not sorted on right keys";
    final int leftFieldCount = left.getRowType().getFieldCount();
    for (RelCollation collation : rightCollations) {
        builder.add(RelCollations.shift(collation, leftFieldCount));
    }
    return builder.build();
}

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

/** Collects all .dwo artifacts in this target's transitive closure. */
public static DwoArtifactsCollector collectTransitiveDwoArtifacts(RuleContext ruleContext,
        CcCompilationOutputs compilationOutputs, boolean generateDwo, boolean ltoBackendArtifactsUsePic,
        Iterable<LTOBackendArtifacts> ltoBackendArtifacts) {
    ImmutableList.Builder<TransitiveInfoCollection> deps = ImmutableList.<TransitiveInfoCollection>builder();

    deps.addAll(ruleContext.getPrerequisites("deps", Mode.TARGET));

    if (ruleContext.attributes().has("malloc", BuildType.LABEL)) {
        deps.add(CppHelper.mallocForTarget(ruleContext));
    }/*from   w w w . j  a  va 2s .  c  om*/

    return compilationOutputs == null // Possible in LIPO collection mode (see initializationHook).
            ? DwoArtifactsCollector.emptyCollector()
            : DwoArtifactsCollector.transitiveCollector(ruleContext, compilationOutputs, deps.build(),
                    generateDwo, ltoBackendArtifactsUsePic, ltoBackendArtifacts);
}

From source file:de.flapdoodle.guava.Merger.java

public static <T> ImmutableList<T> merge(Iterable<? extends T> left, Iterable<? extends T> right,
        Equivalence<? super T> matcher, Foldleft<? super T, T> fold) {
    ImmutableList.Builder<T> builder = ImmutableList.builder();
    Iterable<? extends T> notMerged = right;
    for (T l : left) {
        Iterable<? extends T> matching = Iterables.filter(notMerged, matcher.equivalentTo(l));
        notMerged = Iterables.filter(notMerged, Predicates.not(matcher.equivalentTo(l)));

        boolean noMatching = true;
        for (T r : matching) {
            builder.add(fold.apply(l, r));
            noMatching = false;//w w  w .  j a v  a 2s.co m
        }
        if (noMatching) {
            builder.add(l);
        }
    }
    builder.addAll(notMerged);
    return builder.build();
}

From source file:com.google.devtools.build.lib.rules.objc.ExperimentalObjcLibrary.java

private static FeatureConfiguration getFeatureConfiguration(RuleContext ruleContext) {
    CcToolchainProvider toolchain = ruleContext.getPrerequisite(":cc_toolchain", Mode.TARGET)
            .getProvider(CcToolchainProvider.class);

    ImmutableList.Builder<String> activatedCrosstoolSelectables = ImmutableList.<String>builder()
            .addAll(ACTIVATED_ACTIONS);/*from  w  w w. j  a  v a2  s . co  m*/

    if (ruleContext.getPrerequisiteArtifact("pch", Mode.TARGET) != null) {
        activatedCrosstoolSelectables.add("pch");
    }

    if (ObjcCommon.shouldUseObjcModules(ruleContext)) {
        activatedCrosstoolSelectables.add(OBJC_MODULE_FEATURE_NAME);
    }

    activatedCrosstoolSelectables
            .addAll(ruleContext.getFragment(AppleConfiguration.class).getBitcodeMode().getFeatureNames());

    // We create a module map by default to allow for swift interop.
    activatedCrosstoolSelectables.add(CppRuleClasses.MODULE_MAPS);
    activatedCrosstoolSelectables.add(CppRuleClasses.COMPILE_ACTION_FLAGS_IN_FLAG_SET);
    activatedCrosstoolSelectables.add(CppRuleClasses.DEPENDENCY_FILE);
    activatedCrosstoolSelectables.add(CppRuleClasses.INCLUDE_PATHS);

    return toolchain.getFeatures().getFeatureConfiguration(activatedCrosstoolSelectables.build());
}

From source file:com.spectralogic.ds3autogen.java.generators.requestmodels.BaseRequestGenerator.java

/**
 * Takes a list of constructors and splits all constructors containing at least one UUID into two
 * constructors: an original, and a constructor where all UUIDs are replaced with String type.
 *///w  ww .ja  v a  2  s.  com
protected static ImmutableList<RequestConstructor> splitAllUuidConstructors(
        final ImmutableList<RequestConstructor> constructors) {
    if (isEmpty(constructors)) {
        return ImmutableList.of();
    }
    final ImmutableList.Builder<RequestConstructor> builder = ImmutableList.builder();
    for (final RequestConstructor constructor : constructors) {
        builder.addAll(splitUuidConstructor(constructor));
    }
    return builder.build();
}

From source file:com.google.devtools.build.xcode.xcodegen.XcodeprojGeneration.java

private static ImmutableList<String> otherLdflags(TargetControl targetControl) {
    Iterable<String> givenFlags = targetControl.getLinkoptList();
    ImmutableList.Builder<String> flags = new ImmutableList.Builder<>();
    flags.addAll(givenFlags);
    if (Containing.item(PRODUCT_TYPES_THAT_HAVE_A_BINARY, productType(targetControl))) {
        for (String dylib : targetControl.getSdkDylibList()) {
            if (dylib.startsWith("lib")) {
                dylib = dylib.substring(3);
            }/* w ww  .ja v a 2 s. c  om*/
            flags.add("-l" + dylib);
        }
    }

    return flags.build();
}

From source file:com.facebook.buck.util.MoreIterables.java

/**
 * Combine the given iterables by peeling off items one at a time from each of the input
 * iterables until any one of the iterables are exhausted.
 *///from w w w . j  a  v a 2  s  .  c o  m
@SafeVarargs
public static <T> Iterable<T> zipAndConcat(Iterable<T>... inputs) {

    // If no inputs were seen, just return an empty list.
    if (inputs.length == 0) {
        return ImmutableList.of();
    }

    ImmutableList.Builder<T> result = ImmutableList.builder();
    ImmutableList<Iterator<T>> iterators = iterators(inputs);

    // Keep grabbing rounds from the input iterators until we've exhausted one
    // of them, then return.
    List<T> round = Lists.newArrayListWithCapacity(inputs.length);
    while (true) {
        for (Iterator<T> iterator : iterators) {
            if (!iterator.hasNext()) {
                return result.build();
            }
            round.add(iterator.next());
        }
        result.addAll(round);
        round.clear();
    }
}

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

public static CxxPreprocessorInput concat(Iterable<CxxPreprocessorInput> inputs) {
    ImmutableSet.Builder<BuildTarget> rules = ImmutableSet.builder();
    ImmutableMultimap.Builder<CxxSource.Type, String> preprocessorFlags = ImmutableMultimap.builder();
    ImmutableCxxHeaders.Builder includes = ImmutableCxxHeaders.builder();
    ImmutableList.Builder<Path> includeRoots = ImmutableList.builder();
    ImmutableList.Builder<Path> systemIncludeRoots = ImmutableList.builder();

    for (CxxPreprocessorInput input : inputs) {
        rules.addAll(input.getRules());//from   w w w  . j av a  2 s. c o m
        preprocessorFlags.putAll(input.getPreprocessorFlags());
        includes.putAllNameToPathMap(input.getIncludes().nameToPathMap());
        includes.putAllFullNameToPathMap(input.getIncludes().fullNameToPathMap());
        includeRoots.addAll(input.getIncludeRoots());
        systemIncludeRoots.addAll(input.getSystemIncludeRoots());
    }

    return new CxxPreprocessorInput(rules.build(), preprocessorFlags.build(), includes.build(),
            includeRoots.build(), systemIncludeRoots.build());
}