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

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

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:com.facebook.buck.apple.AbstractProvisioningProfileMetadata.java

public static ProvisioningProfileMetadata fromProvisioningProfilePath(ProcessExecutor executor,
        ImmutableList<String> readCommand, Path profilePath) throws IOException, InterruptedException {
    Set<ProcessExecutor.Option> options = EnumSet.of(ProcessExecutor.Option.EXPECTING_STD_OUT);

    // Extract the XML from its signed message wrapper.
    ProcessExecutorParams processExecutorParams = ProcessExecutorParams.builder().addAllCommand(readCommand)
            .addCommand(profilePath.toString()).build();
    ProcessExecutor.Result result;
    result = executor.launchAndExecute(processExecutorParams, options, /* stdin */ Optional.empty(),
            /* timeOutMs */ Optional.empty(), /* timeOutHandler */ Optional.empty());
    if (result.getExitCode() != 0) {
        throw new IOException(result.getMessageForResult("Invalid provisioning profile: " + profilePath));
    }/*from ww w.  j  a v a2  s .c o m*/

    try {
        NSDictionary plist = (NSDictionary) PropertyListParser.parse(result.getStdout().get().getBytes());
        Date expirationDate = ((NSDate) plist.get("ExpirationDate")).getDate();
        String uuid = ((NSString) plist.get("UUID")).getContent();

        ImmutableSet.Builder<HashCode> certificateFingerprints = ImmutableSet.builder();
        NSArray certificates = (NSArray) plist.get("DeveloperCertificates");
        HashFunction hasher = Hashing.sha1();
        if (certificates != null) {
            for (NSObject item : certificates.getArray()) {
                certificateFingerprints.add(hasher.hashBytes(((NSData) item).bytes()));
            }
        }

        ImmutableMap.Builder<String, NSObject> builder = ImmutableMap.builder();
        NSDictionary entitlements = ((NSDictionary) plist.get("Entitlements"));
        for (String key : entitlements.keySet()) {
            builder = builder.put(key, entitlements.objectForKey(key));
        }
        String appID = entitlements.get("application-identifier").toString();

        return ProvisioningProfileMetadata.builder().setAppID(ProvisioningProfileMetadata.splitAppID(appID))
                .setExpirationDate(expirationDate).setUUID(uuid).setProfilePath(profilePath)
                .setEntitlements(builder.build())
                .setDeveloperCertificateFingerprints(certificateFingerprints.build()).build();
    } catch (Exception e) {
        throw new IllegalArgumentException("Malformed embedded plist: " + e);
    }
}

From source file:google.registry.ui.server.registrar.RegistrarSettingsAction.java

/**
 * Updates a registrar builder with the supplied args from the http request, and returns a list of
 * the new registrar contacts.//ww w  . j a  va 2 s. c  om
 */
public static ImmutableSet<RegistrarContact> changeRegistrarFields(Registrar existingRegistrarObj,
        Registrar.Builder builder, Map<String, ?> args) {

    // WHOIS
    builder.setWhoisServer(RegistrarFormFields.WHOIS_SERVER_FIELD.extractUntyped(args).orNull());
    builder.setReferralUrl(RegistrarFormFields.REFERRAL_URL_FIELD.extractUntyped(args).orNull());
    for (String email : RegistrarFormFields.EMAIL_ADDRESS_FIELD.extractUntyped(args).asSet()) {
        builder.setEmailAddress(email);
    }
    builder.setPhoneNumber(RegistrarFormFields.PHONE_NUMBER_FIELD.extractUntyped(args).orNull());
    builder.setFaxNumber(RegistrarFormFields.FAX_NUMBER_FIELD.extractUntyped(args).orNull());
    builder.setLocalizedAddress(RegistrarFormFields.L10N_ADDRESS_FIELD.extractUntyped(args).orNull());

    // Security
    builder.setIpAddressWhitelist(RegistrarFormFields.IP_ADDRESS_WHITELIST_FIELD.extractUntyped(args)
            .or(ImmutableList.<CidrAddressBlock>of()));
    for (String certificate : RegistrarFormFields.CLIENT_CERTIFICATE_FIELD.extractUntyped(args).asSet()) {
        builder.setClientCertificate(certificate, ofy().getTransactionTime());
    }
    for (String certificate : RegistrarFormFields.FAILOVER_CLIENT_CERTIFICATE_FIELD.extractUntyped(args)
            .asSet()) {
        builder.setFailoverClientCertificate(certificate, ofy().getTransactionTime());
    }

    builder.setUrl(RegistrarFormFields.URL_FIELD.extractUntyped(args).orNull());
    builder.setReferralUrl(RegistrarFormFields.REFERRAL_URL_FIELD.extractUntyped(args).orNull());

    // Contact
    ImmutableSet.Builder<RegistrarContact> contacts = new ImmutableSet.Builder<>();
    for (RegistrarContact.Builder contactBuilder : concat(
            RegistrarFormFields.CONTACTS_FIELD.extractUntyped(args).asSet())) {
        contacts.add(contactBuilder.setParent(existingRegistrarObj).build());
    }

    return contacts.build();
}

