Example usage for com.google.common.collect ImmutableSet.Builder addAll

List of usage examples for com.google.common.collect ImmutableSet.Builder addAll

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet.Builder addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

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

@Override
public Iterable<BuildTarget> findDepsForTargetFromConstructorArgs(BuildTarget buildTarget,
        CellPathResolver cellRoots, Arg constructorArg) {
    ImmutableSet.Builder<BuildTarget> targets = ImmutableSet.builder();

    // Add in all parse time deps from the C/C++ platforms.
    for (CxxPlatform cxxPlatform : cxxPlatforms.getValues()) {
        targets.addAll(CxxPlatforms.getParseTimeDeps(cxxPlatform));
    }/*from w  w  w . j a va 2s .co m*/

    // Add in parse time deps from parent.
    targets.addAll(super.findDepsForTargetFromConstructorArgs(buildTarget, cellRoots, constructorArg));

    return targets.build();
}

From source file:com.facebook.buck.skylark.parser.SkylarkProjectBuildFileParser.java

private ImmutableSet<String> toIncludedPaths(String containingPath, ImmutableList<IncludesData> dependencies,
        @Nullable ExtensionData implicitLoadExtensionData) {
    ImmutableSet.Builder<String> includedPathsBuilder = ImmutableSet.builder();
    includedPathsBuilder.add(containingPath);
    // for loop is used instead of foreach to avoid iterator overhead, since it's a hot spot
    for (int i = 0; i < dependencies.size(); ++i) {
        includedPathsBuilder.addAll(dependencies.get(i).getLoadTransitiveClosure());
    }//from   w w  w . j ava2s.  c o  m
    if (implicitLoadExtensionData != null) {
        includedPathsBuilder.addAll(implicitLoadExtensionData.getLoadTransitiveClosure());
    }
    return includedPathsBuilder.build();
}

From source file:google.registry.tools.CreateOrUpdateRegistrarCommand.java

