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.AbstractCxxPreprocessorInput.java

public static CxxPreprocessorInput concat(Iterable<CxxPreprocessorInput> inputs) {
    ImmutableMultimap.Builder<CxxSource.Type, String> preprocessorFlags = ImmutableMultimap.builder();
    ImmutableList.Builder<CxxHeaders> headers = ImmutableList.builder();
    ImmutableSet.Builder<FrameworkPath> frameworks = ImmutableSet.builder();
    ImmutableSet.Builder<BuildTarget> rules = ImmutableSet.builder();

    for (CxxPreprocessorInput input : inputs) {
        preprocessorFlags.putAll(input.getPreprocessorFlags());
        headers.addAll(input.getIncludes());
        frameworks.addAll(input.getFrameworks());
        rules.addAll(input.getRules());/*from w w  w . java  2  s  .c o  m*/
    }

    return CxxPreprocessorInput.of(preprocessorFlags.build(), headers.build(), frameworks.build(),
            rules.build());
}

From source file:com.facebook.buck.haskell.HaskellDescriptionUtils.java

/**
 * Create a Haskell link rule that links the given inputs to a executable or shared library and
 * pulls in transitive native linkable deps from the given dep roots.
 *//*  w w  w.  j a  v  a2 s  . c om*/
public static HaskellLinkRule createLinkRule(BuildTarget target, BuildRuleParams baseParams,
        BuildRuleResolver resolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder,
        CxxPlatform cxxPlatform, HaskellConfig haskellConfig, Linker.LinkType linkType,
        ImmutableList<String> extraFlags, Iterable<Arg> linkerInputs, Iterable<? extends NativeLinkable> deps,
        Linker.LinkableDepType depType) throws NoSuchBuildTargetException {

    Tool linker = haskellConfig.getLinker().resolve(resolver);
    String name = target.getShortName();

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

    // Add the base flags from the `.buckconfig` first.
    argsBuilder.addAll(StringArg.from(haskellConfig.getLinkerFlags()));

    // Pass in the appropriate flags to link a shared library.
    if (linkType.equals(Linker.LinkType.SHARED)) {
        name = CxxDescriptionEnhancer.getSharedLibrarySoname(Optional.empty(), target.withFlavors(),
                cxxPlatform);
        argsBuilder.addAll(StringArg.from("-shared", "-dynamic"));
        argsBuilder.addAll(StringArg.from(MoreIterables.zipAndConcat(Iterables.cycle("-optl"),
                cxxPlatform.getLd().resolve(resolver).soname(name))));
    }

    // Add in extra flags passed into this function.
    argsBuilder.addAll(StringArg.from(extraFlags));

    // We pass in the linker inputs and all native linkable deps by prefixing with `-optl` so that
    // the args go straight to the linker, and preserve their order.
    linkerArgsBuilder.addAll(linkerInputs);
    for (NativeLinkable nativeLinkable : NativeLinkables.getNativeLinkables(cxxPlatform, deps, depType)
            .values()) {
        linkerArgsBuilder
                .addAll(NativeLinkables.getNativeLinkableInput(cxxPlatform, depType, nativeLinkable).getArgs());
    }

    // Since we use `-optl` to pass all linker inputs directly to the linker, the haskell linker
    // will complain about not having any input files.  So, create a dummy archive with an empty
    // module and pass that in normally to work around this.
    BuildTarget emptyModuleTarget = target.withAppendedFlavors(ImmutableFlavor.of("empty-module"));
    WriteFile emptyModule = resolver.addToIndex(new WriteFile(baseParams.copyWithBuildTarget(emptyModuleTarget),
            "module Unused where",
            BuildTargets.getGenPath(baseParams.getProjectFilesystem(), emptyModuleTarget, "%s/Unused.hs"),
            /* executable */ false));
    HaskellCompileRule emptyCompiledModule = resolver.addToIndex(createCompileRule(
            target.withAppendedFlavors(ImmutableFlavor.of("empty-compiled-module")), baseParams, resolver,
            ruleFinder, pathResolver, cxxPlatform, haskellConfig, depType, Optional.empty(), Optional.empty(),
            ImmutableList.of(), HaskellSources.builder()
                    .putModuleMap("Unused", new BuildTargetSourcePath(emptyModule.getBuildTarget())).build()));
    BuildTarget emptyArchiveTarget = target.withAppendedFlavors(ImmutableFlavor.of("empty-archive"));
    Archive emptyArchive = resolver.addToIndex(Archive.from(emptyArchiveTarget, baseParams, pathResolver,
            ruleFinder, cxxPlatform, Archive.Contents.NORMAL,
            BuildTargets.getGenPath(baseParams.getProjectFilesystem(), emptyArchiveTarget, "%s/libempty.a"),
            emptyCompiledModule.getObjects()));
    argsBuilder.add(new SourcePathArg(pathResolver, new BuildTargetSourcePath(emptyArchive.getBuildTarget())));

    ImmutableList<Arg> args = argsBuilder.build();
    ImmutableList<Arg> linkerArgs = linkerArgsBuilder.build();

    return resolver.addToIndex(new HaskellLinkRule(
            baseParams.copyWithChanges(target,
                    Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder()
                            .addAll(linker.getDeps(ruleFinder))
                            .addAll(Stream.of(args, linkerArgs).flatMap(Collection::stream)
                                    .flatMap(arg -> arg.getDeps(ruleFinder).stream()).iterator())
                            .build()),
                    Suppliers.ofInstance(ImmutableSortedSet.of())),
            pathResolver, linker, name, args, linkerArgs, haskellConfig.shouldCacheLinks()));
}