From source file:com.facebook.buck.cli.QueryTargetAccessor.java

/**
 * Filters the objects in the given attribute that satisfy the given predicate.
 *///from w  ww . jav  a  2  s  . c o  m
public static <T extends AbstractDescriptionArg> ImmutableSet<Object> filterAttributeContents(
        TargetNode<T> node, String attribute, final Predicate<Object> predicate) throws QueryException {
    try {
        final ImmutableSet.Builder<Object> builder = ImmutableSet.builder();
        Field field = node.getConstructorArg().getClass().getField(attribute);
        ParamInfo<T> info = new ParamInfo<>(typeCoercerFactory, field);
        info.traverse(new ParamInfo.Traversal() {
            @Override
            public void traverse(Object value) {
                if (predicate.apply(value)) {
                    builder.add(value);
                }
            }
        }, node.getConstructorArg());
        return builder.build();
    } catch (NoSuchFieldException e) {
        // Ignore if the field does not exist in this rule.
        return ImmutableSet.of();
    }
}

From source file:paperparcel.PaperParcelDescriptor.java

private static ImmutableSet<String> possibleGetterNames(String name) {
    ImmutableSet.Builder<String> possibleGetterNames = new ImmutableSet.Builder<>();
    possibleGetterNames.add(name);
    possibleGetterNames.add(IS_PREFIX + Strings.capitalizeAsciiOnly(name));
    possibleGetterNames.add(HAS_PREFIX + Strings.capitalizeAsciiOnly(name));
    possibleGetterNames.add(GET_PREFIX + Strings.capitalizeAsciiOnly(name));
    possibleGetterNames.add(GET_PREFIX + Strings.capitalizeFirstWordAsciiOnly(name));
    return possibleGetterNames.build();
}

From source file:org.jetbrains.jet.lang.resolve.DiagnosticsWithSuppression.java

private static void addStrings(ImmutableSet.Builder<String> builder, List<CompileTimeConstant<?>> values) {
    for (CompileTimeConstant<?> value : values) {
        if (value instanceof StringValue) {
            StringValue stringValue = (StringValue) value;
            builder.add(stringValue.getValue().toLowerCase());
        }/*from w  w w . j  a  va 2s . c  o m*/
    }
}

From source file:co.cask.cdap.app.program.ManifestFields.java

/**
 * Parses the manifest {@link #EXPORT_PACKAGE} attribute and returns a set of export packages.
 *///from  www.ja va  2s  . com
public static Set<String> getExportPackages(@Nullable Manifest manifest) {
    if (manifest == null) {
        return ImmutableSet.of();
    }

    ImmutableSet.Builder<String> result = ImmutableSet.builder();
    String exportPackages = manifest.getMainAttributes().getValue(ManifestFields.EXPORT_PACKAGE);
    if (exportPackages == null) {
        return result.build();
    }

    // The matcher matches the package name one by one.
    Matcher matcher = EXPORT_PACKAGE_PATTERN.matcher(exportPackages);
    int start = 0;
    while (matcher.find(start)) {
        result.add(matcher.group(1));
        start = matcher.end();
    }
    return result.build();
}

From source file:com.google.template.soy.types.aggregate.UnionType.java

/**
 * Create a set containing all of the types contained in the input collection.
 * If any of the members of the input collection are unions, add the
 * individual members to the result union, thus "flattening" the union.
 * @param members The input types.//  www . ja  v  a2 s  .  c o m
 * @return The set of all types in the input collection.
 */
private static ImmutableSet<SoyType> flatten(Collection<SoyType> members) {
    ImmutableSet.Builder<SoyType> builder = ImmutableSet.builder();
    for (SoyType type : members) {
        if (type.getKind() == Kind.UNKNOWN) {
            return ImmutableSet.of(type);
        }
        if (type.getKind() == Kind.UNION) {
            builder.addAll(((UnionType) type).members);
        } else {
            builder.add(type);
        }
    }
    return builder.build();
}

From source file:org.grouplens.lenskit.core.LenskitInfo.java