@Override
protected final void init() throws Exception {
    initRegistrarCommand();/* www .j a  v a  2 s  . c  o m*/
    DateTime now = DateTime.now(UTC);
    for (String clientId : mainParameters) {
        Registrar oldRegistrar = getOldRegistrar(clientId);
        Registrar.Builder builder = (oldRegistrar == null) ? new Registrar.Builder().setClientId(clientId)
                : oldRegistrar.asBuilder();

        if (!isNullOrEmpty(password)) {
            builder.setPassword(password);
        }
        if (!isNullOrEmpty(registrarName)) {
            builder.setRegistrarName(registrarName);
        }
        if (email != null) {
            builder.setEmailAddress(email.orNull());
        }
        if (url != null) {
            builder.setUrl(url.orNull());
        }
        if (phone != null) {
            builder.setPhoneNumber(phone.orNull());
        }
        if (fax != null) {
            builder.setFaxNumber(fax.orNull());
        }
        if (registrarType != null) {
            builder.setType(registrarType);
        }
        if (registrarState != null) {
            builder.setState(registrarState);
        }
        if (driveFolderId != null) {
            builder.setDriveFolderId(driveFolderId.orNull());
        }
        if (!allowedTlds.isEmpty()) {
            checkArgument(addAllowedTlds.isEmpty(), "Can't specify both --allowedTlds and --addAllowedTlds");
            ImmutableSet.Builder<String> allowedTldsBuilder = new ImmutableSet.Builder<>();
            for (String allowedTld : allowedTlds) {
                allowedTldsBuilder.add(canonicalizeDomainName(allowedTld));
            }
            builder.setAllowedTlds(allowedTldsBuilder.build());
        }
        if (!addAllowedTlds.isEmpty()) {
            ImmutableSet.Builder<String> allowedTldsBuilder = new ImmutableSet.Builder<>();
            if (oldRegistrar != null) {
                allowedTldsBuilder.addAll(oldRegistrar.getAllowedTlds());
            }
            for (String allowedTld : addAllowedTlds) {
                allowedTldsBuilder.add(canonicalizeDomainName(allowedTld));
            }
            builder.setAllowedTlds(allowedTldsBuilder.build());
        }
        if (!ipWhitelist.isEmpty()) {
            ImmutableList.Builder<CidrAddressBlock> ipWhitelistBuilder = new ImmutableList.Builder<>();
            if (!(ipWhitelist.size() == 1 && ipWhitelist.get(0).contains("null"))) {
                for (String ipRange : ipWhitelist) {
                    ipWhitelistBuilder.add(CidrAddressBlock.create(ipRange));
                }
            }
            builder.setIpAddressWhitelist(ipWhitelistBuilder.build());
        }
        if (clientCertificateFilename != null) {
            String asciiCert = new String(Files.readAllBytes(clientCertificateFilename), US_ASCII);
            builder.setClientCertificate(asciiCert, now);
        }
        if (failoverClientCertificateFilename != null) {
            String asciiCert = new String(Files.readAllBytes(failoverClientCertificateFilename), US_ASCII);
            builder.setFailoverClientCertificate(asciiCert, now);
        }
        if (!isNullOrEmpty(clientCertificateHash)) {
            checkArgument(clientCertificateFilename == null, "Can't specify both --cert_hash and --cert_file");
            if ("null".equals(clientCertificateHash)) {
                clientCertificateHash = null;
            }
            builder.setClientCertificateHash(clientCertificateHash);
        }
        if (ianaId != null) {
            builder.setIanaIdentifier(ianaId.orNull());
        }
        if (billingId != null) {
            builder.setBillingIdentifier(billingId.orNull());
        }
        if (billingMethod != null) {
            if (oldRegistrar != null && !billingMethod.equals(oldRegistrar.getBillingMethod())) {
                Map<CurrencyUnit, Money> balances = RegistrarBillingUtils.loadBalance(oldRegistrar);
                for (Money balance : balances.values()) {
                    checkState(balance.isZero(),
                            "Refusing to change billing method on Registrar '%s' from %s to %s"
                                    + " because current balance is non-zero: %s",
                            clientId, oldRegistrar.getBillingMethod(), billingMethod, balances);
                }
            }
            builder.setBillingMethod(billingMethod);
        }
        List<Object> streetAddressFields = Arrays.asList(street, city, state, zip, countryCode);
        checkArgument(
                Iterables.any(streetAddressFields, isNull()) == Iterables.all(streetAddressFields, isNull()),
                "Must specify all fields of address");
        if (street != null) {
            // We always set the localized address for now. That should be safe to do since it supports
            // unrestricted UTF-8.
            builder.setLocalizedAddress(new RegistrarAddress.Builder().setStreet(ImmutableList.copyOf(street))
                    .setCity(city).setState("null".equals(state) ? null : state)
                    .setZip("null".equals(zip) ? null : zip).setCountryCode(countryCode).build());
        }
        if (blockPremiumNames != null) {
            builder.setBlockPremiumNames(blockPremiumNames);
        }
        if (contactsRequireSyncing != null) {
            builder.setContactsRequireSyncing(contactsRequireSyncing);
        }
        // When creating a new REAL registrar or changing the type to REAL, a passcode is required.
        // Leave existing REAL registrars alone.
        if (Registrar.Type.REAL.equals(registrarType)
                && (oldRegistrar == null || oldRegistrar.getPhonePasscode() == null)) {
            checkArgument(phonePasscode != null, "--passcode is required for REAL registrars.");
        }
        if (phonePasscode != null) {
            builder.setPhonePasscode(phonePasscode);
        }
        if (icannReferralEmail != null) {
            builder.setIcannReferralEmail(icannReferralEmail);
        }
        if (whoisServer != null) {
            builder.setWhoisServer(whoisServer);
        }

        // If the registrarName is being set, verify that it is either null or it normalizes uniquely.
        String oldRegistrarName = (oldRegistrar == null) ? null : oldRegistrar.getRegistrarName();
        if (registrarName != null && !registrarName.equals(oldRegistrarName)) {
            String normalizedName = normalizeRegistrarName(registrarName);
            for (Registrar registrar : Registrar.loadAll()) {
                if (registrar.getRegistrarName() != null) {
                    checkArgument(!normalizedName.equals(normalizeRegistrarName(registrar.getRegistrarName())),
                            "The registrar name %s normalizes identically to existing registrar name %s",
                            registrarName, registrar.getRegistrarName());
                }
            }
        }

        stageEntityChange(oldRegistrar, builder.build());
    }
}

From source file:com.facebook.buck.apple.xcode.WorkspaceAndProjectGenerator.java

