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.cxx.Omnibus.java

protected static OmnibusLibrary createOmnibus(BuildRuleParams params, BuildRuleResolver ruleResolver,
        SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, CxxBuckConfig cxxBuckConfig,
        CxxPlatform cxxPlatform, ImmutableList<? extends Arg> extraLdflags, OmnibusSpec spec)
        throws NoSuchBuildTargetException {

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

    // Add extra ldflags to the beginning of the link.
    argsBuilder.addAll(extraLdflags);

    // For roots that aren't dependencies of nodes in the body, we extract their undefined symbols
    // to add to the link so that required symbols get pulled into the merged library.
    List<SourcePath> undefinedSymbolsOnlyRoots = new ArrayList<>();
    for (BuildTarget target : Sets.difference(spec.getRoots().keySet(), spec.getGraph().getNodes())) {
        NativeLinkTarget linkTarget = Preconditions.checkNotNull(spec.getRoots().get(target));
        undefinedSymbolsOnlyRoots.add(new BuildTargetSourcePath(getRootTarget(params.getBuildTarget(),
                shouldCreateDummyRoot(linkTarget, cxxPlatform) ? getDummyRootTarget(target) : target)));
    }/* w ww.j a v  a  2  s.c om*/
    argsBuilder.addAll(createUndefinedSymbolsArgs(params, ruleResolver, pathResolver, ruleFinder, cxxPlatform,
            undefinedSymbolsOnlyRoots));

    // Walk the graph in topological order, appending each nodes contributions to the link.
    ImmutableList<BuildTarget> targets = TopologicalSort.sort(spec.getGraph()).reverse();
    for (BuildTarget target : targets) {

        // If this is a root, just place the shared library we've linked above onto the link line.
        // We need this so that the linker can grab any undefined symbols from it, and therefore
        // know which symbols to pull in from the body nodes.
        NativeLinkTarget root = spec.getRoots().get(target);
        if (root != null) {
            argsBuilder.add(new SourcePathArg(pathResolver,
                    new BuildTargetSourcePath(getRootTarget(params.getBuildTarget(), root.getBuildTarget()))));
            continue;
        }

        // Otherwise, this is a body node, and we need to add its static library to the link line,
        // so that the linker can discard unused object files from it.
        NativeLinkable nativeLinkable = Preconditions.checkNotNull(spec.getBody().get(target));
        NativeLinkableInput input = NativeLinkables.getNativeLinkableInput(cxxPlatform,
                Linker.LinkableDepType.STATIC_PIC, nativeLinkable);
        argsBuilder.addAll(input.getArgs());
    }

    // We process all excluded omnibus deps last, and just add their components as if this were a
    // normal shared link.
    ImmutableMap<BuildTarget, NativeLinkable> deps = NativeLinkables.getNativeLinkables(cxxPlatform,
            spec.getDeps().values(), Linker.LinkableDepType.SHARED);
    for (NativeLinkable nativeLinkable : deps.values()) {
        NativeLinkableInput input = NativeLinkables.getNativeLinkableInput(cxxPlatform,
                Linker.LinkableDepType.SHARED, nativeLinkable);
        argsBuilder.addAll(input.getArgs());
    }

    // Create the merged omnibus library using the arguments assembled above.
    BuildTarget omnibusTarget = params.getBuildTarget().withAppendedFlavors(OMNIBUS_FLAVOR);
    String omnibusSoname = getOmnibusSoname(cxxPlatform);
    ruleResolver.addToIndex(CxxLinkableEnhancer.createCxxLinkableSharedBuildRule(cxxBuckConfig, cxxPlatform,
            params, ruleResolver, pathResolver, ruleFinder, omnibusTarget,
            BuildTargets.getGenPath(params.getProjectFilesystem(), omnibusTarget, "%s").resolve(omnibusSoname),
            Optional.of(omnibusSoname), argsBuilder.build()));

    return OmnibusLibrary.of(omnibusSoname, new BuildTargetSourcePath(omnibusTarget));
}

From source file:com.opera.core.systems.OperaBinary.java

