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.torodb.torod.db.backends.query.processors.InProcessor.java

@Nullable
private static ProcessedQueryCriteria getNumericQuery(InQueryCriteria criteria,
        Multimap<ScalarType, ScalarValue<?>> byTypeValues) {
    ImmutableList.Builder<ScalarValue<?>> newInBuilder = ImmutableList.builder();

    for (ScalarValue<?> value : byTypeValues.values()) {
        newInBuilder.add(value);//from   w ww .ja v a  2 s  .  c o  m
    }

    ImmutableList<ScalarValue<?>> newIn = newInBuilder.build();

    if (newIn.isEmpty()) {
        return null;
    }

    DisjunctionBuilder structureBuilder = new DisjunctionBuilder();

    structureBuilder.add(new TypeIsQueryCriteria(criteria.getAttributeReference(), ScalarType.DOUBLE));
    structureBuilder.add(new TypeIsQueryCriteria(criteria.getAttributeReference(), ScalarType.INTEGER));
    structureBuilder.add(new TypeIsQueryCriteria(criteria.getAttributeReference(), ScalarType.LONG));

    newInBuilder.addAll(byTypeValues.get(ScalarType.DOUBLE));
    newInBuilder.addAll(byTypeValues.get(ScalarType.INTEGER));
    newInBuilder.addAll(byTypeValues.get(ScalarType.LONG));

    return new ProcessedQueryCriteria(structureBuilder.build(),
            new InQueryCriteria(criteria.getAttributeReference(), newIn));
}

From source file:com.spectralogic.ds3autogen.c.helpers.RequestHelper.java

public static String generateInitRequestFunctionSignature(final Request request) {
    final ImmutableList.Builder<String> builder = ImmutableList.builder();

    if (request.getClassification() == Classification.amazons3) {
        final String amazonS3InitParams = getAmazonS3InitParams(request.isResourceRequired(),
                request.isResourceIdRequired());
        if (!amazonS3InitParams.isEmpty()) {
            builder.add(amazonS3InitParams);
        }//from  ww w  . ja va  2 s. c om
    } else {
        final String spectraS3InitParams = getSpectraS3InitParams(request.isResourceRequired());
        if (!spectraS3InitParams.isEmpty()) {
            builder.add(spectraS3InitParams);
        }
    }

    builder.addAll(request.getRequiredQueryParams().stream()
            .filter(parm -> !parm.getParameterType().equals("ds3_bool")) // for required bool / void query param nothing to specify
            .filter(parm -> !parm.getParameterType().equals("operation")) // for required spectrads3 operation query param nothing to specify
            .map(Parameter::toString).collect(GuavaCollectors.immutableList()));

    if (request.hasRequestPayload() && !request.getName().equalsIgnoreCase("ds3_put_object_request")
            && !request.getName().equalsIgnoreCase("ds3_put_multi_part_upload_part_request")) {
        builder.add(request.getRequestPayload().toString());
    }

    final ImmutableList<String> allParams = builder.build();

    return "ds3_request* " + request.getInitName() + "(" + joinStrings(allParams) + ")";
}

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

/**
 * Reads the header scanning output file and discovers all of those headers as input artifacts.
 *
 * @param sourceFile the source that requires these headers
 * @param headersListFile .headers_list file output from header_scanner tool to be read
 * @param inputArtifactsMap map of PathFragment to Artifact of possible headers
 * @return collection of header artifacts that are required for {@code action} to compile
 * @throws ExecException on environmental (IO) or user errors
 *//*from  w  w w.  j  av a  2s  .com*/
public static Iterable<Artifact> findRequiredHeaderInputs(Artifact sourceFile, Artifact headersListFile,
        Map<PathFragment, Artifact> inputArtifactsMap) throws ExecException {
    try {
        ImmutableList.Builder<Artifact> includeBuilder = ImmutableList.builder();
        List<PathFragment> missing = new ArrayList<>();
        for (String line : FileSystemUtils.readLines(headersListFile.getPath(), StandardCharsets.UTF_8)) {
            if (line.isEmpty()) {
                continue;
            }

            PathFragment headerPath = PathFragment.create(line);
            Artifact header = inputArtifactsMap.get(headerPath);
            if (header == null) {
                missing.add(headerPath);
            } else {
                includeBuilder.add(header);
            }
        }

        if (!missing.isEmpty()) {
            includeBuilder
                    .addAll(findRequiredHeaderInputsInTreeArtifacts(sourceFile, inputArtifactsMap, missing));
        }
        return includeBuilder.build();
    } catch (IOException ex) {
        throw new EnvironmentalExecException(
                String.format("Error reading headers file %s", headersListFile.getExecPathString()), ex);
    }
}

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

