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:org.sonar.php.tree.symbols.SymbolVisitor.java

@Override
public void visitMemberAccess(MemberAccessTree tree) {
    tree.object().accept(this);

    final ImmutableSet<String> selfObjects = ImmutableSet.of("$this", "self", "static");
    String strObject = SourceBuilder.build(tree.object()).trim();

    classMemberUsageState = new ClassMemberUsageState();
    classMemberUsageState.isStatic = tree.isStatic();
    classMemberUsageState.isSelfMember = selfObjects.contains(strObject.toLowerCase(Locale.ENGLISH));
    classMemberUsageState.isField = insideCallee.isEmpty();
    classMemberUsageState.isConst = classMemberUsageState.isField && tree.isStatic();

    tree.member().accept(this);
}

From source file:com.facebook.buck.features.project.intellij.BaseIjModuleRule.java

private void addDepsAndFolder(IJFolderFactory folderFactory, DependencyType dependencyType,
        TargetNode<T> targetNode, boolean wantsPackagePrefix, ModuleBuildContext context,
        ImmutableSet<Path> resourcePaths) {
    ImmutableMultimap<Path, Path> foldersToInputsIndex = getSourceFoldersToInputsIndex(targetNode.getInputs()
            .stream().map(path -> projectFilesystem.relativize(targetNode.getFilesystem().resolve(path)))
            .collect(ImmutableList.toImmutableList()));

    if (!resourcePaths.isEmpty()) {
        foldersToInputsIndex = foldersToInputsIndex.entries().stream()
                .filter(entry -> !resourcePaths.contains(entry.getValue()))
                .collect(ImmutableListMultimap.toImmutableListMultimap(Map.Entry::getKey, Map.Entry::getValue));
    }/*from  ww w. java 2  s  .  com*/

    addSourceFolders(folderFactory, foldersToInputsIndex, wantsPackagePrefix, context);
    addDeps(foldersToInputsIndex, targetNode, dependencyType, context);

    addGeneratedOutputIfNeeded(folderFactory, targetNode, context);

    if (targetNode.getConstructorArg() instanceof JvmLibraryArg) {
        addAnnotationOutputIfNeeded(folderFactory, targetNode, context);
    }
}

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

@Override
public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
    return cxxPlatforms.containsAnyOf(flavors) || flavors.contains(CxxCompilationDatabase.COMPILATION_DATABASE)
            || flavors.contains(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)
            || flavors.contains(CxxInferEnhancer.InferFlavors.INFER.get())
            || flavors.contains(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get())
            || flavors.contains(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.get())
            || LinkerMapMode.FLAVOR_DOMAIN.containsAnyOf(flavors);

}

From source file:com.arpnetworking.metrics.mad.Bucket.java

private void computeStatistics(final ConcurrentMap<String, Collection<Calculator<?>>> calculatorsByMetric,
        final ImmutableSet<Statistic> specifiedStatistics,
        final ImmutableMultimap.Builder<String, AggregatedData> data) {
    computeStatistics(calculatorsByMetric, (metric, statistic) -> specifiedStatistics.contains(statistic),
            data);//  www .  ja  v  a  2s . c  om
}

From source file:com.github.hilcode.versionator.Model.java