private static List<String> buildDesktopPaths() {
    ImmutableList.Builder<String> paths = ImmutableList.builder();

    switch (platform) {
    case LINUX:/*from  ww w .j av  a 2 s. c o m*/
    case UNIX:
        paths.add("/usr/bin/opera");
        paths.add("/usr/bin/opera-next");
        break;

    case MAC:
        paths.add("/Applications/Opera.app/Contents/MacOS/Opera");
        paths.add("/Applications/Opera Next.app/Contents/MacOS/Opera");
        break;

    case WINDOWS:
    case VISTA:
    case XP:
        paths.addAll(WindowsUtils.getPathsInProgramFiles("Opera\\opera.exe"));
        paths.addAll(WindowsUtils.getPathsInProgramFiles("Opera Next\\opera.exe"));
        break;
    }

    return paths.build();
}

From source file:com.google.devtools.build.skyframe.ErrorInfo.java

/** Create an ErrorInfo from a collection of existing errors. */
public static ErrorInfo fromChildErrors(SkyKey currentValue, Collection<ErrorInfo> childErrors) {
    Preconditions.checkNotNull(currentValue, "currentValue must not be null");
    Preconditions.checkState(!childErrors.isEmpty(), "childErrors may not be empty");

    NestedSetBuilder<SkyKey> rootCausesBuilder = NestedSetBuilder.stableOrder();
    ImmutableList.Builder<CycleInfo> cycleBuilder = ImmutableList.builder();
    Exception firstException = null;
    SkyKey firstChildKey = null;/*from www .j  a v a  2  s  .c o m*/
    boolean isTransient = false;
    boolean isCatastrophic = false;
    for (ErrorInfo child : childErrors) {
        if (firstException == null) {
            // Arbitrarily pick the first error.
            firstException = child.getException();
            firstChildKey = child.getRootCauseOfException();
        }
        rootCausesBuilder.addTransitive(child.rootCauses);
        cycleBuilder.addAll(CycleInfo.prepareCycles(currentValue, child.cycles));
        isTransient |= child.isTransient();
        isCatastrophic |= child.isCatastrophic();
    }

    return new ErrorInfo(rootCausesBuilder.build(), firstException, firstChildKey, cycleBuilder.build(),
            isTransient, isCatastrophic);
}

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

/**
 * Create all build rules needed to generate the shared library.
 *
 * @return the {@link CxxLink} rule representing the actual shared library.
 *//* ww  w. j  ava 2 s . c o  m*/
private static BuildRule createSharedLibrary(BuildRuleParams params, BuildRuleResolver ruleResolver,
        SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, CxxBuckConfig cxxBuckConfig,
        CxxPlatform cxxPlatform, CxxLibraryDescription.Arg args, ImmutableList<String> linkerFlags,
        ImmutableSet<FrameworkPath> frameworks, ImmutableSet<FrameworkPath> libraries, Optional<String> soname,
        Optional<Linker.CxxRuntimeType> cxxRuntimeType, Linker.LinkType linkType,
        Linker.LinkableDepType linkableDepType, Optional<SourcePath> bundleLoader,
        ImmutableSet<BuildTarget> blacklist) throws NoSuchBuildTargetException {
    Optional<LinkerMapMode> flavoredLinkerMapMode = LinkerMapMode.FLAVOR_DOMAIN
            .getValue(params.getBuildTarget());
    params = LinkerMapMode.removeLinkerMapModeFlavorInParams(params, flavoredLinkerMapMode);

    // Create rules for compiling the PIC object files.
    ImmutableMap<CxxPreprocessAndCompile, SourcePath> objects = CxxDescriptionEnhancer.requireObjects(params,
            ruleResolver, pathResolver, ruleFinder, cxxBuckConfig, cxxPlatform,
            CxxSourceRuleFactory.PicType.PIC, args);

    // Setup the rules to link the shared library.
    BuildTarget sharedTarget = CxxDescriptionEnhancer.createSharedLibraryBuildTarget(
            LinkerMapMode.restoreLinkerMapModeFlavorInParams(params, flavoredLinkerMapMode).getBuildTarget(),
            cxxPlatform.getFlavor(), linkType);

    String sharedLibrarySoname = CxxDescriptionEnhancer.getSharedLibrarySoname(soname, params.getBuildTarget(),
            cxxPlatform);
    Path sharedLibraryPath = CxxDescriptionEnhancer.getSharedLibraryPath(params.getProjectFilesystem(),
            sharedTarget, sharedLibrarySoname);
    ImmutableList.Builder<String> extraLdFlagsBuilder = ImmutableList.builder();
    extraLdFlagsBuilder.addAll(linkerFlags);
    ImmutableList<String> extraLdFlags = extraLdFlagsBuilder.build();

    return CxxLinkableEnhancer.createCxxLinkableBuildRule(cxxBuckConfig, cxxPlatform,
            LinkerMapMode.restoreLinkerMapModeFlavorInParams(params, flavoredLinkerMapMode), ruleResolver,
            pathResolver, ruleFinder, sharedTarget, linkType, Optional.of(sharedLibrarySoname),
            sharedLibraryPath, linkableDepType, Iterables.filter(params.getDeps(), NativeLinkable.class),
            cxxRuntimeType, bundleLoader, blacklist,
            NativeLinkableInput.builder()
                    .addAllArgs(FluentIterable.from(extraLdFlags)
                            .transform(MacroArg.toMacroArgFunction(MACRO_HANDLER, params.getBuildTarget(),
                                    params.getCellRoots(), ruleResolver)))
                    .addAllArgs(SourcePathArg.from(pathResolver, objects.values())).setFrameworks(frameworks)
                    .setLibraries(libraries).build());
}