public static ImmutableList<String> getOptions(JavacOptions javacOptions, ProjectFilesystem filesystem,
        Path outputDirectory, ExecutionContext context, ImmutableSortedSet<Path> buildClasspathEntries) {
    final ImmutableList.Builder<String> builder = ImmutableList.builder();

    javacOptions.appendOptionsTo(new OptionsConsumer() {
        @Override//from ww  w. java  2s . c o m
        public void addOptionValue(String option, String value) {
            builder.add("-" + option).add(value);
        }

        @Override
        public void addFlag(String flagName) {
            builder.add("-" + flagName);
        }

        @Override
        public void addExtras(Collection<String> extras) {
            builder.addAll(extras);
        }
    }, filesystem::resolve);

    // verbose flag, if appropriate.
    if (context.getVerbosity().shouldUseVerbosityFlagIfAvailable()) {
        builder.add("-verbose");
    }

    // Specify the output directory.
    builder.add("-d").add(filesystem.resolve(outputDirectory).toString());

    // Build up and set the classpath.
    if (!buildClasspathEntries.isEmpty()) {
        String classpath = Joiner.on(File.pathSeparator).join(buildClasspathEntries);
        builder.add("-classpath", classpath);
    } else {
        builder.add("-classpath", "''");
    }

    return builder.build();
}

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

public static List<PartitionUpdate> mergePartitionUpdates(List<PartitionUpdate> unMergedUpdates) {
    ImmutableList.Builder<PartitionUpdate> partitionUpdates = ImmutableList.builder();
    for (Collection<PartitionUpdate> partitionGroup : Multimaps.index(unMergedUpdates, PartitionUpdate::getName)
            .asMap().values()) {/*  w  ww.  ja v  a  2  s  .  c om*/
        PartitionUpdate firstPartition = partitionGroup.iterator().next();

        ImmutableList.Builder<String> allFileNames = ImmutableList.builder();
        for (PartitionUpdate partition : partitionGroup) {
            // verify partitions have the same new flag, write path and target path
            // this shouldn't happen but could if another user added a partition during the write
            if (partition.isNew() != firstPartition.isNew()
                    || !partition.getWritePath().equals(firstPartition.getWritePath())
                    || !partition.getTargetPath().equals(firstPartition.getTargetPath())) {
                throw new PrestoException(HIVE_WRITER_ERROR,
                        format("Partition %s was added or modified during INSERT", firstPartition.getName()));
            }
            allFileNames.addAll(partition.getFileNames());
        }

        partitionUpdates.add(new PartitionUpdate(firstPartition.getName(), firstPartition.isNew(),
                firstPartition.getWritePath(), firstPartition.getTargetPath(), allFileNames.build()));
    }
    return partitionUpdates.build();
}

From source file:gobblin.runtime.JobState.java

private static List<WorkUnitState> workUnitStatesFromDatasetStates(
        Iterable<JobState.DatasetState> datasetStates) {
    ImmutableList.Builder<WorkUnitState> taskStateBuilder = ImmutableList.builder();
    for (JobState datasetState : datasetStates) {
        taskStateBuilder.addAll(datasetState.getTaskStatesAsWorkUnitStates());
    }/*from   w w  w  . j  a v  a2s.c om*/
    return taskStateBuilder.build();
}

From source file:org.apache.aurora.scheduler.resources.AcceptedOffer.java