public Model apply(final ImmutableCollection<Gav> gavs) {
    Preconditions.checkNotNull(gavs, "Missing 'gavs'.");
    if (gavs.isEmpty()) {
        return this;
    }// w  w  w . j a v  a  2s.  c  om
    final ImmutableCollection<Gav> gavs_ = createClosure(gavs);
    Model result = this;
    for (final Gav gav : gavs_) {
        boolean pomChange = false;
        final ImmutableList.Builder<Pom> newPomsBuilder = ImmutableList.builder();
        for (final Pom pom : result.poms) {
            final Pom newPom = pom.apply(gav);
            pomChange = pomChange || newPom != pom;
            newPomsBuilder.add(newPom);
        }
        result = pomChange ? BUILDER.build(newPomsBuilder.build()) : this;
    }
    final ImmutableSet.Builder<GroupArtifact> groupArtifactsBuilder = ImmutableSet.builder();
    for (final Gav gav : gavs_) {
        groupArtifactsBuilder.add(gav.groupArtifact);
    }
    final ImmutableSet<GroupArtifact> groupArtifacts = groupArtifactsBuilder.build();
    while (true) {
        final ImmutableSet.Builder<Gav> collateralGavs = ImmutableSet.builder();
        for (final Tuple._2<Pom, Pom> tuple : Zipper.BUILDER.zip(this.poms, result.poms)) {
            final Pom originalPom = tuple._1;
            final Pom resultPom = tuple._2;
            if (originalPom != resultPom) {
                if (originalPom.gav != resultPom.gav
                        && !groupArtifacts.contains(originalPom.gav.groupArtifact)) {
                    collateralGavs.add(resultPom.gav);
                } else if (originalPom.gav.version.isRelease()) {
                    final Pom pom = originalPom.findRoot();
                    final Gav gav = Gav.BUILDER.build(pom.gav.groupArtifact,
                            pom.gav.version.next().toSnapshot());
                    if (!groupArtifacts.contains(gav.groupArtifact)) {
                        collateralGavs.add(gav);
                    }
                }
            }
        }
        final Model result_ = result.apply(collateralGavs.build());
        if (result_ == result) {
            break;
        }
        result = result_;
    }
    return result;
}

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

public Optional<ProvisioningProfileMetadata> getBestProvisioningProfile(String bundleID,
        Optional<ImmutableMap<String, NSObject>> entitlements,
        Optional<? extends Iterable<CodeSignIdentity>> identities) {
    final Optional<String> prefix;
    if (entitlements.isPresent()) {
        prefix = ProvisioningProfileMetadata.prefixFromEntitlements(entitlements.get());
    } else {/*from  w  w w  .j  av a2  s .c  om*/
        prefix = Optional.empty();
    }

    int bestMatchLength = -1;
    Optional<ProvisioningProfileMetadata> bestMatch = Optional.empty();

    for (ProvisioningProfileMetadata profile : getProvisioningProfiles()) {
        if (profile.getExpirationDate().after(new Date())) {
            Pair<String, String> appID = profile.getAppID();

            LOG.debug("Looking at provisioning profile " + profile.getUUID() + "," + appID.toString());

            if (!prefix.isPresent() || prefix.get().equals(appID.getFirst())) {
                String profileBundleID = appID.getSecond();
                boolean match;
                if (profileBundleID.endsWith("*")) {
                    // Chop the ending * if wildcard.
                    profileBundleID = profileBundleID.substring(0, profileBundleID.length() - 1);
                    match = bundleID.startsWith(profileBundleID);
                } else {
                    match = (bundleID.equals(profileBundleID));
                }

                if (!match) {
                    LOG.debug("Ignoring non-matching ID for profile " + profile.getUUID());
                }

                // Match against other keys of the entitlements.  Otherwise, we could potentially select
                // a profile that doesn't have all the needed entitlements, causing a error when
                // installing to device.
                //
                // For example: get-task-allow, aps-environment, etc.
                if (match && entitlements.isPresent()) {
                    ImmutableMap<String, NSObject> entitlementsDict = entitlements.get();
                    ImmutableMap<String, NSObject> profileEntitlements = profile.getEntitlements();
                    for (Entry<String, NSObject> entry : entitlementsDict.entrySet()) {
                        if (!(entry.getKey().equals("keychain-access-groups")
                                || entry.getKey().equals("application-identifier")
                                || entry.getKey().equals("com.apple.developer.associated-domains")
                                || matchesOrArrayIsSubsetOf(entry.getValue(),
                                        profileEntitlements.get(entry.getKey())))) {
                            match = false;
                            LOG.debug("Ignoring profile " + profile.getUUID() + " with mismatched entitlement "
                                    + entry.getKey() + "; value is " + profileEntitlements.get(entry.getKey())
                                    + " but expected " + entry.getValue());
                            break;
                        }
                    }
                }

                // Reject any certificate which we know we can't sign with the supplied identities.
                ImmutableSet<HashCode> validFingerprints = profile.getDeveloperCertificateFingerprints();
                if (match && identities.isPresent() && !validFingerprints.isEmpty()) {
                    match = false;
                    for (CodeSignIdentity identity : identities.get()) {
                        Optional<HashCode> fingerprint = identity.getFingerprint();
                        if (fingerprint.isPresent() && validFingerprints.contains(fingerprint.get())) {
                            match = true;
                            break;
                        }
                    }

                    if (!match) {
                        LOG.debug("Ignoring profile " + profile.getUUID()
                                + " because it can't be signed with any valid identity in the current keychain.");
                    }
                }

                if (match && profileBundleID.length() > bestMatchLength) {
                    bestMatchLength = profileBundleID.length();
                    bestMatch = Optional.of(profile);
                }
            }
        } else {
            LOG.debug("Ignoring expired profile " + profile.getUUID());
        }
    }

    LOG.debug("Found provisioning profile " + bestMatch.toString());
    return bestMatch;
}