From source file:com.facebook.buck.features.haskell.HaskellHaddockLibRule.java

public static HaskellHaddockLibRule from(BuildTarget buildTarget, ProjectFilesystem projectFilesystem,
        BuildRuleParams buildRuleParams, SourcePathRuleFinder ruleFinder, HaskellSources sources,
        Tool haddockTool, ImmutableList<String> haddockFlags, ImmutableList<String> compilerFlags,
        ImmutableList<String> linkerFlags, ImmutableSet<SourcePath> interfaces,
        ImmutableSortedMap<String, HaskellPackage> packages,
        ImmutableSortedMap<String, HaskellPackage> exposedPackages, HaskellPackageInfo packageInfo,
        HaskellPlatform platform, Preprocessor preprocessor, PreprocessorFlags ppFlags) {

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

    for (HaskellPackage pkg : packages.values()) {
        pkgDeps.addAll(pkg.getDeps(ruleFinder).iterator());
    }/* w w  w  .j a  va 2  s . c  o  m*/
    for (HaskellPackage pkg : exposedPackages.values()) {
        pkgDeps.addAll(pkg.getDeps(ruleFinder).iterator());
    }

    Supplier<ImmutableSortedSet<BuildRule>> declaredDeps = MoreSuppliers.memoize(() -> ImmutableSortedSet
            .<BuildRule>naturalOrder().addAll(BuildableSupport.getDepsCollection(haddockTool, ruleFinder))
            .addAll(sources.getDeps(ruleFinder)).addAll(ruleFinder.filterBuildRuleInputs(interfaces))
            .addAll(pkgDeps.build()).addAll(ppFlags.getDeps(ruleFinder)).build());
    return new HaskellHaddockLibRule(buildTarget, projectFilesystem,
            buildRuleParams.withDeclaredDeps(declaredDeps).withoutExtraDeps(), sources, haddockTool,
            haddockFlags, compilerFlags, linkerFlags, interfaces, packages, exposedPackages, packageInfo,
            platform, preprocessor, ppFlags);
}

From source file:com.google.api.codegen.discovery.Document.java

/**
 * Returns a document constructed from root.
 *
 * @param root the root node to parse./*  w w  w  .ja  v a 2s  .  c  o  m*/
 * @return a document.
 */
public static Document from(DiscoveryNode root) {
    AuthType authType;
    DiscoveryNode scopesNode = root.getObject("auth").getObject("oauth2").getObject("scopes");

    ImmutableList.Builder<String> authScopes = new Builder<>();
    if (scopesNode.isEmpty()) {
        authType = AuthType.API_KEY;
    } else {
        authScopes.addAll(scopesNode.getFieldNames());
        if (scopesNode.has(CLOUD_PLATFORM_SCOPE)) {
            authType = AuthType.ADC;
        } else {
            authType = AuthType.OAUTH_3L;
        }
    }
    String canonicalName = root.getString("canonicalName");
    String description = root.getString("description");
    String id = root.getString("id");
    Map<String, Schema> schemas = parseSchemas(root);
    List<Method> methods = parseMethods(root);
    Collections.sort(methods); // Ensure methods are ordered alphabetically by their ID.
    String ownerDomain = root.getString("ownerDomain");
    String name = root.getString("name");
    if (canonicalName.isEmpty()) {
        canonicalName = name;
    }
    Map<String, List<Method>> resources = parseResources(root);
    String revision = root.getString("revision");
    String rootUrl = root.getString("rootUrl");
    String servicePath = root.getString("servicePath");
    String title = root.getString("title");
    String version = root.getString("version");
    boolean versionModule = root.getBoolean("version_module");

    String baseUrl = root.has("baseUrl") ? root.getString("baseUrl")
            : (rootUrl + Strings.nullToEmpty(root.getString("basePath")));

    Document thisDocument = new AutoValue_Document("", // authInstructionsUrl (only intended to be overridden).
            authScopes.build(), authType, baseUrl, canonicalName, description, "", // discoveryDocUrl (only intended to be overridden).
            id, methods, name, ownerDomain, resources, revision, rootUrl, schemas, servicePath, title, version,
            versionModule);

    for (Schema schema : schemas.values()) {
        schema.setParent(thisDocument);
    }
    for (Method method : methods) {
        method.setParent(thisDocument);
    }
    for (List<Method> resourceMethods : resources.values()) {
        for (Method method : resourceMethods) {
            method.setParent(thisDocument);
        }
    }

    return thisDocument;
}