public static AcceptedOffer create(Offer offer, IAssignedTask task, ResourceBag executorOverhead,
        TierInfo tierInfo) throws ResourceManager.InsufficientResourcesException {

    ImmutableList.Builder<Resource> taskResources = ImmutableList.builder();
    ImmutableList.Builder<Resource> executorResources = ImmutableList.builder();

    ResourceManager.bagFromResources(task.getTask().getResources()).streamResourceVectors().forEach(entry -> {
        ResourceType type = entry.getKey();
        Iterable<Resource.Builder> offerResources = StreamSupport
                .stream(getOfferResources(offer, tierInfo, entry.getKey()).spliterator(), false)
                // Note the reverse order of args in .compare(): we want RESERVED resources first.
                .sorted((l, r) -> Boolean.compare(RESERVED.test(r), RESERVED.test(l))).map(Resource::toBuilder)
                .collect(toList());//from   w w  w .ja v a  2s .  co m

        boolean isRevocable = type.isMesosRevocable() && tierInfo.isRevocable();

        taskResources.addAll(type.getMesosResourceConverter().toMesosResource(offerResources,
                type.getMapper().isPresent() ? () -> type.getMapper().get().getAssigned(task)
                        : () -> entry.getValue(),
                isRevocable));

        if (executorOverhead.getResourceVectors().containsKey(type)) {
            executorResources.addAll(type.getMesosResourceConverter().toMesosResource(offerResources,
                    () -> executorOverhead.getResourceVectors().get(type), isRevocable));
        }
    });

    return new AcceptedOffer(taskResources.build(), executorResources.build());
}

From source file:org.apache.gobblin.runtime.JobState.java

public static List<WorkUnitState> workUnitStatesFromDatasetStates(
        Iterable<JobState.DatasetState> datasetStates) {
    ImmutableList.Builder<WorkUnitState> taskStateBuilder = ImmutableList.builder();
    for (JobState datasetState : datasetStates) {
        taskStateBuilder.addAll(datasetState.getTaskStatesAsWorkUnitStates());
    }/* ww w . j av  a  2  s.co  m*/
    return taskStateBuilder.build();
}

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

