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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:org.janusgraph.diskstorage.indexing.IndexFeatures.java

public IndexFeatures(boolean supportsDocumentTTL, Mapping defaultMap, ImmutableSet<Mapping> supportedMap,
        String wildcardField, ImmutableSet<Cardinality> supportedCardinaities, boolean supportsNanoseconds) {

    Preconditions.checkArgument(defaultMap != null || defaultMap != Mapping.DEFAULT);
    Preconditions.checkArgument(/*from  www. j av a  2  s. c om*/
            supportedMap != null && !supportedMap.isEmpty() && supportedMap.contains(defaultMap));
    this.supportsDocumentTTL = supportsDocumentTTL;
    this.defaultStringMapping = defaultMap;
    this.supportedStringMappings = supportedMap;
    this.wildcardField = wildcardField;
    this.supportedCardinaities = supportedCardinaities;
    this.supportsNanoseconds = supportsNanoseconds;
}

From source file:com.facebook.buck.swift.SwiftLibraryDescription.java

@Override
public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
    ImmutableSet<Flavor> currentUnsupportedFlavors = ImmutableSet
            .copyOf(Sets.filter(flavors, Predicates.not(SUPPORTED_FLAVORS::contains)));
    if (currentUnsupportedFlavors.isEmpty()) {
        return true;
    }/*w  w w .ja va  2  s  .  c  o m*/
    return cxxPlatformFlavorDomain.containsAnyOf(flavors);
}

From source file:be.fror.password.rule.Ruler.java

private Generator createGenerator() {
    final ImmutableSet<CharacterRule> charRules = rules.stream().filter(e -> e instanceof CharacterRule)
            .map(e -> (CharacterRule) e).collect(MoreCollectors.toImmutableSet());
    checkState(!charRules.isEmpty(), "No CharacterRule were added to this Ruler");
    Set<Character> uniqueChars = new TreeSet<>();
    int minLen = 0;
    for (CharacterRule rule : charRules) {
        for (char c : rule.getValidCharacters().toCharArray()) {
            uniqueChars.add(c);//from   www  .j  a  va 2  s . c o m
        }
        minLen += rule.getNumberOfCharacters();
    }
    return new Generator(charRules, Chars.toArray(uniqueChars), minLen);
}

From source file:google.registry.export.CheckSnapshotServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    String snapshotName;/*from w  ww.j a  v a  2 s  . co m*/
    String kindsToLoadParam;
    // TODO(b/28266757): Remove this try/catch/rethrow block once this servlet is Daggerized.
    try {
        snapshotName = extractRequiredParameter(req, SNAPSHOT_NAME_PARAM);
        kindsToLoadParam = extractRequiredParameter(req, SNAPSHOT_KINDS_TO_LOAD_PARAM);
    } catch (BadRequestException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    Set<String> kindsToLoad = ImmutableSet.copyOf(Splitter.on(',').split(kindsToLoadParam));

    // Look up the backup by the provided name, stopping if we can't find it.
    DatastoreBackupInfo backup;
    try {
        backup = backupService.findByName(snapshotName);
    } catch (IllegalArgumentException e) {
        String message = String.format("Bad backup name %s: %s", snapshotName, e.getMessage());
        logger.severe(e, message);
        // TODO(b/19081569): Ideally this would return a 2XX error so the task would not be retried,
        //   but we might abandon backups that start late and haven't yet written to datastore.
        //   We could fix that by replacing this with a two-phase polling strategy.
        rsp.sendError(SC_BAD_REQUEST, htmlEscaper().escape(message));
        return;
    }
    // Stop now if the backup is not complete.
    if (!backup.getStatus().equals(BackupStatus.COMPLETE)) {
        Duration runningTime = backup.getRunningTime();
        if (runningTime.isShorterThan(MAXIMUM_BACKUP_RUNNING_TIME)) {
            // Backup might still be running, so send a 304 to have the task retry.
            rsp.sendError(SC_NOT_MODIFIED,
                    htmlEscaper().escape(String.format("Datastore backup %s still pending", snapshotName)));
        } else {
            // Declare the backup a lost cause, and send 202 Accepted so the task will not be retried.
            String message = String.format("Datastore backup %s abandoned - not complete after %s",
                    snapshotName, PeriodFormat.getDefault().print(runningTime.toPeriod()
                            .normalizedStandard(PeriodType.dayTime().withMillisRemoved())));
            logger.severe(message);
            rsp.sendError(SC_ACCEPTED, htmlEscaper().escape(message));
        }
        return;
    }
    // Get a compact string to identify this snapshot in BigQuery by trying to parse the unique
    // suffix out of the snapshot name and falling back to the start time as a string.
    String snapshotId = snapshotName.startsWith(ExportSnapshotServlet.SNAPSHOT_PREFIX)
            ? snapshotName.substring(ExportSnapshotServlet.SNAPSHOT_PREFIX.length())
            : backup.getStartTime().toString("YYYYMMdd_HHmmss");
    // Log a warning if kindsToLoad is not a subset of the exported snapshot kinds.
    if (!backup.getKinds().containsAll(kindsToLoad)) {
        logger.warningfmt("Kinds to load included non-exported kinds: %s",
                Sets.difference(kindsToLoad, backup.getKinds()));
    }
    // Load kinds from the snapshot, limited to those also in kindsToLoad (if it's present).
    ImmutableSet<String> exportedKindsToLoad = ImmutableSet
            .copyOf(intersection(backup.getKinds(), kindsToLoad));
    String message = String.format("Datastore backup %s complete - ", snapshotName);
    if (exportedKindsToLoad.isEmpty()) {
        message += "no kinds to load into BigQuery";
    } else {
        enqueueLoadSnapshotTask(snapshotId, backup.getGcsFilename().get(), exportedKindsToLoad);
        message += "BigQuery load task enqueued";
    }
    logger.info(message);
    rsp.getWriter().write(message);
}

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