From source file:io.takari.swagger.ReflectionHelper.java

public static Iterable<Field> getAllDeclaredFields(Class<?> type) {
    ImmutableList.Builder<Field> fields = ImmutableList.builder();
    for (Class<?> clazz = type; clazz != null && !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
        fields.addAll(ImmutableList.copyOf(clazz.getDeclaredFields()));
    }//ww  w  .  j  a v  a2  s . c  o  m
    return fields.build();
}

From source file:com.spotify.heroic.metric.FetchData.java

@Deprecated
public static Collector<FetchData, FetchData> collect(final QueryTrace.Identifier what) {
    final Collector<Result, Result> resultCollector = collectResult(what);

    return fetchDataCollection -> {
        final ImmutableList.Builder<Long> times = ImmutableList.builder();
        final Map<MetricType, ImmutableList.Builder<Metric>> fetchGroups = new HashMap<>();
        final ImmutableList.Builder<Result> results = ImmutableList.builder();

        for (final FetchData fetch : fetchDataCollection) {
            times.addAll(fetch.times);
            results.add(fetch.result);/*  ww  w.  j  av a  2s  .  com*/

            for (final MetricCollection g : fetch.groups) {
                ImmutableList.Builder<Metric> data = fetchGroups.get(g.getType());

                if (data == null) {
                    data = new ImmutableList.Builder<>();
                    fetchGroups.put(g.getType(), data);
                }

                data.addAll(g.data);
            }
        }

        final List<MetricCollection> groups = fetchGroups.entrySet().stream()
                .map((e) -> MetricCollection.build(e.getKey(),
                        Ordering.from(Metric.comparator()).immutableSortedCopy(e.getValue().build())))
                .collect(Collectors.toList());

        return new FetchData(resultCollector.collect(results.build()), times.build(), groups);
    };
}

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

static GoCompile createGoCompileRule(BuildRuleParams params, BuildRuleResolver resolver,
        GoBuckConfig goBuckConfig, Path packageName, ImmutableSet<SourcePath> srcs, List<String> compilerFlags,
        List<String> assemblerFlags, GoPlatform platform, Iterable<BuildTarget> deps)
        throws NoSuchBuildTargetException {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);

    Preconditions.checkState(params.getBuildTarget().getFlavors().contains(platform.getFlavor()));

    ImmutableSet<GoLinkable> linkables = requireGoLinkables(params.getBuildTarget(), resolver, platform, deps);

    ImmutableList.Builder<BuildRule> linkableDepsBuilder = ImmutableList.builder();
    for (GoLinkable linkable : linkables) {
        linkableDepsBuilder.addAll(linkable.getDeps(ruleFinder));
    }//from  ww w. j a va2s . c om
    ImmutableList<BuildRule> linkableDeps = linkableDepsBuilder.build();

    BuildTarget target = createSymlinkTreeTarget(params.getBuildTarget());
    SymlinkTree symlinkTree = makeSymlinkTree(params.copyWithBuildTarget(target), pathResolver, ruleFinder,
            linkables);
    resolver.addToIndex(symlinkTree);

    LOG.verbose("Symlink tree for compiling %s: %s", params.getBuildTarget(), symlinkTree.getLinks());

    return new GoCompile(params.appendExtraDeps(linkableDeps).appendExtraDeps(ImmutableList.of(symlinkTree)),
            pathResolver, symlinkTree, packageName,
            getPackageImportMap(goBuckConfig.getVendorPaths(), params.getBuildTarget().getBasePath(),
                    FluentIterable.from(linkables)
                            .transformAndConcat(new Function<GoLinkable, ImmutableSet<Path>>() {
                                @Override
                                public ImmutableSet<Path> apply(GoLinkable input) {
                                    return input.getGoLinkInput().keySet();
                                }
                            })),
            ImmutableSet.copyOf(srcs), ImmutableList.copyOf(compilerFlags), goBuckConfig.getCompiler(),
            ImmutableList.copyOf(assemblerFlags), goBuckConfig.getAssemblerIncludeDirs(),
            goBuckConfig.getAssembler(), goBuckConfig.getPacker(), platform);
}