From source file:google.registry.flows.host.HostUpdateFlow.java

private void verifyUpdateAllowed(Update command, HostResource existingResource,
        DomainResource superordinateDomain) throws EppException {
    if (!isSuperuser) {
        verifyResourceOwnership(clientId, existingResource);
        ImmutableSet<StatusValue> statusesToAdd = command.getInnerAdd().getStatusValues();
        ImmutableSet<StatusValue> statusesToRemove = command.getInnerRemove().getStatusValues();
        // If the resource is marked with clientUpdateProhibited, and this update does not clear that
        // status, then the update must be disallowed (unless a superuser is requesting the change).
        if (!isSuperuser && existingResource.getStatusValues().contains(StatusValue.CLIENT_UPDATE_PROHIBITED)
                && !statusesToRemove.contains(StatusValue.CLIENT_UPDATE_PROHIBITED)) {
            throw new ResourceHasClientUpdateProhibitedException();
        }/* w ww. j a va 2 s  .c  o  m*/
        verifyAllStatusesAreClientSettable(union(statusesToAdd, statusesToRemove));
    }
    verifyDomainIsSameRegistrar(superordinateDomain, clientId);
    verifyNoDisallowedStatuses(existingResource, DISALLOWED_STATUSES);
}

From source file:com.facebook.buck.features.halide.HalideLibraryDescription.java

@Override
public BuildRule createBuildRule(BuildRuleCreationContextWithTargetGraph context, BuildTarget buildTarget,
        BuildRuleParams params, HalideLibraryDescriptionArg args) {
    CxxPlatformsProvider cxxPlatformsProvider = getCxxPlatformsProvider();
    FlavorDomain<UnresolvedCxxPlatform> cxxPlatforms = cxxPlatformsProvider.getUnresolvedCxxPlatforms();

    ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
    ImmutableSet<Flavor> flavors = ImmutableSet.copyOf(buildTarget.getFlavors());
    // TODO(cjhopman): This description doesn't handle parse time deps correctly.
    CxxPlatform cxxPlatform = cxxPlatforms.getValue(flavors)
            .orElse(cxxPlatformsProvider.getDefaultUnresolvedCxxPlatform()).resolve(graphBuilder);
    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();

    if (flavors.contains(CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR)) {
        ImmutableMap.Builder<Path, SourcePath> headersBuilder = ImmutableMap.builder();
        BuildTarget compileTarget = graphBuilder
                .requireRule(buildTarget.withFlavors(HALIDE_COMPILE_FLAVOR, cxxPlatform.getFlavor()))
                .getBuildTarget();//from w w  w .  j  ava  2 s .  c  o m
        Path outputPath = HalideCompile.headerOutputPath(compileTarget, projectFilesystem,
                args.getFunctionName());
        headersBuilder.put(outputPath.getFileName(),
                ExplicitBuildTargetSourcePath.of(compileTarget, outputPath));
        return CxxDescriptionEnhancer.createHeaderSymlinkTree(buildTarget, projectFilesystem, ruleFinder,
                graphBuilder, cxxPlatform, headersBuilder.build(), HeaderVisibility.PUBLIC, true);
    } else if (flavors.contains(HALIDE_COMPILER_FLAVOR)) {
        // We always want to build the halide "compiler" for the host platform, so
        // we use the host flavor here, regardless of the flavors on the build
        // target.
        CxxPlatform hostCxxPlatform = cxxPlatforms.getValue(CxxPlatforms.getHostFlavor()).resolve(graphBuilder);
        ImmutableSortedSet<BuildTarget> compilerDeps = args.getCompilerDeps();
        return createHalideCompiler(buildTarget, projectFilesystem,
                params.withDeclaredDeps(graphBuilder.getAllRules(compilerDeps)).withoutExtraDeps(),
                graphBuilder, pathResolver, ruleFinder, context.getCellPathResolver(), cxxPlatformsProvider,
                hostCxxPlatform, args.getSrcs(), args.getCompilerFlags(), args.getPlatformCompilerFlags(),
                args.getLangCompilerFlags(), args.getLinkerFlags(), args.getPlatformLinkerFlags(),
                args.getRawHeaders());
    } else if (flavors.contains(CxxDescriptionEnhancer.STATIC_FLAVOR)
            || flavors.contains(CxxDescriptionEnhancer.STATIC_PIC_FLAVOR)) {
        // Halide always output PIC, so it's output can be used for both cases.
        // See: https://github.com/halide/Halide/blob/e3c301f3/src/LLVM_Output.cpp#L152
        return createHalideStaticLibrary(buildTarget, projectFilesystem, params, graphBuilder, ruleFinder,
                cxxPlatform, args);
    } else if (flavors.contains(CxxDescriptionEnhancer.SHARED_FLAVOR)) {
        throw new HumanReadableException("halide_library '%s' does not support shared libraries as output",
                buildTarget);
    } else if (flavors.contains(HALIDE_COMPILE_FLAVOR)) {
        return createHalideCompile(buildTarget, projectFilesystem,
                params.withoutDeclaredDeps().withoutExtraDeps(), graphBuilder, cxxPlatform,
                Optional.of(args.getCompilerInvocationFlags()), args.getFunctionName());
    }

    return new HalideLibrary(buildTarget, projectFilesystem, params, graphBuilder,
            args.getSupportedPlatformsRegex());
}

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