@Override
public ExitCode runWithoutHelp(CommandRunnerParams params) {
    try {// w ww  .j  av a2 s  .c o  m
        // Create a TargetGraph that is composed of the transitive closure of all of the dependent
        // BuildRules for the specified BuildTargetPaths.
        ImmutableSet<BuildTarget> targets = convertArgumentsToBuildTargets(params, getArguments());

        if (targets.isEmpty()) {
            throw new CommandLineException("must specify at least one build target");
        }

        TargetGraph targetGraph;
        try (CommandThreadManager pool = new CommandThreadManager("Audit",
                getConcurrencyLimit(params.getBuckConfig()))) {
            targetGraph = params.getParser()
                    .buildTargetGraph(createParsingContext(params.getCell(), pool.getListeningExecutorService())
                            .withSpeculativeParsing(SpeculativeParsing.ENABLED)
                            .withExcludeUnsupportedTargets(false), targets);
        } catch (BuildFileParseException e) {
            params.getBuckEventBus()
                    .post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
            return ExitCode.PARSE_ERROR;
        }
        if (params.getBuckConfig().getView(BuildBuckConfig.class).getBuildVersions()) {
            targetGraph = toVersionedTargetGraph(params, TargetGraphAndBuildTargets.of(targetGraph, targets))
                    .getTargetGraph();
        }

        ActionGraphBuilder graphBuilder = Objects.requireNonNull(new ActionGraphProvider(
                params.getBuckEventBus(),
                ActionGraphFactory.create(params.getBuckEventBus(), params.getCell().getCellProvider(),
                        params.getPoolSupplier(), params.getBuckConfig()),
                new ActionGraphCache(
                        params.getBuckConfig().getView(BuildBuckConfig.class).getMaxActionGraphCacheEntries()),
                params.getRuleKeyConfiguration(), params.getBuckConfig()).getFreshActionGraph(targetGraph))
                .getActionGraphBuilder();
        graphBuilder.requireAllRules(targets);

        SerializationReportGenerator reportGenerator = new SerializationReportGenerator();

        SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
        IsolationChecker isolationChecker = new IsolationChecker(ruleFinder,
                params.getCell().getCellPathResolver(), reportGenerator.getFailureReporter());
        AbstractBreadthFirstTraversal.<BuildRule>traverse(
                targets.stream().map(graphBuilder::getRule).collect(Collectors.toList()), rule -> {
                    isolationChecker.check(rule);
                    ImmutableList.Builder<BuildRule> depsBuilder = ImmutableList.builder();
                    depsBuilder.addAll(rule.getBuildDeps());
                    if (rule instanceof HasRuntimeDeps) {
                        depsBuilder.addAll(graphBuilder.getAllRules(((HasRuntimeDeps) rule)
                                .getRuntimeDeps(ruleFinder).collect(Collectors.toList())));
                    }
                    return depsBuilder.build();
                });

        String report = Joiner.on("\n").join(reportGenerator.generate());
        params.getConsole().getStdOut().println(report);
    } catch (Exception e) {
        throw new BuckUncheckedExecutionException(e,
                "When inspecting serialization state of the action graph.");
    }

    return ExitCode.SUCCESS;
}

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 {//w w w .  ja  v a 2 s . c  o  m
        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:dagger.internal.codegen.DependencyRequestFormatter.java

/** Returns a representation of the dependency trace, with the entry point at the bottom. */
String format(DependencyTrace dependencyTrace) {
    AtomicReference<ImmutableSet<OptionalBindingDeclaration>> dependentOptionalBindingDeclarations = new AtomicReference<>(
            ImmutableSet.of());/*w w  w .ja  va2  s .c om*/
    return Joiner.on('\n').join(dependencyTrace.transform((dependencyRequest, resolvedBindings) -> {
        ImmutableSet<OptionalBindingDeclaration> optionalBindingDeclarations = dependentOptionalBindingDeclarations
                .getAndSet(resolvedBindings.optionalBindingDeclarations());
        return optionalBindingDeclarations.isEmpty() ? format(dependencyRequest)
                : formatSyntheticOptionalBindingDependency(optionalBindingDeclarations);
    }).filter(f -> !f.isEmpty()).collect(toImmutableList()).reverse());
}

From source file:org.elasticsearch.search.facet.terms.strings.TermsStringFacetExecutor.java

public TermsStringFacetExecutor(IndexFieldData indexFieldData, int size, int shardSize,
        TermsFacet.ComparatorType comparatorType, boolean allTerms, SearchContext context,
        ImmutableSet<BytesRef> excluded, Pattern pattern, SearchScript script) {
    this.indexFieldData = indexFieldData;
    this.size = size;
    this.shardSize = shardSize;
    this.comparatorType = comparatorType;
    this.script = script;
    this.allTerms = allTerms;

    if (excluded.isEmpty() && pattern == null && script == null) {
        aggregator = new HashedAggregator();
    } else {//  w  w w. ja  v  a2  s  .  c o  m
        aggregator = new HashedScriptAggregator(excluded, pattern, script);
    }

    if (allTerms) {
        loadAllTerms(context, indexFieldData, aggregator);
    }
}

From source file:com.facebook.buck.artifact_cache.ArtifactCacheBuckConfig.java

public ImmutableSet<HttpCacheEntry> getHttpCaches() {
    ImmutableSet.Builder<HttpCacheEntry> result = ImmutableSet.builder();

    ImmutableSet<String> httpCacheNames = getHttpCacheNames();
    boolean implicitLegacyCache = httpCacheNames.isEmpty()
            && getArtifactCacheModes().contains(ArtifactCacheMode.http);
    if (implicitLegacyCache || legacyCacheConfigurationFieldsPresent()) {
        result.add(obtainEntryForName(Optional.empty()));
    }/*from   w w w.j  a  v  a  2  s  .  co  m*/

    for (String cacheName : httpCacheNames) {
        result.add(obtainEntryForName(Optional.of(cacheName)));
    }
    return result.build();
}

From source file:com.facebook.buck.ide.intellij.aggregation.AggregationTree.java

private void aggregateModules(AggregationTreeNode parentNode) {
    if (parentNode.getChildren().isEmpty()) {
        return;/*from  w w w. j a  va  2 s  .c om*/
    }

    AggregationModule nodeModule = parentNode.getModule();

    if (nodeModule != null && !nodeModule.getModuleType().canBeAggregated()) {
        return;
    }

    Path moduleBasePath = parentNode.getModuleBasePath();

    LOG.info("Aggregating module at %s: %s", moduleBasePath, nodeModule);

    String aggregationTag;
    IjModuleType rootModuleType;
    if (nodeModule == null) {
        aggregationTag = findBestAggregationTag(parentNode);
        rootModuleType = null;
    } else {
        aggregationTag = nodeModule.getAggregationTag();
        rootModuleType = nodeModule.getModuleType();
    }

    ImmutableSet<Path> modulePathsToAggregate;
    if (aggregationTag == null) {
        modulePathsToAggregate = parentNode.getChildrenPathsByModuleType(IjModuleType.UNKNOWN_MODULE);
        if (modulePathsToAggregate.isEmpty()) {
            return;
        }
        rootModuleType = IjModuleType.UNKNOWN_MODULE;
    } else {
        modulePathsToAggregate = parentNode.getChildrenPathsByModuleTypeOrTag(IjModuleType.UNKNOWN_MODULE,
                aggregationTag);

        if (rootModuleType == null) {
            rootModuleType = parentNode.getChild(modulePathsToAggregate.iterator().next()).getModule()
                    .getModuleType();
        }
    }

    ImmutableSet<Path> excludes = findExcludes(parentNode, modulePathsToAggregate);

    List<AggregationModule> modulesToAggregate = modulePathsToAggregate.stream().map(parentNode::getChild)
            .map(AggregationTreeNode::getModule).collect(Collectors.toList());

    modulePathsToAggregate.forEach(parentNode::removeChild);

    if (nodeModule == null) {
        parentNode.setModule(ModuleAggregator.aggregate(moduleBasePath, rootModuleType,
                aggregationTag == null ? modulesToAggregate.iterator().next().getAggregationTag()
                        : aggregationTag,
                modulesToAggregate, excludes));
    } else {
        parentNode.setModule(ModuleAggregator.aggregate(nodeModule, modulesToAggregate, excludes));
    }
    LOG.info("Module after aggregation: %s", parentNode.getModule());
}