private static Set<String> loadRevisionSet() {
    ImmutableSet.Builder<String> revisions = ImmutableSet.builder();
    InputStream input = LenskitInfo.class.getResourceAsStream("/META-INF/lenskit/git-commits.lst");
    if (input != null) {
        try {// w  w w.j  ava  2s .c om
            Reader reader = new InputStreamReader(input);
            BufferedReader lines = new BufferedReader(reader);
            String line;
            while ((line = lines.readLine()) != null) {
                revisions.add(StringUtils.trim(line));
            }
        } catch (IOException e) {
            throw new RuntimeException("error reading revision list", e);
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                logger.error("error closing git-commit list", e);
            }
        }
    } else {
        logger.warn("cannot find LensKit revision list");
    }
    Set<String> revset = revisions.build();
    logger.debug("have {} active revisions", revset.size());
    return revset;
}

From source file:ezbake.deployer.utilities.ArtifactTypeKey.java

/**
 * Compute the permutations of artifact types. Should only be called once
 * @return the permutations//from ww w .  j  a  va2s  . c o m
 */
private static ImmutableSet<ArtifactTypeKey> computePermutations() {
    ImmutableSet.Builder<ArtifactTypeKey> permutations = ImmutableSet.builder();
    for (ArtifactType type : ArtifactType.values()) {
        for (Language language : Language.values()) {
            permutations.add(new ArtifactTypeKey(type, language));
        }
    }

    return permutations.build();
}

From source file:com.google.devtools.build.lib.analysis.AspectCollection.java

/**
 *  Creates an {@link AspectCollection} from an ordered list of aspects and
 *  a set of visible aspects.//  www . j a  v a 2 s .  c om
 *
 *  The order of aspects is reverse to the order in which they originated, with
 *  the earliest originating occurring last in the list.
 */
public static AspectCollection create(Iterable<Aspect> aspectPath, Set<AspectDescriptor> visibleAspects)
        throws AspectCycleOnPathException {
    LinkedHashMap<AspectDescriptor, Aspect> aspectMap = deduplicateAspects(aspectPath);

    LinkedHashMap<AspectDescriptor, ArrayList<AspectDescriptor>> deps = new LinkedHashMap<>();

    // Calculate all needed aspects (either visible from outside or visible to
    // other needed aspects). Already discovered needed aspects are in key set of deps.
    // 1) Start from the end of the path. The aspect only sees other aspects that are
    //    before it
    // 2) If the 'aspect' is visible from outside, it is needed.
    // 3) Otherwise, check whether 'aspect' is visible to any already needed aspects,
    //    if it is visible to a needed 'depAspect',
    //            add the 'aspect' to a list of aspects visible to 'depAspect'.
    //    if 'aspect' is needed, add it to 'deps'.
    // At the end of this algorithm, key set of 'deps' contains a subset of original
    // aspect list consisting only of needed aspects, in reverse (since we iterate
    // the original list in reverse).
    //
    // deps[aspect] contains all aspects that 'aspect' needs, in reverse order.
    for (Entry<AspectDescriptor, Aspect> aspect : ImmutableList.copyOf(aspectMap.entrySet()).reverse()) {
        boolean needed = visibleAspects.contains(aspect.getKey());
        for (AspectDescriptor depAspectDescriptor : deps.keySet()) {
            if (depAspectDescriptor.equals(aspect.getKey())) {
                continue;
            }
            Aspect depAspect = aspectMap.get(depAspectDescriptor);
            if (depAspect.getDefinition().getRequiredProvidersForAspects()
                    .isSatisfiedBy(aspect.getValue().getDefinition().getAdvertisedProviders())) {
                deps.get(depAspectDescriptor).add(aspect.getKey());
                needed = true;
            }
        }
        if (needed && !deps.containsKey(aspect.getKey())) {
            deps.put(aspect.getKey(), new ArrayList<AspectDescriptor>());
        }
    }

    // Record only the needed aspects from all aspects, in correct order.
    ImmutableList<AspectDescriptor> neededAspects = ImmutableList.copyOf(deps.keySet()).reverse();

    // Calculate visible aspect paths.
    HashMap<AspectDescriptor, AspectDeps> aspectPaths = new HashMap<>();
    ImmutableSet.Builder<AspectDeps> visibleAspectPaths = ImmutableSet.builder();
    for (AspectDescriptor visibleAspect : visibleAspects) {
        visibleAspectPaths.add(buildAspectDeps(visibleAspect, aspectPaths, deps));
    }
    return new AspectCollection(ImmutableSet.copyOf(neededAspects), visibleAspectPaths.build());
}