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:edu.jhu.hlt.tift.TwitterTokenizer.java

private static List<TokenTagTuple> concatAll(List<List<TokenTagTuple>> arrays) {
    ImmutableList.Builder<TokenTagTuple> ttlb = new ImmutableList.Builder<>();
    for (List<TokenTagTuple> array : arrays)
        ttlb.addAll(array);

    return ttlb.build();
}

From source file:com.google.devtools.build.lib.rules.android.NativeLibs.java

public static NativeLibs fromLinkedNativeDeps(RuleContext ruleContext, String nativeDepsFileName,
        Multimap<String, TransitiveInfoCollection> depsByArchitecture,
        Map<String, CcToolchainProvider> toolchainMap, Map<String, BuildConfiguration> configurationMap)
        throws InterruptedException {
    Map<String, Iterable<Artifact>> result = new LinkedHashMap<>();
    String nativeDepsLibraryBasename = null;
    for (Map.Entry<String, Collection<TransitiveInfoCollection>> entry : depsByArchitecture.asMap()
            .entrySet()) {/*w  ww.j a  v  a2s  .c  om*/
        CcLinkParams linkParams = AndroidCommon
                .getCcLinkParamsStore(entry.getValue(),
                        ImmutableList.of("-Wl,-soname=lib" + ruleContext.getLabel().getName()))
                .get(/* linkingStatically */ true, /* linkShared */ true);

        Artifact nativeDepsLibrary = NativeDepsHelper.linkAndroidNativeDepsIfPresent(ruleContext, linkParams,
                configurationMap.get(entry.getKey()), toolchainMap.get(entry.getKey()));

        ImmutableList.Builder<Artifact> librariesBuilder = ImmutableList.builder();
        if (nativeDepsLibrary != null) {
            librariesBuilder.add(nativeDepsLibrary);
            nativeDepsLibraryBasename = nativeDepsLibrary.getExecPath().getBaseName();
        }
        librariesBuilder
                .addAll(filterUniqueSharedLibraries(ruleContext, nativeDepsLibrary, linkParams.getLibraries()));
        ImmutableList<Artifact> libraries = librariesBuilder.build();

        if (!libraries.isEmpty()) {
            result.put(entry.getKey(), libraries);
        }
    }
    if (result.isEmpty()) {
        return NativeLibs.EMPTY;
    } else if (nativeDepsLibraryBasename == null) {
        return new NativeLibs(ImmutableMap.copyOf(result), null);
    } else {
        // The native deps name file must be the only file in its directory because ApkBuilder does
        // not have an option to add a particular file to the .apk, only one to add every file in a
        // particular directory.
        Artifact nativeDepsName = ruleContext.getUniqueDirectoryArtifact("nativedeps_filename",
                nativeDepsFileName, ruleContext.getBinOrGenfilesDirectory());
        ruleContext.registerAction(
                FileWriteAction.create(ruleContext, nativeDepsName, nativeDepsLibraryBasename, false));

        return new NativeLibs(ImmutableMap.copyOf(result), nativeDepsName);
    }
}

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

@VisibleForTesting
static ImmutableMap<Path, Path> getPackageImportMap(ImmutableList<Path> globalVendorPaths, Path basePackagePath,
        Iterable<Path> packageNameIter) {
    Map<Path, Path> importMapBuilder = new HashMap<>();
    ImmutableSortedSet<Path> packageNames = ImmutableSortedSet.copyOf(packageNameIter);

    ImmutableList.Builder<Path> vendorPathsBuilder = ImmutableList.builder();
    vendorPathsBuilder.addAll(globalVendorPaths);
    Path prefix = Paths.get("");
    for (Path component : FluentIterable.from(new Path[] { Paths.get("") }).append(basePackagePath)) {
        prefix = prefix.resolve(component);
        vendorPathsBuilder.add(prefix.resolve("vendor"));
    }//w  ww.  ja v a  2s  .co  m

    for (Path vendorPrefix : vendorPathsBuilder.build()) {
        for (Path vendoredPackage : packageNames.tailSet(vendorPrefix)) {
            if (!vendoredPackage.startsWith(vendorPrefix)) {
                break;
            }

            importMapBuilder.put(MorePaths.relativize(vendorPrefix, vendoredPackage), vendoredPackage);
        }
    }

    return ImmutableMap.copyOf(importMapBuilder);
}

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

