Example usage for com.google.common.collect ImmutableSet contains

List of usage examples for com.google.common.collect ImmutableSet contains

Introduction

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

Prototype

boolean contains(Object o);

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:com.google.devtools.build.lib.rules.proto.ProtoCommon.java

/**
 * Decides whether this proto_library should check for strict proto deps.
 *
 * <p>Takes into account command-line flags, package-level attributes and rule attributes.
 *///from w ww  .ja  v  a2  s.  c om
@VisibleForTesting
public static boolean areDepsStrict(RuleContext ruleContext) {
    BuildConfiguration.StrictDepsMode flagValue = ruleContext.getFragment(ProtoConfiguration.class)
            .strictProtoDeps();
    if (flagValue == BuildConfiguration.StrictDepsMode.OFF) {
        return false;
    }
    if (flagValue == BuildConfiguration.StrictDepsMode.ERROR
            || flagValue == BuildConfiguration.StrictDepsMode.WARN) {
        return true;
    }

    TriState attrValue = ruleContext.attributes().get("strict_proto_deps", TRISTATE);
    if (attrValue == TriState.NO) {
        return false;
    }
    if (attrValue == TriState.YES) {
        return true;
    }

    ImmutableSet<String> pkgFeatures = ruleContext.getRule().getPackage().getFeatures();
    if (pkgFeatures.contains("disable_strict_proto_deps_NO")) {
        return false;
    }
    if (pkgFeatures.contains("disable_strict_proto_deps_YES")) {
        return true;
    }

    return (flagValue == BuildConfiguration.StrictDepsMode.STRICT);
}

From source file:dk.dma.ais.packet.AisPacketSourceFilters.java

public static Predicate<AisPacketSource> filterOnSourceType(final SourceType... sourceType) {
    requireNonNull(sourceType, "sourceType is null");
    final ImmutableSet<SourceType> sourceTypes = ImmutableSet.copyOf(sourceType);
    return new Predicate<AisPacketSource>() {
        public boolean test(AisPacketSource p) {
            return sourceTypes.contains(p.getSourceType()); // sourceType == p.getSourceType();
        }/*w w  w .j av  a  2  s .  c  o m*/

        public String toString() {
            return "sourceType = " + sourceType;
        }
    };
}

From source file:com.facebook.buck.parser.RawRulePredicates.java

public static RawRulePredicate matchBuildTargets(final ImmutableSet<BuildTarget> targets) {
    return new RawRulePredicate() {
        @Override/*from   ww w  . j a  v a2  s. c  o m*/
        public boolean isMatch(Map<String, Object> rawParseData, BuildRuleType buildRuleType,
                BuildTarget buildTarget) {
            return targets.contains(buildTarget);
        }
    };
}

From source file:com.squareup.auto.value.redacted.AutoValueRedactedExtension.java

private static MethodSpec generateToString(Name superName, Map<String, ExecutableElement> properties) {
    MethodSpec.Builder builder = MethodSpec.methodBuilder("toString") //
            .addAnnotation(Override.class) //
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL) //
            .returns(String.class) //
            .addCode("return \"$L{\"\n", superName) //
            .addCode("$>$>");

    int count = 0;
    for (Map.Entry<String, ExecutableElement> entry : properties.entrySet()) {
        String propertyName = entry.getKey();
        ExecutableElement propertyElement = entry.getValue();
        TypeName propertyType = TypeName.get(entry.getValue().getReturnType());
        ImmutableSet<String> propertyAnnotations = getAnnotations(propertyElement);

        builder.addCode("+ \"$N=\" + ", propertyName);

        CodeBlock propertyToString;/*from  w  w w.  j ava 2 s .co  m*/
        if (propertyAnnotations.contains("Redacted")) {
            propertyToString = CodeBlock.builder() //
                    .add("\"\"") //
                    .build();
        } else if (propertyType instanceof ArrayTypeName) {
            propertyToString = CodeBlock.builder() //
                    .add("$T.toString($N())", Arrays.class, propertyName) //
                    .build();
        } else {
            propertyToString = CodeBlock.builder() //
                    .add("$N()", propertyName) //
                    .build();
        }

        if (propertyAnnotations.contains("Nullable")) {
            builder.addCode("($N() != null ? $L : null)", propertyName, propertyToString);
        } else {
            builder.addCode(propertyToString);
        }

        if (count++ < properties.size() - 1) {
            builder.addCode(" + \", \"");
        }

        builder.addCode("\n");
    }

    return builder //
            .addStatement("+ '}'") //
            .addCode("$<$<").build();
}