From source file:io.takari.swagger.ReflectionHelper.java

public static Iterable<Method> getAllDeclaredMethods(Class<?> type) {
    ImmutableList.Builder<Method> methods = ImmutableList.builder();

    for (Class<?> clazz = type; clazz != null && !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
        methods.addAll(ImmutableList.copyOf(clazz.getDeclaredMethods()));
    }/*  w w  w  .j  a  va  2  s  .c o m*/
    return methods.build();
}

From source file:org.fixb.meta.FixMetaScanner.java

static <T> FixBlockMeta<T> scanClass(Class<T> model, MutableFixMetaDictionary dictionary) {
    if (dictionary.containsMeta(model)) {
        return dictionary.getComponentMeta(model);
    }/* w  w  w .  java 2  s  . co  m*/

    final FixBlockMeta<T> result;

    if (model.getConstructors().length == 0) {
        throw new FixException("Class [" + model.getName() + "] does not provide a public constructor.");
    }

    @SuppressWarnings("unchecked")
    Optional<Constructor<T>> constructor = Optional.of((Constructor<T>) model.getConstructors()[0]);

    final int c = numberOfFixParameters(constructor.get());

    if (c == 0) {
        constructor = Optional.absent();
    } else if (c != constructor.get().getParameterTypes().length) {
        throw new FixException(
                "Some constructor parameters don't have FIX mapping in class [" + model.getName() + "].");
    }

    if (model.isAnnotationPresent(FixMessage.class)) {
        final FixMessage messageAnnotation = model.getAnnotation(FixMessage.class);
        ImmutableList.Builder<FixFieldMeta> allFieldsBuilder = ImmutableList.builder();
        allFieldsBuilder.addAll(processConstantFields(messageAnnotation)); // add constant fields
        allFieldsBuilder.addAll(processFields(model, constructor, dictionary)); // add all other fields
        result = new FixMessageMeta<>(model, messageAnnotation.type(), allFieldsBuilder.build(),
                constructor.isPresent());
    } else if (model.isAnnotationPresent(FixBlock.class)) {
        final List<FixFieldMeta> fixFields = processFields(model, constructor, dictionary);
        result = new FixBlockMeta<>(model, fixFields, constructor.isPresent());
    } else {
        throw new FixException(
                "Neither @FixBlock nor @FixMessage annotation present on class [" + model.getName() + "].");
    }

    return result;
}

From source file:com.google.devtools.moe.client.repositories.RevisionMetadata.java

/**
 * @return a single RevisionMetadata concatenating the information in the given List
 *///w  w w.jav a  2s. c o  m
public static RevisionMetadata concatenate(List<RevisionMetadata> rms, @Nullable Revision migrationFromRev) {
    Preconditions.checkArgument(!rms.isEmpty());

    ImmutableList.Builder<String> idBuilder = ImmutableList.builder();
    ImmutableList.Builder<String> authorBuilder = ImmutableList.builder();
    DateTime newDate = new DateTime(0L);
    ImmutableList.Builder<String> descBuilder = ImmutableList.builder();
    ImmutableList.Builder<Revision> parentBuilder = ImmutableList.builder();

    for (RevisionMetadata rm : rms) {
        idBuilder.add(rm.id);
        authorBuilder.add(rm.author);
        if (newDate.isBefore(rm.date)) {
            newDate = rm.date;
        }
        descBuilder.add(rm.description);
        parentBuilder.addAll(rm.parents);
    }

    if (migrationFromRev != null) {
        descBuilder.add("Created by MOE: https://github.com/google/moe\n" + "MOE_MIGRATED_REVID="
                + migrationFromRev.revId());
    }

    String newId = Joiner.on(", ").join(idBuilder.build());
    String newAuthor = Joiner.on(", ").join(authorBuilder.build());
    String newDesc = Joiner.on("\n-------------\n").join(descBuilder.build());
    ImmutableList<Revision> newParents = parentBuilder.build();

    return new RevisionMetadata(newId, newAuthor, newDate, newDesc, newParents);
}