public static BinaryWrapperRule createBinaryBuildRule(BuildRuleParams params, BuildRuleResolver resolver,
        RustBuckConfig rustBuckConfig, FlavorDomain<CxxPlatform> cxxPlatforms, CxxPlatform defaultCxxPlatform,
        Optional<String> crateName, ImmutableSortedSet<String> features, Iterator<String> rustcFlags,
        Iterator<String> linkerFlags, Linker.LinkableDepType linkStyle, boolean rpath,
        ImmutableSortedSet<SourcePath> srcs, Optional<SourcePath> crateRoot, ImmutableSet<String> defaultRoots)
        throws NoSuchBuildTargetException {
    final BuildTarget buildTarget = params.getBuildTarget();
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);

    ImmutableList.Builder<String> rustcArgs = ImmutableList.builder();

    RustCompileUtils.addFeatures(buildTarget, features, rustcArgs);

    rustcArgs.addAll(rustcFlags);

    ImmutableList.Builder<String> linkerArgs = ImmutableList.builder();
    linkerArgs.addAll(linkerFlags);//w  w  w  .j av a 2  s.c o  m

    String crate = crateName.orElse(ruleToCrateName(buildTarget.getShortName()));

    Optional<SourcePath> rootModule = RustCompileUtils.getCrateRoot(pathResolver, crate, crateRoot,
            defaultRoots, srcs.stream());

    if (!rootModule.isPresent()) {
        throw new HumanReadableException("Can't find suitable top-level source file for %s",
                buildTarget.getShortName());
    }

    CxxPlatform cxxPlatform = cxxPlatforms.getValue(params.getBuildTarget()).orElse(defaultCxxPlatform);

    // The target to use for the link rule.
    BuildTarget binaryTarget = params.getBuildTarget().withAppendedFlavors(cxxPlatform.getFlavor(),
            RustDescriptionEnhancer.RFBIN);

    CommandTool.Builder executableBuilder = new CommandTool.Builder();

    // Add the binary as the first argument.
    executableBuilder.addArg(new SourcePathArg(pathResolver, new BuildTargetSourcePath(binaryTarget)));

    // 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 = resolver.addToIndex(
                CxxDescriptionEnhancer.createSharedLibrarySymlinkTree(params, pathResolver, cxxPlatform,
                        params.getDeps(), RustLinkable.class::isInstance, RustLinkable.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 absBinaryDir = params.getBuildTarget().getCellPath()
                .resolve(RustCompileRule.getOutputDir(binaryTarget, params.getProjectFilesystem()));
        linkerArgs.addAll(Linkers.iXlinker("-rpath",
                String.format("%s/%s", cxxPlatform.getLd().resolve(resolver).origin(),
                        absBinaryDir.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());
    }

    final CommandTool executable = executableBuilder.build();

    final RustCompileRule buildRule = RustCompileUtils.createBuild(binaryTarget, crate, params, resolver,
            pathResolver, ruleFinder, cxxPlatform, rustBuckConfig, rustcArgs.build(), linkerArgs.build(),
            /* linkerInputs */ ImmutableList.of(), CrateType.BIN, linkStyle, rpath, srcs, rootModule.get());

    return new BinaryWrapperRule(params.appendExtraDeps(buildRule), pathResolver, ruleFinder) {

        @Override
        public Tool getExecutableCommand() {
            return executable;
        }

        @Override
        public Path getPathToOutput() {
            return buildRule.getPathToOutput();
        }

    };
}

From source file:com.android.tools.idea.editors.theme.MaterialColorUtils.java

/**
 * Method that suggests accent colors for a given primary color based on the material guidelines and classical color theory
 * <a href="http://www.tigercolor.com/color-lab/color-theory/color-harmonies.htm">Complementary, Analogous and Triad combinations</a>
 * <a href="https://en.wikipedia.org/wiki/Monochromatic_color">Monochromatic colors</a>
 * For each hue (complementary, analogous, triad or monochromatic), two colors are suggested as accents:
 * <ul>/*w w w. j ava 2s.c o  m*/
 * <li>75% saturation and 100% brightness</li>
 * <li>100% saturation and original brightness of the color</li>
 * </ul>
 */
@NotNull
public static List<Color> suggestAccentColors(@NotNull Color primaryColor) {
    ImmutableList.Builder<Color> builder = ImmutableList.builder();
    if (AccentSuggestionsUtils.isMaterialPrimary(primaryColor)) {
        builder.addAll(AccentSuggestionsUtils.getMonochromaticAccents(primaryColor));
        builder.addAll(AccentSuggestionsUtils.getAssociatedAccents(primaryColor));
        builder.addAll(AccentSuggestionsUtils.getComplementaryAccents(primaryColor));
        builder.addAll(AccentSuggestionsUtils.getTriadAccents(primaryColor));
    } else {
        float[] hsv = Color.RGBtoHSB(primaryColor.getRed(), primaryColor.getGreen(), primaryColor.getBlue(),
                null);

        // If the primaryColor's brightness is too low, we set it to a higher value (0.6) to have a bright accent color
        hsv[2] = Math.max(0.6f, hsv[2]);

        // Monochromatic
        builder.add(Color.getHSBColor(hsv[0], 0.75f, 1));
        builder.add(Color.getHSBColor(hsv[0], 1, hsv[2]));
        // Analogous
        float associatedHue1 = (hsv[0] + 0.125f) % 1;
        builder.add(Color.getHSBColor(associatedHue1, 0.75f, 1));
        builder.add(Color.getHSBColor(associatedHue1, 1, hsv[2]));
        float associatedHue2 = (hsv[0] + 0.875f) % 1;
        builder.add(Color.getHSBColor(associatedHue2, 0.75f, 1));
        builder.add(Color.getHSBColor(associatedHue2, 1, hsv[2]));
        // Complementary
        float complementaryHue = (hsv[0] + 0.5f) % 1;
        builder.add(Color.getHSBColor(complementaryHue, 0.75f, 1));
        builder.add(Color.getHSBColor(complementaryHue, 1, hsv[2]));
        // Triad
        float triadHue1 = (hsv[0] + 0.625f) % 1;
        builder.add(Color.getHSBColor(triadHue1, 0.75f, 1));
        builder.add(Color.getHSBColor(triadHue1, 1, hsv[2]));
        float triadHue2 = (hsv[0] + 0.375f) % 1;
        builder.add(Color.getHSBColor(triadHue2, 0.75f, 1));
        builder.add(Color.getHSBColor(triadHue2, 1, hsv[2]));
    }
    return builder.build();
}

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

/**
 * @param params base params used to build the rule.  Target and deps will be overridden.
 *//*from  ww w . ja v a 2 s  . co m*/
public static CxxLink createCxxLinkableBuildRule(CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform,
        BuildRuleParams params, BuildRuleResolver ruleResolver, final SourcePathResolver resolver,
        SourcePathRuleFinder ruleFinder, BuildTarget target, Path output, ImmutableList<Arg> args,
        Linker.LinkableDepType depType, Optional<Linker.CxxRuntimeType> cxxRuntimeType) {

    final Linker linker = cxxPlatform.getLd().resolve(ruleResolver);

    // Build up the arguments to pass to the linker.
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();

    // Add flags to generate linker map if supported.
    if (linker instanceof HasLinkerMap && LinkerMapMode.isLinkerMapEnabledForBuildTarget(target)) {
        argsBuilder.addAll(((HasLinkerMap) linker).linkerMap(output));
    }

    // Pass any platform specific or extra linker flags.
    argsBuilder.addAll(SanitizedArg.from(cxxPlatform.getCompilerDebugPathSanitizer().sanitize(Optional.empty()),
            cxxPlatform.getLdflags()));

    argsBuilder.addAll(args);

    // Add all arguments needed to link in the C/C++ platform runtime.
    Linker.LinkableDepType runtimeDepType = depType;
    if (cxxRuntimeType.orElse(Linker.CxxRuntimeType.DYNAMIC) == Linker.CxxRuntimeType.STATIC) {
        runtimeDepType = Linker.LinkableDepType.STATIC;
    }
    argsBuilder.addAll(StringArg.from(cxxPlatform.getRuntimeLdflags().get(runtimeDepType)));

    final ImmutableList<Arg> allArgs = argsBuilder.build();

    // Build the C/C++ link step.
    return new CxxLink(
            // Construct our link build rule params.  The important part here is combining the build
            // rules that construct our object file inputs and also the deps that build our
            // dependencies.
            params.copyWithChanges(target,
                    () -> FluentIterable.from(allArgs).transformAndConcat(arg -> arg.getDeps(ruleFinder))
                            .append(linker.getDeps(ruleFinder)).toSortedSet(Ordering.natural()),
                    Suppliers.ofInstance(ImmutableSortedSet.of())),
            resolver, linker, output, allArgs, cxxBuckConfig.getLinkScheduleInfo(),
            cxxBuckConfig.shouldCacheLinks());
}

From source file:org.spongepowered.common.data.SpongeDataRegistry.java

public static void finalizeRegistration() {
    allowRegistrations = false;//from   www  .j  a v a  2 s .  c o  m
    final SpongeDataRegistry registry = instance;
    for (Map.Entry<Key<? extends BaseValue<?>>, List<ValueProcessor<?, ?>>> entry : registry.valueProcessorMap
            .entrySet()) {
        ImmutableList.Builder<ValueProcessor<?, ?>> valueListBuilder = ImmutableList.builder();
        Collections.sort(entry.getValue(), ComparatorUtil.VALUE_PROCESSOR_COMPARATOR);
        valueListBuilder.addAll(entry.getValue());
        final ValueProcessorDelegate<?, ?> delegate = new ValueProcessorDelegate(entry.getKey(),
                valueListBuilder.build());
        registry.valueDelegates.put(entry.getKey(), delegate);
    }
    registry.valueProcessorMap.clear();
    for (Map.Entry<Class<? extends DataManipulator<?, ?>>, List<DataProcessor<?, ?>>> entry : registry.processorMap
            .entrySet()) {
        ImmutableList.Builder<DataProcessor<?, ?>> dataListBuilder = ImmutableList.builder();
        Collections.sort(entry.getValue(), ComparatorUtil.DATA_PROCESSOR_COMPARATOR);
        dataListBuilder.addAll(entry.getValue());
        final DataProcessorDelegate<?, ?> delegate = new DataProcessorDelegate(dataListBuilder.build());
        registry.dataProcessorDelegates.put(entry.getKey(), delegate);
    }
    registry.processorMap.clear();
    for (Map.Entry<Class<? extends ImmutableDataManipulator<?, ?>>, List<DataProcessor<?, ?>>> entry : registry.immutableProcessorMap
            .entrySet()) {
        ImmutableList.Builder<DataProcessor<?, ?>> dataListBuilder = ImmutableList.builder();
        Collections.sort(entry.getValue(), ComparatorUtil.DATA_PROCESSOR_COMPARATOR);
        dataListBuilder.addAll(entry.getValue());
        final DataProcessorDelegate<?, ?> delegate = new DataProcessorDelegate(dataListBuilder.build());
        registry.immutableDataProcessorDelegates.put(entry.getKey(), delegate);
    }
    registry.immutableProcessorMap.clear();
    for (Map.Entry<Class<? extends ImmutableDataManipulator<?, ?>>, List<BlockDataProcessor<?>>> entry : registry.blockDataMap
            .entrySet()) {
        ImmutableList.Builder<BlockDataProcessor<?>> dataListBuilder = ImmutableList.builder();
        Collections.sort(entry.getValue(), ComparatorUtil.BLOCK_DATA_PROCESSOR_COMPARATOR);
        dataListBuilder.addAll(entry.getValue());
        final BlockDataProcessorDelegate<?> delegate = new BlockDataProcessorDelegate(dataListBuilder.build());
        registry.blockDataProcessorDelegates.put(entry.getKey(), delegate);
    }
    registry.blockDataMap.clear();
    for (Map.Entry<Key<? extends BaseValue<?>>, List<BlockValueProcessor<?, ?>>> entry : registry.blockValueMap
            .entrySet()) {
        ImmutableList.Builder<BlockValueProcessor<?, ?>> valueListBuilder = ImmutableList.builder();
        Collections.sort(entry.getValue(), ComparatorUtil.BLOCK_VALUE_PROCESSOR_COMPARATOR);
        valueListBuilder.addAll(entry.getValue());
        final BlockValueProcessorDelegate<?, ?> delegate = new BlockValueProcessorDelegate(entry.getKey(),
                valueListBuilder.build());
        registry.blockValueProcessorDelegates.put(entry.getKey(), delegate);
    }
    registry.blockValueMap.clear();

}

From source file:google.registry.tmch.LordnTask.java

/** Leases and returns all tasks from the queue with the specified tag tld, in batches. */
public static List<TaskHandle> loadAllTasks(Queue queue, String tld) {
    ImmutableList.Builder<TaskHandle> allTasks = new ImmutableList.Builder<>();
    int numErrors = 0;
    long backOff = backOffMillis;
    while (true) {
        try {//from w  w w.ja  v  a2 s .  c o  m
            List<TaskHandle> tasks = queue.leaseTasks(LeaseOptions.Builder.withTag(tld)
                    .leasePeriod(LEASE_PERIOD.getMillis(), TimeUnit.MILLISECONDS).countLimit(BATCH_SIZE));
            allTasks.addAll(tasks);
            if (tasks.isEmpty()) {
                return allTasks.build();
            }
        } catch (TransientFailureException | DeadlineExceededException e) {
            if (++numErrors >= 3) {
                throw new RuntimeException("Error leasing tasks", e);
            }
            Uninterruptibles.sleepUninterruptibly(backOff, TimeUnit.MILLISECONDS);
            backOff *= 2;
        }
    }
}

From source file:com.facebook.presto.hive.AbstractTestHiveClientS3.java

private static List<ConnectorSplit> getAllSplits(ConnectorSplitSource source) throws InterruptedException {
    ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder();
    while (!source.isFinished()) {
        splits.addAll(getFutureValue(source.getNextBatch(1000)));
    }/*from ww  w. ja v a 2  s  . com*/
    return splits.build();
}

From source file:com.facebook.buck.android.resources.UsedResourcesFinder.java

public static ResourceClosure computePrimaryApkClosure(ApkContentProvider apkContentProvider) {
    // The Android framework (and other apps) have easy access to the values in the manifest and
    // anything reachable from there. Also, the framework needs access to animation references to
    // drive some animations (requested by the app itself).
    ImmutableList.Builder<Integer> rootIds = ImmutableList.builder();
    ResTablePackage resPackage = apkContentProvider.getResourceTable().getPackage();
    for (ResTableTypeSpec spec : resPackage.getTypeSpecs()) {
        if (spec.getResourceTypeName(resPackage).equals("anim")) {
            int startId = (ResTablePackage.APP_PACKAGE_ID << 24) | (spec.getResourceType() << 16);
            rootIds.addAll(IntStream.range(startId, startId + spec.getEntryCount())::iterator);
        }//from   ww  w  . j  ava 2s . c o m
    }
    return computeClosure(apkContentProvider, ImmutableList.of("AndroidManifest.xml"), rootIds.build());
}