From source file:com.spectralogic.ds3autogen.c.converters.StructConverter.java

public static Struct toStruct(final Ds3Type ds3Type, final ImmutableSet<String> enumNames,
        final ImmutableSet<String> responseTypes, final ImmutableSet<String> embeddedTypes,
        final ImmutableSet<String> arrayMemberTypes, final ImmutableSet<String> paginatedTypes)
        throws ParseException {
    final String responseTypeName = StructHelper.getResponseTypeName(ds3Type.getName());
    final ImmutableList<StructMember> structMembersList = convertDs3Elements(ds3Type.getElements(), enumNames,
            paginatedTypes.contains(responseTypeName));
    return new Struct(responseTypeName, convertNameToMarshall(ds3Type), structMembersList,
            responseTypes.contains(responseTypeName), arrayMemberTypes.contains(responseTypeName),
            hasComplexArrayMembers(structMembersList), embeddedTypes.contains(responseTypeName));
}

From source file:com.outerspacecat.openid.rp.Assertion.java

/**
 * Creates a new assertion./*w ww  .  j a v  a2 s. c  om*/
 * 
 * @param association the association to use to validate the assertion. Must
 *        be non {@code null}.
 * @param fields the assertion fields. Must be non {@code null}.
 * @param receivingUrl the url that is processing this assertion. Must be non
 *        {@code null}.
 * @param nonceStore a nonce store. Must be non {@code null};
 * @return a new assertion. Never {@code null}.
 * @throws InvalidAssertionException if an assertion cannot be created
 */
public static Assertion create(final Association association, final Map<String, String> fields,
        final URI receivingUrl, final NonceStore nonceStore) throws InvalidAssertionException {
    Preconditions.checkNotNull(association, "association required");
    Preconditions.checkNotNull(fields, "fields required");
    Preconditions.checkNotNull(receivingUrl, "receivingUrl required");
    Preconditions.checkNotNull(nonceStore, "nonceStore required");

    String nsParam = fields.get("openid.ns");
    if (!"http://specs.openid.net/auth/2.0".equals(nsParam))
        throw new InvalidAssertionException("invalid ns: " + nsParam);

    String modeParam = fields.get("openid.mode");
    if (!"id_res".equals(modeParam))
        throw new InvalidAssertionException("invalid openid.mode: " + modeParam);

    String claimedIdParam = fields.get("openid.claimed_id");
    String identityParam = fields.get("openid.identity");
    if ((claimedIdParam == null) != (identityParam == null))
        throw new InvalidAssertionException(
                "invalid openid.claimed_id and openid.identity: " + claimedIdParam + ", " + identityParam);

    String returnToParam = fields.get("openid.return_to");
    if (returnToParam == null)
        throw new InvalidAssertionException("missing openid.return_to");

    try {
        URI returnToUri = new URI(returnToParam);

        if (!(receivingUrl.getScheme() + "://" + receivingUrl.getRawAuthority() + receivingUrl.getRawPath())
                .equals((returnToUri.getScheme() + "://" + returnToUri.getRawAuthority()
                        + returnToUri.getRawPath())))
            throw new InvalidAssertionException(null);

        Multimap<String, String> returnToParams = Utils.parseHttpQueryString(returnToUri.getRawQuery(),
                Charset.forName("UTF-8"));

        for (Map.Entry<String, String> e : returnToParams.entries()) {
            if (!e.getValue().equals(fields.get(e.getKey())))
                throw new InvalidAssertionException(
                        "missing return_to parameter, key=" + e.getKey() + ", return_to value=" + e.getValue()
                                + ", recievingUrl value=" + fields.get(e.getKey()));
        }
    } catch (URISyntaxException e) {
        throw new InvalidAssertionException(
                "invalid openid.return_to parameter, openid.return_to=" + returnToParam);
    }

    // openid.invalidate_handle is not checked because associations are never
    // reused

    String assocHandleParam = fields.get("openid.assoc_handle");
    if (!association.getHandle().equals(assocHandleParam))
        throw new InvalidAssertionException("invalid openid.assoc_handle, expected " + association.getHandle()
                + ", got " + assocHandleParam);

    String responseSignedParam = fields.get("openid.signed");
    if (responseSignedParam == null)
        throw new InvalidAssertionException("missing openid.signed");

    String responseSigParam = fields.get("openid.sig");
    if (responseSigParam == null)
        throw new InvalidAssertionException("missing openid.sig");

    String responseNonceParam = fields.get("openid.response_nonce");
    if (responseNonceParam == null || !NoncePattern.matcher(responseNonceParam).matches())
        throw new InvalidAssertionException("invalid openid.response_nonce: " + responseNonceParam);

    // discovery information is not verified because none is ever gathered

    nonceStore.store(association.getEndpoint().getUri(), responseNonceParam);

    ImmutableSet<String> signedFields = ImmutableSet.copyOf(responseSignedParam.split(","));

    if (!signedFields.contains("op_endpoint"))
        throw new InvalidAssertionException("openid.signed must contain \"op_endpoint\"");
    if (!signedFields.contains("return_to"))
        throw new InvalidAssertionException("openid.signed must contain \"return_to\"");
    if (!signedFields.contains("response_nonce"))
        throw new InvalidAssertionException("openid.signed must contain \"response_nonce\"");
    if (!signedFields.contains("assoc_handle"))
        throw new InvalidAssertionException("openid.signed must contain \"assoc_handle\"");
    if (claimedIdParam != null && !signedFields.contains("claimed_id"))
        throw new InvalidAssertionException(
                "openid.signed must contain \"claimed_id\" when claimed_id is in response");
    if (identityParam != null && !signedFields.contains("identity"))
        throw new InvalidAssertionException(
                "openid.signed must contain \"identity\" when identity is in response");

    StringBuilder sb = new StringBuilder();
    for (String field : signedFields) {
        if (fields.containsKey("openid." + field)) {
            sb.append(field).append(":").append(fields.get("openid." + field)).append("\n");
        }
    }

    try {
        Mac mac = Mac.getInstance(association.getAssociationType().getAlgorithm());
        mac.init(new SecretKeySpec(association.getMacKey(), association.getAssociationType().getValue()));
        mac.update(sb.toString().getBytes(Charset.forName("UTF-8")));
        String calculatedSig = new String(Base64.encode(mac.doFinal()));

        if (!Utils.constantEquals(responseSigParam, calculatedSig))
            throw new InvalidAssertionException(
                    "invalid sig, expected " + calculatedSig + ", got " + responseSigParam);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }

    return new Assertion(claimedIdParam);
}

