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.cli.Config.java

public static Config createDefaultConfig(Path root,
        ImmutableMap<String, ImmutableMap<String, String>> configOverrides) throws IOException {
    ImmutableList.Builder<Path> configFileBuilder = ImmutableList.builder();

    configFileBuilder.addAll(listFiles(GLOBAL_BUCK_CONFIG_DIRECTORY_PATH));
    if (Files.isRegularFile(GLOBAL_BUCK_CONFIG_FILE_PATH)) {
        configFileBuilder.add(GLOBAL_BUCK_CONFIG_FILE_PATH);
    }/* w  w w.  ja v  a2s  .co m*/

    Path homeDirectory = Paths.get(System.getProperty("user.home"));
    Path userConfigDir = homeDirectory.resolve(DEFAULT_BUCK_CONFIG_DIRECTORY_NAME);
    configFileBuilder.addAll(listFiles(userConfigDir));
    Path userConfigFile = homeDirectory.resolve(DEFAULT_BUCK_CONFIG_FILE_NAME);
    if (Files.isRegularFile(userConfigFile)) {
        configFileBuilder.add(userConfigFile);
    }

    Path configFile = root.resolve(DEFAULT_BUCK_CONFIG_FILE_NAME);
    if (Files.isRegularFile(configFile)) {
        configFileBuilder.add(configFile);
    }
    Path overrideConfigFile = root.resolve(DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME);
    if (Files.isRegularFile(overrideConfigFile)) {
        configFileBuilder.add(overrideConfigFile);
    }

    ImmutableList<Path> configFiles = configFileBuilder.build();

    ImmutableList.Builder<ImmutableMap<String, ImmutableMap<String, String>>> builder = ImmutableList.builder();
    for (Path file : configFiles) {
        try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
            ImmutableMap<String, ImmutableMap<String, String>> parsedConfiguration = Inis.read(reader);
            LOG.debug("Loaded a configuration file %s: %s", file, parsedConfiguration);
            builder.add(parsedConfiguration);
        }
    }
    LOG.debug("Adding configuration overrides: %s", configOverrides);
    builder.add(configOverrides);
    return new Config(builder.build());
}

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