From source file:org.apache.aurora.scheduler.config.CommandLine.java

@VisibleForTesting
static List<Object> getOptionsObjects(CliOptions options) {
    ImmutableList.Builder<Object> objects = ImmutableList.builder();

    // Reflect on fields defined in CliOptions to DRY and avoid mistakes of forgetting to add an
    // option field here.
    for (Field field : CliOptions.class.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }/*from   w w w .  ja v  a  2 s . c  o  m*/

        try {
            if (Iterable.class.isAssignableFrom(field.getType())) {
                Iterable<?> iterableValue = (Iterable<?>) field.get(options);
                objects.addAll(iterableValue);
            } else {
                objects.add(field.get(options));
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    return objects.build();
}

From source file:com.facebook.presto.sql.planner.EffectivePredicateExtractor.java

private static Expression pullExpressionThroughSymbols(Expression expression, Collection<Symbol> symbols) {
    EqualityInference equalityInference = createEqualityInference(expression);

    ImmutableList.Builder<Expression> effectiveConjuncts = ImmutableList.builder();
    for (Expression conjunct : EqualityInference.nonInferrableConjuncts(expression)) {
        if (DeterminismEvaluator.isDeterministic(conjunct)) {
            Expression rewritten = equalityInference.rewriteExpression(conjunct, in(symbols));
            if (rewritten != null) {
                effectiveConjuncts.add(rewritten);
            }/*  w  w  w.j  a va2s  .  c o  m*/
        }
    }

    effectiveConjuncts
            .addAll(equalityInference.generateEqualitiesPartitionedBy(in(symbols)).getScopeEqualities());

    return combineConjuncts(effectiveConjuncts.build());
}

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

protected static OmnibusRoot createRoot(BuildRuleParams params, BuildRuleResolver ruleResolver,
        SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, CxxBuckConfig cxxBuckConfig,
        CxxPlatform cxxPlatform, ImmutableList<? extends Arg> extraLdflags, OmnibusSpec spec,
        SourcePath omnibus, NativeLinkTarget root, BuildTarget rootTargetBase, Optional<Path> output)
        throws NoSuchBuildTargetException {

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

    // Add any extra flags to the link.
    argsBuilder.addAll(extraLdflags);

    // Since the dummy omnibus library doesn't actually contain any symbols, make sure the linker
    // won't drop its runtime reference to it.
    argsBuilder/* w ww. j  a va  2  s. co m*/
            .addAll(StringArg.from(cxxPlatform.getLd().resolve(ruleResolver).getNoAsNeededSharedLibsFlags()));

    // Since we're linking against a dummy libomnibus, ignore undefined symbols.
    argsBuilder
            .addAll(StringArg.from(cxxPlatform.getLd().resolve(ruleResolver).getIgnoreUndefinedSymbolsFlags()));

    // Add the args for the root link target first.
    NativeLinkableInput input = root.getNativeLinkTargetInput(cxxPlatform);
    argsBuilder.addAll(input.getArgs());

    // Grab a topologically sorted mapping of all the root's deps.
    ImmutableMap<BuildTarget, NativeLinkable> deps = NativeLinkables.getNativeLinkables(cxxPlatform,
            root.getNativeLinkTargetDeps(cxxPlatform), Linker.LinkableDepType.SHARED);

    // Now process the dependencies in topological order, to assemble the link line.
    boolean alreadyAddedOmnibusToArgs = false;
    for (Map.Entry<BuildTarget, NativeLinkable> entry : deps.entrySet()) {
        BuildTarget target = entry.getKey();
        NativeLinkable nativeLinkable = entry.getValue();
        Linker.LinkableDepType linkStyle = NativeLinkables
                .getLinkStyle(nativeLinkable.getPreferredLinkage(cxxPlatform), Linker.LinkableDepType.SHARED);

        // If this dep needs to be linked statically, then we always link it directly.
        if (linkStyle != Linker.LinkableDepType.SHARED) {
            Preconditions.checkState(linkStyle == Linker.LinkableDepType.STATIC_PIC);
            argsBuilder.addAll(nativeLinkable.getNativeLinkableInput(cxxPlatform, linkStyle).getArgs());
            continue;
        }

        // If this dep is another root node, substitute in the custom linked library we built for it.
        if (spec.getRoots().containsKey(target)) {
            argsBuilder.add(new SourcePathArg(pathResolver,
                    new BuildTargetSourcePath(getRootTarget(params.getBuildTarget(), target))));
            continue;
        }

        // If we're linking this dep from the body, then we need to link via the giant merged
        // libomnibus instead.
        if (spec.getBody().containsKey(target)) { // && linkStyle == Linker.LinkableDepType.SHARED) {
            if (!alreadyAddedOmnibusToArgs) {
                argsBuilder.add(new SourcePathArg(pathResolver, omnibus));
                alreadyAddedOmnibusToArgs = true;
            }
            continue;
        }

        // Otherwise, this is either an explicitly statically linked or excluded node, so link it
        // normally.
        Preconditions.checkState(spec.getExcluded().containsKey(target));
        argsBuilder.addAll(nativeLinkable.getNativeLinkableInput(cxxPlatform, linkStyle).getArgs());
    }

    // Create the root library rule using the arguments assembled above.
    BuildTarget rootTarget = getRootTarget(params.getBuildTarget(), rootTargetBase);
    NativeLinkTargetMode rootTargetMode = root.getNativeLinkTargetMode(cxxPlatform);
    CxxLink rootLinkRule;
    switch (rootTargetMode.getType()) {

    // Link the root as a shared library.
    case SHARED: {
        Optional<String> rootSoname = rootTargetMode.getLibraryName();
        rootLinkRule = CxxLinkableEnhancer
                .createCxxLinkableSharedBuildRule(cxxBuckConfig, cxxPlatform, params, ruleResolver,
                        pathResolver, ruleFinder, rootTarget,
                        output.orElse(BuildTargets.getGenPath(params.getProjectFilesystem(), rootTarget, "%s")
                                .resolve(rootSoname.orElse(String.format("%s.%s", rootTarget.getShortName(),
                                        cxxPlatform.getSharedLibraryExtension())))),
                        rootSoname, argsBuilder.build());
        break;
    }

    // Link the root as an executable.
    case EXECUTABLE: {
        rootLinkRule = CxxLinkableEnhancer.createCxxLinkableBuildRule(cxxBuckConfig, cxxPlatform, params,
                ruleResolver, pathResolver, ruleFinder, rootTarget,
                output.orElse(BuildTargets.getGenPath(params.getProjectFilesystem(), rootTarget, "%s")
                        .resolve(rootTarget.getShortName())),
                argsBuilder.build(), Linker.LinkableDepType.SHARED, Optional.empty());
        break;
    }

    // $CASES-OMITTED$
    default:
        throw new IllegalStateException(String.format("%s: unexpected omnibus root type: %s %s",
                params.getBuildTarget(), root.getBuildTarget(), rootTargetMode.getType()));

    }

    ruleResolver.addToIndex(rootLinkRule);
    return OmnibusRoot.of(new BuildTargetSourcePath(rootTarget));
}

From source file:com.google.javascript.jscomp.parsing.parser.codegeneration.ParseTreeFactory.java

public static CallExpressionTree createCallCall(ParseTree function, ParseTree thisExpression,
        List<ParseTree> arguments) {
    ImmutableList.Builder<ParseTree> builder = ImmutableList.<ParseTree>builder();

    builder.add(thisExpression);//from   ww w.  j a va  2s.  c  o m
    builder.addAll(arguments);

    return createCallExpression(createMemberExpression(function, PredefinedName.CALL),
            createArgumentList(builder.build()));
}

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

/**
 * Processes a list of java source files, extracting and SRC_ZIP or SRC_JAR to the working
 * directory and returns a list of all the resulting .java files.
 *///from  w w  w  . j av a 2 s  . c o m
static ImmutableList<Path> extractArchivesAndGetPaths(ProjectFilesystem projectFilesystem,
        ProjectFilesystemFactory projectFilesystemFactory, ImmutableSet<Path> javaSourceFilePaths,
        Path workingDirectory) throws InterruptedException, IOException {

    // Add sources file or sources list to command
    ImmutableList.Builder<Path> sources = ImmutableList.builder();
    for (Path path : javaSourceFilePaths) {
        String pathString = path.toString();
        if (pathString.endsWith(".java")) {
            sources.add(path);
        } else if (pathString.endsWith(SRC_ZIP) || pathString.endsWith(SRC_JAR)) {
            // For a Zip of .java files, create a JavaFileObject for each .java entry.
            ImmutableList<Path> zipPaths = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
                    projectFilesystemFactory, projectFilesystem.resolve(path),
                    projectFilesystem.resolve(workingDirectory), ExistingFileMode.OVERWRITE);
            sources.addAll(zipPaths.stream().filter(input -> input.toString().endsWith(".java")).iterator());
        }
    }
    return sources.build();
}

From source file:com.opengamma.strata.calc.runner.CalculationTasks.java

/**
 * Obtains an instance from a set of targets, columns and rules.
 * <p>/*  w  w w  . j  a va 2s  .  c  om*/
 * The targets will typically be trades.
 * The columns represent the measures to calculate.
 * 
 * @param rules  the rules defining how the calculation is performed
 * @param targets  the targets for which values of the measures will be calculated
 * @param columns  the columns that will be calculated
 * @return the calculation tasks
 */
public static CalculationTasks of(CalculationRules rules, List<? extends CalculationTarget> targets,
        List<Column> columns) {

    // create columns that are a combination of the column overrides and the defaults
    // this is done once as it is the same for all targets
    List<Column> effectiveColumns = columns.stream()
            .map(column -> column.combineWithDefaults(rules.getReportingCurrency(), rules.getParameters()))
            .collect(toImmutableList());

    // loop around the targets, then the columns, to build the tasks
    ImmutableList.Builder<CalculationTask> taskBuilder = ImmutableList.builder();
    for (int rowIndex = 0; rowIndex < targets.size(); rowIndex++) {
        CalculationTarget target = targets.get(rowIndex);

        // find the applicable function
        CalculationFunction<?> fn = rules.getFunctions().getFunction(target);

        // create the tasks
        List<CalculationTask> targetTasks = createTargetTasks(target, rowIndex, fn, effectiveColumns);
        taskBuilder.addAll(targetTasks);
    }

    // calculation tasks holds the original user-specified columns, not the derived ones
    return new CalculationTasks(taskBuilder.build(), columns);
}