From source file:org.ambraproject.wombat.util.HttpMessageUtil.java

/**
 * Return a list of headers from a request, using an optional whitelist
 *
 * @param request a request//from   w w  w. ja v  a2 s .  co  m
 * @return its headers
 */
public static Collection<Header> getRequestHeaders(HttpServletRequest request,
        ImmutableSet<String> headerWhitelist) {
    Enumeration headerNames = request.getHeaderNames();
    List<Header> headers = Lists.newArrayList();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        if (headerWhitelist.contains(headerName)) {
            String headerValue = request.getHeader(headerName);
            headers.add(new BasicHeader(headerName, headerValue));
        }
    }
    return headers;
}

From source file:com.datastax.driver.core.policies.HostFilterPolicy.java

private static Predicate<Host> hostDCPredicate(Iterable<String> dcs, final boolean includeNullDC) {
    final ImmutableSet<String> _dcs = ImmutableSet.copyOf(dcs);
    return new Predicate<Host>() {
        @Override/*from  ww w  .  j a  va 2 s.  c o  m*/
        public boolean apply(Host host) {
            String hdc = host.getDatacenter();
            return (hdc == null) ? includeNullDC : _dcs.contains(hdc);
        }
    };
}

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

/**
 * Create a union from a collection of types.
 *
 * @param members Member types of the union.
 * @return Union of those types. If there is exactly one distinct type in members, then this will
 *     not be a UnionType.//from w  w w  .  j  a  v a  2 s  .c o  m
 */
public static SoyType of(Collection<SoyType> members) {
    ImmutableSet<SoyType> flattenedMembers = flatten(members);
    if (flattenedMembers.size() == 1) {
        return Iterables.getOnlyElement(flattenedMembers);
    }
    // unions with the error type should just resolve to the error type to simplify analysis.
    if (flattenedMembers.contains(ErrorType.getInstance())) {
        return ErrorType.getInstance();
    }
    return new UnionType(flattenedMembers);
}

From source file:co.cask.cdap.common.utils.DirUtils.java

/**
 * Returns list of file names under the given directory that matches the give set of file name extension.
 * An empty list will be returned if the given file is not a directory.
 */// w ww  .  java  2 s .c  o m
public static List<String> list(File directory, Iterable<String> extensions) {
    final ImmutableSet<String> allowedExtensions = ImmutableSet.copyOf(extensions);

    return list(directory, new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return allowedExtensions.contains(Files.getFileExtension(name));
        }
    });
}