protected static RustCompileRule createBuild(BuildTarget target, String crateName, BuildRuleParams params,
        BuildRuleResolver resolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder,
        CxxPlatform cxxPlatform, RustBuckConfig rustConfig, ImmutableList<String> extraFlags,
        ImmutableList<String> extraLinkerFlags, Iterable<Arg> linkerInputs, CrateType crateType,
        Linker.LinkableDepType depType, boolean rpath, ImmutableSortedSet<SourcePath> sources,
        SourcePath rootModule) throws NoSuchBuildTargetException {
    ImmutableSortedSet<BuildRule> ruledeps = params.getDeps();
    ImmutableList.Builder<Arg> linkerArgs = ImmutableList.builder();

    Stream.concat(rustConfig.getLinkerArgs(cxxPlatform).stream(), extraLinkerFlags.stream()).map(StringArg::new)
            .forEach(linkerArgs::add);//from  w  ww .j  ava2 s. c om

    linkerArgs.addAll(linkerInputs);

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

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

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

    // Find direct and transitive Rust deps. 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.
    new AbstractBreadthFirstTraversal<BuildRule>(ruledeps) {
        private final ImmutableSet<BuildRule> empty = ImmutableSet.of();

        @Override
        public Iterable<BuildRule> visit(BuildRule rule) {
            ImmutableSet<BuildRule> deps = empty;
            if (rule instanceof RustLinkable) {
                deps = rule.getDeps();
                Arg arg = ((RustLinkable) rule).getLinkerArg(ruledeps.contains(rule), cxxPlatform, depType);

                args.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, ruledeps,
                depType, RustLinkable.class::isInstance, RustLinkable.class::isInstance).getArgs();

        // Add necessary rpaths if we're dynamically linking with things
        // XXX currently breaks on paths containing commas, which all of ours do: see
        // https://github.com/rust-lang/rust/issues/38795
        if (rpath && depType == Linker.LinkableDepType.SHARED) {
            args.add(new StringArg("-Crpath"));
        }

        linkerArgs.addAll(nativeArgs);

        // Also let rustc know about libraries as native deps (in case someone is using #[link]
        // even though it won't generally work with Buck)
        nativeArgs.stream().filter(HasSourcePath.class::isInstance).map(sp -> (HasSourcePath) sp)
                .map(sp -> sp.getPathResolver().getRelativePath(sp.getPath()).getParent())
                .map(dir -> String.format("-Lnative=%s", dir)).map(StringArg::new).forEach(args::add);
    }

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

    String filename = crateType.filenameFor(crateName, cxxPlatform);

    return resolver.addToIndex(RustCompileRule.from(ruleFinder, params.copyWithBuildTarget(target),
            pathResolver, filename, rustConfig.getRustCompiler().resolve(resolver),
            rustConfig.getLinkerProvider(cxxPlatform, cxxPlatform.getLd().getType()).resolve(resolver),
            args.build(), linkerArgs.build(), sources, rootModule));
}

From source file:io.airlift.http.server.HttpRequestEvent.java

public static HttpRequestEvent createHttpRequestEvent(Request request, Response response,
        TraceTokenManager traceTokenManager, long currentTimeInMillis) {
    String user = null;//from w  ww  .  j  a va 2 s .  com
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        user = principal.getName();
    }

    String token = null;
    if (traceTokenManager != null) {
        token = traceTokenManager.getCurrentRequestToken();
    }

    long dispatchTime = request.getTimeStamp();
    long timeToDispatch = max(dispatchTime - request.getTimeStamp(), 0);

    Long timeToFirstByte = null;
    Object firstByteTime = request.getAttribute(TimingFilter.FIRST_BYTE_TIME);
    if (firstByteTime instanceof Long) {
        Long time = (Long) firstByteTime;
        timeToFirstByte = max(time - request.getTimeStamp(), 0);
    }

    long timeToLastByte = max(currentTimeInMillis - request.getTimeStamp(), 0);

    ImmutableList.Builder<String> builder = ImmutableList.builder();
    if (request.getRemoteAddr() != null) {
        builder.add(request.getRemoteAddr());
    }
    for (Enumeration<String> e = request.getHeaders("X-FORWARDED-FOR"); e != null && e.hasMoreElements();) {
        String forwardedFor = e.nextElement();
        builder.addAll(Splitter.on(',').trimResults().omitEmptyStrings().split(forwardedFor));
    }
    String clientAddress = null;
    ImmutableList<String> clientAddresses = builder.build();
    for (String address : Lists.reverse(clientAddresses)) {
        try {
            if (!Inet4Networks.isPrivateNetworkAddress(address)) {
                clientAddress = address;
                break;
            }
        } catch (IllegalArgumentException ignored) {
        }
    }
    if (clientAddress == null) {
        clientAddress = request.getRemoteAddr();
    }

    String requestUri = null;
    if (request.getUri() != null) {
        requestUri = request.getUri().toString();
    }

    String method = request.getMethod();
    if (method != null) {
        method = method.toUpperCase();
    }

    String protocol = request.getHeader("X-FORWARDED-PROTO");
    if (protocol == null) {
        protocol = request.getScheme();
    }
    if (protocol != null) {
        protocol = protocol.toLowerCase();
    }

    return new HttpRequestEvent(new DateTime(request.getTimeStamp()), token, clientAddress, protocol, method,
            requestUri, user, request.getHeader("User-Agent"), request.getHeader("Referer"),
            request.getContentRead(), request.getHeader("Content-Type"), response.getContentCount(),
            response.getStatus(), response.getHeader("Content-Type"), timeToDispatch, timeToFirstByte,
            timeToLastByte);
}

From source file:com.facebook.buck.core.rules.knowntypes.KnownBuildRuleDescriptionsFactory.java

static ImmutableList<Description<?>> createBuildDescriptions(BuckConfig config, ProcessExecutor processExecutor,
        ToolchainProvider toolchainProvider, PluginManager pluginManager,
        SandboxExecutionStrategyFactory sandboxExecutionStrategyFactory) {

    ImmutableList.Builder<Description<?>> builder = ImmutableList.builder();

    SandboxExecutionStrategy sandboxExecutionStrategy = sandboxExecutionStrategyFactory.create(processExecutor,
            config);/*from  w  ww . j a v  a2 s .com*/

    DescriptionCreationContext descriptionCreationContext = DescriptionCreationContext.of(config,
            toolchainProvider, sandboxExecutionStrategy, pluginManager);
    List<DescriptionProvider> descriptionProviders = pluginManager.getExtensions(DescriptionProvider.class);
    for (DescriptionProvider provider : descriptionProviders) {
        builder.addAll(provider.getDescriptions(descriptionCreationContext));
    }

    return builder.build();
}

From source file:gobblin.yarn.ContainerMetrics.java

private static List<Tag<?>> tagsForContainer(State containerState, String applicationName,
        ContainerId containerId) {// w ww .ja v a 2 s .c  o m
    ImmutableList.Builder<Tag<?>> tags = new ImmutableList.Builder<>();
    tags.add(new Tag<>(GobblinYarnMetricTagNames.YARN_APPLICATION_NAME, applicationName));
    tags.add(new Tag<>(GobblinYarnMetricTagNames.YARN_APPLICATION_ID,
            containerId.getApplicationAttemptId().getApplicationId().toString()));
    tags.add(new Tag<>(GobblinYarnMetricTagNames.YARN_APPLICATION_ATTEMPT_ID,
            containerId.getApplicationAttemptId().toString()));
    tags.add(new Tag<>(GobblinYarnMetricTagNames.CONTAINER_ID, containerId.toString()));
    tags.addAll(getCustomTagsFromState(containerState));
    return tags.build();
}