public Path generateWorkspaceAndDependentProjects(Map<TargetNode<?>, ProjectGenerator> projectGenerators)
        throws IOException {
    LOG.debug("Generating workspace for target %s", workspaceTargetNode);

    String workspaceName;/* ww w .  j  a v  a  2  s.  c  o  m*/
    Path outputDirectory;

    if (combinedProject) {
        workspaceName = "GeneratedProject";
        outputDirectory = Paths.get("_gen");
    } else {
        workspaceName = XcodeWorkspaceConfigDescription
                .getWorkspaceNameFromArg(workspaceTargetNode.getConstructorArg());
        outputDirectory = workspaceTargetNode.getBuildTarget().getBasePath();
    }

    WorkspaceGenerator workspaceGenerator = new WorkspaceGenerator(projectFilesystem, workspaceName,
            outputDirectory);

    ImmutableSet<TargetNode<?>> orderedTargetNodes;
    if (workspaceTargetNode.getConstructorArg().srcTarget.isPresent()) {
        orderedTargetNodes = AppleBuildRules.getSchemeBuildableTargetNodes(projectGraph,
                projectGraph.get(workspaceTargetNode.getConstructorArg().srcTarget.get().getBuildTarget()));
    } else {
        orderedTargetNodes = ImmutableSet.of();
    }

    ImmutableSet<TargetNode<?>> orderedTestTargetNodes;
    ImmutableSet<TargetNode<?>> orderedTestBundleTargetNodes;
    {
        ImmutableSet.Builder<TargetNode<?>> orderedTestTargetNodesBuilder = ImmutableSet.builder();
        ImmutableSet.Builder<TargetNode<?>> orderedTestBundleTargetNodesBuilder = ImmutableSet.builder();

        getOrderedTestNodes(projectGraph, sourceTargetToTestNodes, orderedTargetNodes,
                extraTestBundleTargetNodes, orderedTestTargetNodesBuilder, orderedTestBundleTargetNodesBuilder);

        orderedTestTargetNodes = orderedTestTargetNodesBuilder.build();
        orderedTestBundleTargetNodes = orderedTestBundleTargetNodesBuilder.build();
    }

    ImmutableSet<BuildTarget> targetsInRequiredProjects = FluentIterable
            .from(Sets.union(orderedTargetNodes, orderedTestTargetNodes)).transform(HasBuildTarget.TO_TARGET)
            .toSet();
    ImmutableMap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();

    if (combinedProject) {
        ImmutableSet.Builder<BuildTarget> initialTargetsBuilder = ImmutableSet.builder();
        for (TargetNode<?> targetNode : projectGraph.getNodes()) {
            if (targetNode.getType() != XcodeProjectConfigDescription.TYPE) {
                continue;
            }
            XcodeProjectConfigDescription.Arg projectArg = (XcodeProjectConfigDescription.Arg) targetNode
                    .getConstructorArg();
            if (Sets.intersection(targetsInRequiredProjects, projectArg.rules).isEmpty()) {
                continue;
            }
            initialTargetsBuilder.addAll(projectArg.rules);
        }

        LOG.debug("Generating a combined project");
        ProjectGenerator generator = new ProjectGenerator(projectGraph, initialTargetsBuilder.build(),
                projectFilesystem, executionContext, buildRuleResolver, sourcePathResolver, outputDirectory,
                "GeneratedProject", projectGeneratorOptions);
        combinedProjectGenerator = Optional.of(generator);
        generator.createXcodeProjects();

        workspaceGenerator.addFilePath(generator.getProjectPath());

        buildTargetToPbxTargetMapBuilder.putAll(generator.getBuildTargetToGeneratedTargetMap());
        for (PBXTarget target : generator.getBuildTargetToGeneratedTargetMap().values()) {
            targetToProjectPathMapBuilder.put(target, generator.getProjectPath());
        }
    } else {
        for (TargetNode<?> targetNode : projectGraph.getNodes()) {
            if (targetNode.getType() != XcodeProjectConfigDescription.TYPE) {
                continue;
            }
            XcodeProjectConfigDescription.Arg projectArg = (XcodeProjectConfigDescription.Arg) targetNode
                    .getConstructorArg();
            if (Sets.intersection(targetsInRequiredProjects, projectArg.rules).isEmpty()) {
                continue;
            }

            ProjectGenerator generator = projectGenerators.get(targetNode);
            if (generator == null) {
                LOG.debug("Generating project for target %s", targetNode);
                generator = new ProjectGenerator(projectGraph, projectArg.rules, projectFilesystem,
                        executionContext, buildRuleResolver, sourcePathResolver,
                        targetNode.getBuildTarget().getBasePath(), projectArg.projectName,
                        projectGeneratorOptions);
                generator.createXcodeProjects();
                projectGenerators.put(targetNode, generator);
            } else {
                LOG.debug("Already generated project for target %s, skipping", targetNode);
            }

            workspaceGenerator.addFilePath(generator.getProjectPath());

            buildTargetToPbxTargetMapBuilder.putAll(generator.getBuildTargetToGeneratedTargetMap());
            for (PBXTarget target : generator.getBuildTargetToGeneratedTargetMap().values()) {
                targetToProjectPathMapBuilder.put(target, generator.getProjectPath());
            }
        }
    }

    Path workspacePath = workspaceGenerator.writeWorkspace();

    SchemeGenerator schemeGenerator = new SchemeGenerator(projectFilesystem,
            workspaceTargetNode.getConstructorArg().srcTarget,
            Iterables.transform(orderedTargetNodes, HasBuildTarget.TO_TARGET),
            Iterables.transform(orderedTestTargetNodes, HasBuildTarget.TO_TARGET),
            Iterables.transform(orderedTestBundleTargetNodes, HasBuildTarget.TO_TARGET), workspaceName,
            outputDirectory.resolve(workspaceName + ".xcworkspace"),
            XcodeWorkspaceConfigDescription
                    .getActionConfigNamesFromArg(workspaceTargetNode.getConstructorArg()),
            buildTargetToPbxTargetMapBuilder.build(), targetToProjectPathMapBuilder.build());
    schemeGenerator.writeScheme();

    return workspacePath;
}