private static RustCompileRule createBuild(BuildTarget target, String crateName,
        ProjectFilesystem projectFilesystem, BuildRuleParams params, ActionGraphBuilder graphBuilder,
        SourcePathRuleFinder ruleFinder, RustPlatform rustPlatform, RustBuckConfig rustConfig,
        ImmutableList<String> extraFlags, ImmutableList<String> extraLinkerFlags, Iterable<Arg> linkerInputs,
        CrateType crateType, Optional<String> edition, LinkableDepType depType, boolean rpath,
        ImmutableSortedSet<SourcePath> sources, SourcePath rootModule, boolean forceRlib, boolean preferStatic,
        Iterable<BuildRule> ruledeps, Optional<String> incremental) {
    CxxPlatform cxxPlatform = rustPlatform.getCxxPlatform();
    ImmutableList.Builder<Arg> linkerArgs = ImmutableList.builder();

    Optional<String> filename = crateType.filenameFor(target, crateName, cxxPlatform);

    if (crateType == CrateType.CDYLIB) {
        String soname = filename.get();
        Linker linker = cxxPlatform.getLd().resolve(graphBuilder);
        linkerArgs.addAll(StringArg.from(linker.soname(soname)));
    }/* ww w  . j a va2s . c o m*/

    Stream.concat(rustPlatform.getLinkerArgs().stream(), extraLinkerFlags.stream()).filter(x -> !x.isEmpty())
            .map(StringArg::of).forEach(linkerArgs::add);

    linkerArgs.addAll(linkerInputs);

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

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

    Stream<String> checkArgs;
    if (crateType.isCheck()) {
        args.add(StringArg.of("--emit=metadata"));
        checkArgs = rustPlatform.getRustCheckFlags().stream();
    } else {
        checkArgs = Stream.of();
    }

    if (crateType.isSaveAnalysis()) {
        // This is an unstable option - not clear what the path to stabilization is.
        args.add(StringArg.of("-Zsave-analysis"));
    }

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

    if (edition.isPresent()) {
        args.add(StringArg.of(String.format("--edition=%s", edition.get())));
    }

    if (incremental.isPresent()) {
        Path path = projectFilesystem.getBuckPaths().getTmpDir().resolve("rust-incremental")
                .resolve(incremental.get());

        for (Flavor f : target.getFlavors()) {
            path = path.resolve(f.getName());
        }
        args.add(StringArg.of(String.format("-Cincremental=%s", path)));
    }

    LinkableDepType rustDepType;
    // If we're building a CDYLIB then our Rust dependencies need to be static
    // Alternatively, if we're using forceRlib then anything else needs rlib deps.
    if (depType == LinkableDepType.SHARED && (forceRlib || crateType == CrateType.CDYLIB)) {
        rustDepType = LinkableDepType.STATIC_PIC;
    } else {
        rustDepType = depType;
    }

    // Find direct and transitive Rust deps. We do this in two passes, since a dependency that's
    // both direct and transitive needs to be listed on the command line in each form.
    //
    // 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.

    // First pass - direct deps
    RichStream.from(ruledeps).filter(RustLinkable.class::isInstance).map(
            rule -> ((RustLinkable) rule).getLinkerArg(true, crateType.isCheck(), rustPlatform, rustDepType))
            .forEach(depArgs::add);

    // Second pass - indirect deps
    new AbstractBreadthFirstTraversal<BuildRule>(RichStream.from(ruledeps).filter(RustLinkable.class)
            .flatMap(r -> RichStream.from(r.getRustLinakbleDeps(rustPlatform)))
            .collect(ImmutableList.toImmutableList())) {
        @Override
        public Iterable<BuildRule> visit(BuildRule rule) {
            Iterable<BuildRule> deps = ImmutableSortedSet.of();
            if (rule instanceof RustLinkable) {
                deps = ((RustLinkable) rule).getRustLinakbleDeps(rustPlatform);

                Arg arg = ((RustLinkable) rule).getLinkerArg(false, crateType.isCheck(), rustPlatform,
                        rustDepType);

                depArgs.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, graphBuilder, ruledeps, depType,
                        r -> r instanceof RustLinkable
                                ? Optional.of(((RustLinkable) r).getRustLinakbleDeps(rustPlatform))
                                : Optional.empty())
                .getArgs();

        // Add necessary rpaths if we're dynamically linking with things
        if (rpath && depType == Linker.LinkableDepType.SHARED) {
            args.add(StringArg.of("-Crpath"));
        }

        linkerArgs.addAll(nativeArgs);
    }

    // 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 ((!preferStatic && depType == Linker.LinkableDepType.SHARED) || crateType == CrateType.DYLIB) {
        args.add(StringArg.of("-Cprefer-dynamic"));
    }

    return RustCompileRule.from(ruleFinder, target, projectFilesystem, params, filename,
            rustPlatform.getRustCompiler().resolve(graphBuilder),
            rustPlatform.getLinkerProvider().resolve(graphBuilder), args.build(), depArgs.build(),
            linkerArgs.build(),
            CxxGenruleDescription.fixupSourcePaths(graphBuilder, ruleFinder, cxxPlatform, sources),
            CxxGenruleDescription.fixupSourcePath(graphBuilder, ruleFinder, cxxPlatform, rootModule),
            rustConfig.getRemapSrcPaths());
}

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

static ImmutableList<Arg> getCxxLinkerArgs(ActionGraphBuilder graphBuilder, CxxPlatform cxxPlatform,
        Iterable<BuildRule> linkables, Linker.LinkableDepType linkStyle, Iterable<Arg> externalLinkerFlags) {

    // cgo library might have C/C++ dependencies which needs to be linked to the
    // go binary. This piece of code collects the linker args from all the
    // CGoLibrary cxx dependencies.
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();

    NativeLinkableInput linkableInput = NativeLinkables.getTransitiveNativeLinkableInput(cxxPlatform,
            graphBuilder, linkables, linkStyle, r -> Optional.empty());

    // skip setting any arg if no linkable inputs are present
    if (linkableInput.getArgs().isEmpty() && Iterables.size(externalLinkerFlags) == 0) {
        return argsBuilder.build();
    }/*from www . j  ava  2 s  .  c  o m*/

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

    // add all arguments needed to link in the C/C++ platform runtime.
    argsBuilder.addAll(StringArg.from(cxxPlatform.getRuntimeLdflags().get(linkStyle)));
    argsBuilder.addAll(externalLinkerFlags);
    argsBuilder.addAll(linkableInput.getArgs());

    return argsBuilder.build();
}