@Override
int runCommandWithOptionsInternal(AuditCommandOptions options) throws IOException {
    // Create a PartialGraph that is composed of the transitive closure of all of the dependent
    // BuildRules for the specified BuildTargets.
    final ImmutableSet<String> fullyQualifiedBuildTargets = ImmutableSet
            .copyOf(options.getArgumentsFormattedAsBuildTargets());

    if (fullyQualifiedBuildTargets.isEmpty()) {
        console.printBuildFailure("Please specify at least one build target.");
        return 1;
    }/*w  w  w  .  j ava2  s. c  om*/

    RawRulePredicate predicate = new RawRulePredicate() {
        @Override
        public boolean isMatch(Map<String, Object> rawParseData, BuildRuleType buildRuleType,
                BuildTarget buildTarget) {
            return fullyQualifiedBuildTargets.contains(buildTarget.getFullyQualifiedName());
        }
    };
    PartialGraph partialGraph;
    try {
        partialGraph = PartialGraph.createPartialGraph(predicate, getProjectFilesystem(),
                options.getDefaultIncludes(), getParser(), getBuckEventBus());
    } catch (BuildTargetException | BuildFileParseException e) {
        console.printBuildFailureWithoutStacktrace(e);
        return 1;
    }

    if (options.shouldGenerateDotOutput()) {
        return printDotOutput(partialGraph.getDependencyGraph());
    } else if (options.shouldGenerateJsonOutput()) {
        return printJsonClasspath(partialGraph);
    } else {
        return printClasspath(partialGraph);
    }
}

From source file:com.facebook.buck.apple.toolchain.AbstractProvisioningProfileStore.java