From source file:com.facebook.presto.hive.metastore.ThriftHiveMetastore.java

@Override
public Set<HivePrivilegeInfo> getDatabasePrivileges(String user, String databaseName) {
    ImmutableSet.Builder<HivePrivilegeInfo> privileges = ImmutableSet.builder();

    if (isDatabaseOwner(user, databaseName)) {
        privileges.add(new HivePrivilegeInfo(OWNERSHIP, true));
    }/*from w  w w . j  a v a  2 s .  c om*/
    privileges.addAll(getUserPrivileges(new HivePrincipal(user, USER),
            new HiveObjectRef(DATABASE, databaseName, null, null, null)));

    return privileges.build();
}

From source file:com.github.jsdossier.jscomp.TypeRegistry.java

/**
 * Returns the interfaces implemented by the given type. If the type is itself an interface, this
 * will return the interfaces it extends.
 *///www. j av a  2  s. c  o m
public ImmutableSet<JSType> getImplementedTypes(NominalType nominalType, JSTypeRegistry jsRegistry) {
    JSType type = nominalType.getType();
    ImmutableSet.Builder<JSType> builder = ImmutableSet.builder();
    if (type.isConstructor()) {
        for (JSType jsType : getTypeHierarchy(type, jsRegistry)) {
            if (jsType.getJSDocInfo() != null) {
                for (JSTypeExpression expr : jsType.getJSDocInfo().getImplementedInterfaces()) {
                    JSType exprType = expr.evaluate(null, jsRegistry);
                    if (exprType.getJSDocInfo() != null) {
                        builder.addAll(getExtendedInterfaces(exprType.getJSDocInfo(), jsRegistry));
                    }
                    builder.add(exprType);
                }

            } else if (jsType.isInstanceType()) {
                Collection<NominalType> types = getTypes(jsType);
                if (!types.isEmpty()) {
                    NominalType nt = types.iterator().next();
                    if (nt != nominalType) {
                        builder.addAll(getImplementedTypes(nt, jsRegistry));
                    }
                }
            }
        }
    } else if (type.isInterface()) {
        builder.addAll(getExtendedInterfaces(nominalType.getJsDoc().getInfo(), jsRegistry));
    }
    return builder.build();
}

From source file:com.facebook.presto.hive.metastore.ThriftHiveMetastore.java