From source file:com.facebook.buck.rules.modern.ModernBuildRule.java

/**
 * Returns the build steps for the Buildable. Unlike getBuildSteps(), this does not record outputs
 * (callers should call recordOutputs() themselves).
 *///www  .  ja va  2 s.co  m
public static <T extends Buildable> ImmutableList<Step> stepsForBuildable(BuildContext context, T buildable,
        ProjectFilesystem filesystem, BuildTarget buildTarget, Iterable<Path> outputs) {
    ImmutableList.Builder<Step> stepBuilder = ImmutableList.builder();
    OutputPathResolver outputPathResolver = new DefaultOutputPathResolver(filesystem, buildTarget);
    getSetupStepsForBuildable(context, filesystem, outputs, stepBuilder, outputPathResolver);

    stepBuilder.addAll(buildable.getBuildSteps(context, filesystem, outputPathResolver,
            getBuildCellPathFactory(context, filesystem, outputPathResolver)));

    // TODO(cjhopman): This should probably be handled by the build engine.
    if (context.getShouldDeleteTemporaries()) {
        stepBuilder.add(RmStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(),
                filesystem, outputPathResolver.getTempPath())).withRecursive(true));
    }

    return stepBuilder.build();
}

From source file:com.palantir.typescript.TypeScriptProjects.java

private static List<IContainer> getContainers(IProject project, Folders folders) {
    checkNotNull(project);//from   w  ww  . j  av a  2s .c o  m
    checkNotNull(folders);

    ImmutableList.Builder<IContainer> containers = ImmutableList.builder();

    boolean addExported = (folders == Folders.EXPORTED || folders == Folders.SOURCE_AND_EXPORTED);
    boolean addSource = (folders == Folders.SOURCE || folders == Folders.SOURCE_AND_EXPORTED);

    if (addExported) {
        containers.addAll(getFoldersFromPreference(project, IPreferenceConstants.BUILD_PATH_EXPORTED_FOLDER));
    }

    if (addSource) {
        List<IContainer> sourceFolders = getFoldersFromPreference(project,
                IPreferenceConstants.BUILD_PATH_SOURCE_FOLDER);

        // if no source folders are explicitly set, return the entire project
        if (sourceFolders.isEmpty()) {
            sourceFolders = ImmutableList.<IContainer>of(project);
        }

        containers.addAll(sourceFolders);
    }

    return containers.build();
}

From source file:io.prestosql.operator.UnnestOperator.java

private static List<Type> getUnnestedTypes(List<Type> types, boolean isLegacyUnnest) {
    ImmutableList.Builder<Type> builder = ImmutableList.builder();
    for (Type type : types) {
        checkArgument(type instanceof ArrayType || type instanceof MapType,
                "Can only unnest map and array types");
        if (type instanceof ArrayType && !isLegacyUnnest
                && ((ArrayType) type).getElementType() instanceof RowType) {
            builder.addAll(((ArrayType) type).getElementType().getTypeParameters());
        } else {/* ww w  .  j  a v  a 2s  .com*/
            builder.addAll(type.getTypeParameters());
        }
    }
    return builder.build();
}

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

/**
 * Splits all UUID arguments into two arguments (UUID and String) for support of both
 * UUID and String with-constructors. All non-UUID arguments are left unmodified.
 *///from   ww w .j a  v  a2  s .com
protected static ImmutableList<Arguments> splitAllUuidOptionalArguments(
        final ImmutableList<Arguments> arguments) {
    if (isEmpty(arguments)) {
        return ImmutableList.of();
    }
    final ImmutableList.Builder<Arguments> builder = ImmutableList.builder();
    for (final Arguments arg : arguments) {
        builder.addAll(splitUuidOptionalArgument(arg));
    }
    return builder.build();
}

From source file:me.yanaga.guava.stream.MoreCollectors.java

public static <T> Collector<T, ?, ImmutableList<T>> toImmutableList() {
    return Collector.of(ImmutableList::builder, new BiConsumer<ImmutableList.Builder<T>, T>() {
        @Override/*from  ww w .  j a va  2 s. co  m*/
        public void accept(ImmutableList.Builder<T> objectBuilder, T t) {
            objectBuilder.add(t);
        }
    }, new BinaryOperator<ImmutableList.Builder<T>>() {
        @Override
        public ImmutableList.Builder<T> apply(ImmutableList.Builder<T> objectBuilder,
                ImmutableList.Builder<T> objectBuilder2) {
            return objectBuilder.addAll(objectBuilder2.build());
        }
    }, new Function<ImmutableList.Builder<T>, ImmutableList<T>>() {
        @Override
        public ImmutableList<T> apply(ImmutableList.Builder<T> tBuilder) {
            return tBuilder.build();
        }
    }, UNORDERED, CONCURRENT);
}