public Optional<ProvisioningProfileMetadata> getBestProvisioningProfile(String bundleID, ApplePlatform platform,
        Optional<ImmutableMap<String, NSObject>> entitlements,
        Optional<? extends Iterable<CodeSignIdentity>> identities, StringBuffer diagnosticsBuffer) {
    Optional<String> prefix;
    ImmutableList.Builder<String> lines = ImmutableList.builder();
    if (entitlements.isPresent()) {
        prefix = ProvisioningProfileMetadata.prefixFromEntitlements(entitlements.get());
    } else {// ww  w . j  ava2  s .c o m
        prefix = Optional.empty();
    }

    int bestMatchLength = -1;
    Optional<ProvisioningProfileMetadata> bestMatch = Optional.empty();

    lines.add(String.format("Looking for a provisioning profile for bundle ID %s", bundleID));

    boolean atLeastOneMatch = false;
    for (ProvisioningProfileMetadata profile : getProvisioningProfiles()) {
        Pair<String, String> appID = profile.getAppID();

        LOG.debug("Looking at provisioning profile " + profile.getUUID() + "," + appID);

        if (!prefix.isPresent() || prefix.get().equals(appID.getFirst())) {
            String profileBundleID = appID.getSecond();
            boolean match;
            if (profileBundleID.endsWith("*")) {
                // Chop the ending * if wildcard.
                profileBundleID = profileBundleID.substring(0, profileBundleID.length() - 1);
                match = bundleID.startsWith(profileBundleID);
            } else {
                match = (bundleID.equals(profileBundleID));
            }

            if (!match) {
                LOG.debug("Ignoring non-matching ID for profile " + profile.getUUID() + ".  Expected: "
                        + profileBundleID + ", actual: " + bundleID);
                continue;
            }

            atLeastOneMatch = true;
            if (!profile.getExpirationDate().after(new Date())) {
                String message = "Ignoring expired profile " + profile.getUUID() + ": "
                        + profile.getExpirationDate();
                LOG.debug(message);
                lines.add(message);
                continue;
            }

            Optional<String> platformName = platform.getProvisioningProfileName();
            if (platformName.isPresent() && !profile.getPlatforms().contains(platformName.get())) {
                String message = "Ignoring incompatible platform " + platformName.get() + " for profile "
                        + profile.getUUID();
                LOG.debug(message);
                lines.add(message);
                continue;
            }

            // Match against other keys of the entitlements.  Otherwise, we could potentially select
            // a profile that doesn't have all the needed entitlements, causing a error when
            // installing to device.
            //
            // For example: get-task-allow, aps-environment, etc.
            if (entitlements.isPresent()) {
                ImmutableMap<String, NSObject> entitlementsDict = entitlements.get();
                ImmutableMap<String, NSObject> profileEntitlements = profile.getEntitlements();
                for (Entry<String, NSObject> entry : entitlementsDict.entrySet()) {
                    NSObject profileEntitlement = profileEntitlements.get(entry.getKey());
                    if (!(FORCE_INCLUDE_ENTITLEMENTS.contains(entry.getKey())
                            || matchesOrArrayIsSubsetOf(entry.getValue(), profileEntitlement))) {
                        match = false;
                        String profileEntitlementString = getStringFromNSObject(profileEntitlement);
                        String entryValueString = getStringFromNSObject(entry.getValue());
                        String message = "Profile " + profile.getProfilePath().getFileName() + " ("
                                + profile.getUUID() + ") with bundleID " + profile.getAppID().getSecond()
                                + " correctly matches. However there is a mismatched entitlement "
                                + entry.getKey() + ";" + System.lineSeparator() + "value is: "
                                + profileEntitlementString + "but expected: " + entryValueString;
                        LOG.debug(message);
                        lines.add(message);
                    }
                }
            }

            // Reject any certificate which we know we can't sign with the supplied identities.
            ImmutableSet<HashCode> validFingerprints = profile.getDeveloperCertificateFingerprints();
            if (match && identities.isPresent() && !validFingerprints.isEmpty()) {
                match = false;
                for (CodeSignIdentity identity : identities.get()) {
                    Optional<HashCode> fingerprint = identity.getFingerprint();
                    if (fingerprint.isPresent() && validFingerprints.contains(fingerprint.get())) {
                        match = true;
                        break;
                    }
                }

                if (!match) {
                    String message = "Ignoring profile " + profile.getUUID()
                            + " because it can't be signed with any valid identity in the current keychain.";
                    LOG.debug(message);
                    lines.add(message);
                    continue;
                }
            }

            if (match && profileBundleID.length() > bestMatchLength) {
                bestMatchLength = profileBundleID.length();
                bestMatch = Optional.of(profile);
            }
        }
    }

    if (!atLeastOneMatch) {
        lines.add(String.format("No provisioning profile matching the bundle ID %s was found", bundleID));
    }

    LOG.debug("Found provisioning profile " + bestMatch);
    ImmutableList<String> diagnostics = lines.build();
    diagnosticsBuffer.append(Joiner.on("\n").join(diagnostics));
    return bestMatch;
}