@Override
public Set<HivePrivilegeInfo> getTablePrivileges(String user, String databaseName, String tableName) {
    ImmutableSet.Builder<HivePrivilegeInfo> privileges = ImmutableSet.builder();

    if (isTableOwner(user, databaseName, tableName)) {
        privileges.add(new HivePrivilegeInfo(OWNERSHIP, true));
    }/*from w  w w . ja v a  2  s  . c o m*/
    privileges.addAll(getUserPrivileges(new HivePrincipal(user, USER),
            new HiveObjectRef(TABLE, databaseName, tableName, null, null)));

    return privileges.build();
}

From source file:org.obm.domain.dao.UserDaoJdbcImpl.java

@Override
public ImmutableSet<String> getAllEmailsFrom(ObmDomain domain, UserExtId toIgnore) throws SQLException {
    Preconditions.checkArgument(toIgnore != null);

    Connection connection = null;
    PreparedStatement ps = null;/*  www  .j a v a 2  s  . c o  m*/
    ResultSet rs = null;

    try {
        connection = obmHelper.getConnection();

        ps = connection.prepareStatement("SELECT userobm_email as mail FROM UserObm "
                + "INNER JOIN Domain ON Domain.domain_id = userobm_domain_id " + "WHERE domain_id = ? "
                + "AND userobm_ext_id != ? " + "UNION " + "SELECT mailshare_email as mail FROM MailShare "
                + "INNER JOIN Domain ON Domain.domain_id = mailshare_domain_id " + "WHERE domain_id = ? "
                + "UNION " + "SELECT group_email as mail FROM UGroup "
                + "INNER JOIN Domain ON Domain.domain_id = group_domain_id " + "WHERE domain_id = ?");

        ps.setInt(1, domain.getId());
        ps.setString(2, toIgnore.getExtId());
        ps.setInt(3, domain.getId());
        ps.setInt(4, domain.getId());

        rs = ps.executeQuery();
        ImmutableSet.Builder<String> builder = ImmutableSet.builder();

        while (rs.next()) {
            builder.addAll(deserializeEmails(rs.getString("mail")));
        }

        return builder.build();
    } finally {
        JDBCUtils.cleanup(connection, ps, rs);
    }
}

From source file:org.fcrepo.kernel.services.LowLevelStorageService.java

/**
 * Transform low-level cache entries from a particular CompositeBinaryStore
 *
 * @param key a Modeshape BinaryValue's key.
 * @return a set of transformed objects//  w  w w.  ja  va  2 s .c o m
 */
protected <T> Set<T> transformLowLevelCacheEntries(final CompositeBinaryStore compositeStore,
        final BinaryKey key, final Function<LowLevelCacheEntry, T> transform) {

    final ImmutableSet.Builder<T> results = builder();

    final Iterator<Map.Entry<String, BinaryStore>> it = compositeStore.getNamedStoreIterator();

    while (it.hasNext()) {
        final Map.Entry<String, BinaryStore> entry = it.next();
        final BinaryStore bs = entry.getValue();
        if (bs.hasBinary(key)) {
            final Function<LowLevelCacheEntry, T> decorator = new ExternalIdDecorator<>(entry.getKey(),
                    transform);
            final Set<T> transformeds = transformLowLevelCacheEntries(bs, key, decorator);
            results.addAll(transformeds);
        }
    }

    return results.build();
}

From source file:co.cask.cdap.internal.app.runtime.flow.FlowletProgramRunner.java

private SchemaCache createSchemaCache(Program program) throws Exception {
    ImmutableSet.Builder<Schema> schemas = ImmutableSet.builder();

    for (FlowSpecification flowSpec : program.getApplicationSpecification().getFlows().values()) {
        for (FlowletDefinition flowletDef : flowSpec.getFlowlets().values()) {
            schemas.addAll(Iterables.concat(flowletDef.getInputs().values()));
            schemas.addAll(Iterables.concat(flowletDef.getOutputs().values()));
        }//  ww  w.ja v  a 2 s .  c o m
    }

    // Temp fix for ENG-3949. Always add old stream event schema.
    // TODO: Remove it later. The right thing to do is to have schemas history being stored to support schema
    // evolution. By design, as long as the schema cache is populated with old schema, the type projection logic
    // in the decoder would handle it correctly.
    schemas.add(schemaGenerator.generate(StreamEventData.class));

    return new SchemaCache(schemas.build(), program.getClassLoader());
}