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:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystem.java

public static Path getCacheDir(Path root, Optional<String> value, BuckPaths buckPaths) {
    String cacheDir = value.orElse(root.resolve(buckPaths.getCacheDir()).toString());
    Path toReturn = root.getFileSystem().getPath(cacheDir);
    toReturn = MorePaths.expandHomeDir(toReturn);
    if (toReturn.isAbsolute()) {
        return toReturn;
    }/*from   w w w.  j  ava  2 s.  c  o m*/
    ImmutableSet<Path> filtered = MorePaths.filterForSubpaths(ImmutableSet.of(toReturn), root);
    if (filtered.isEmpty()) {
        // OK. For some reason the relative path managed to be out of our directory.
        return toReturn;
    }
    return Iterables.getOnlyElement(filtered);
}

From source file:org.androidtransfuse.gen.componentBuilder.InjectionNodeFactoryImpl.java

private void buildVariableBuilderMap(MethodDescriptor methodDescriptor,
        InjectionNodeBuilderRepository injectionNodeBuilders) {

    for (Map.Entry<ASTParameter, TypedExpression> parameterTypedExpressionEntry : methodDescriptor
            .getParameters().entrySet()) {
        ASTParameter parameter = parameterTypedExpressionEntry.getKey();
        ASTType parameterType = parameterTypedExpressionEntry.getKey().getASTType();
        TypedExpression expression = parameterTypedExpressionEntry.getValue();

        ImmutableSet<ASTAnnotation> qualifiers = FluentIterable.from(parameter.getAnnotations())
                .filter(qualifierPredicate).toSet();

        if (qualifiers.isEmpty()) {
            injectionNodeBuilders.putType(new InjectionSignature(parameterType), buildExpression(expression));
        } else {//from ww  w.  j  av a 2 s  .c o m
            injectionNodeBuilders.putSignatureMatcher(
                    Matchers.type(parameterType).annotated().byAnnotation(qualifiers).build(),
                    buildExpression(expression));
        }
    }
}

From source file:info.gehrels.voting.singleTransferableVote.StringBuilderBackedSTVElectionCalculationListener.java

@Override
public void electedCandidates(ImmutableSet<T> electedCandidates) {
    if (!electedCandidates.isEmpty()) {
        formatLine("======================================");
        formatLine("Gewhlt sind:");
        for (T electedCandidate : electedCandidates) {
            formatLine("\t%s", electedCandidate.name);
        }//from w  w  w  .  ja  v  a2  s .c  o m
    }
}

From source file:google.registry.flows.domain.DomainInfoFlow.java

private ImmutableList<ResponseExtension> getDomainResponseExtensions(DomainResource domain, DateTime now)
        throws EppException {
    ImmutableList.Builder<ResponseExtension> extensions = new ImmutableList.Builder<>();
    addSecDnsExtensionIfPresent(extensions, domain.getDsData());
    ImmutableSet<GracePeriodStatus> gracePeriodStatuses = domain.getGracePeriodStatuses();
    if (!gracePeriodStatuses.isEmpty()) {
        extensions.add(RgpInfoExtension.create(gracePeriodStatuses));
    }/*from  ww w.ja  v  a 2 s. c om*/
    FeeInfoCommandExtensionV06 feeInfo = eppInput.getSingleExtension(FeeInfoCommandExtensionV06.class);
    if (feeInfo != null) { // Fee check was requested.
        FeeInfoResponseExtensionV06.Builder builder = new FeeInfoResponseExtensionV06.Builder();
        handleFeeRequest(feeInfo, builder, InternetDomainName.from(targetId), null, now, pricingLogic);
        extensions.add(builder.build());
    }
    return extensions.build();
}

From source file:google.registry.flows.domain.DomainFlowUtils.java

/**
 * Adds a secDns extension to a list if the given set of dsData is non-empty.
 *
 * <p>According to RFC 5910 section 2, we should only return this if the client specified the
 * "urn:ietf:params:xml:ns:secDNS-1.1" when logging in. However, this is a "SHOULD" not a "MUST"
 * and we are going to ignore it; clients who don't care about secDNS can just ignore it.
 *//* w ww .  j  a  v  a2s  .  com*/
static void addSecDnsExtensionIfPresent(ImmutableList.Builder<ResponseExtension> extensions,
        ImmutableSet<DelegationSignerData> dsData) {
    if (!dsData.isEmpty()) {
        extensions.add(SecDnsInfoExtension.create(dsData));
    }
}

From source file:com.google.devtools.build.lib.skyframe.TraversalInfoRootPackageExtractor.java

private void collectPackagesUnder(WalkableGraph graph, ExtendedEventHandler eventHandler,
        final RepositoryName repository, Set<TraversalInfo> traversals,
        ImmutableList.Builder<PathFragment> builder) throws InterruptedException {
    Map<TraversalInfo, SkyKey> traversalToKeyMap = Maps.asMap(traversals,
            new Function<TraversalInfo, SkyKey>() {
                @Override/*from   ww  w  .j ava2s . co m*/
                public SkyKey apply(TraversalInfo traversalInfo) {
                    return CollectPackagesUnderDirectoryValue.key(repository, traversalInfo.rootedDir,
                            traversalInfo.blacklistedSubdirectories);
                }
            });
    Map<SkyKey, SkyValue> values = graph.getSuccessfulValues(traversalToKeyMap.values());

    ImmutableSet.Builder<TraversalInfo> subdirTraversalBuilder = ImmutableSet.builder();
    for (Map.Entry<TraversalInfo, SkyKey> entry : traversalToKeyMap.entrySet()) {
        TraversalInfo info = entry.getKey();
        SkyKey key = entry.getValue();
        SkyValue val = values.get(key);
        CollectPackagesUnderDirectoryValue collectPackagesValue = (CollectPackagesUnderDirectoryValue) val;
        if (collectPackagesValue != null) {
            if (collectPackagesValue.isDirectoryPackage()) {
                builder.add(info.rootedDir.getRootRelativePath());
            }

            if (collectPackagesValue.getErrorMessage() != null) {
                eventHandler.handle(Event.error(collectPackagesValue.getErrorMessage()));
            }

            ImmutableMap<RootedPath, Boolean> subdirectoryTransitivelyContainsPackages = collectPackagesValue
                    .getSubdirectoryTransitivelyContainsPackagesOrErrors();
            for (RootedPath subdirectory : subdirectoryTransitivelyContainsPackages.keySet()) {
                if (subdirectoryTransitivelyContainsPackages.get(subdirectory)) {
                    PathFragment subdirectoryRelativePath = subdirectory.getRootRelativePath();
                    ImmutableSet<PathFragment> blacklistedSubdirectoriesBeneathThisSubdirectory = info.blacklistedSubdirectories
                            .stream().filter(pathFragment -> pathFragment.startsWith(subdirectoryRelativePath))
                            .collect(toImmutableSet());
                    ImmutableSet<PathFragment> excludedSubdirectoriesBeneathThisSubdirectory = info.excludedSubdirectories
                            .stream().filter(pathFragment -> pathFragment.startsWith(subdirectoryRelativePath))
                            .collect(toImmutableSet());
                    if (!excludedSubdirectoriesBeneathThisSubdirectory.contains(subdirectoryRelativePath)) {
                        subdirTraversalBuilder.add(new TraversalInfo(subdirectory,
                                blacklistedSubdirectoriesBeneathThisSubdirectory,
                                excludedSubdirectoriesBeneathThisSubdirectory));
                    }
                }
            }
        }
    }

    ImmutableSet<TraversalInfo> subdirTraversals = subdirTraversalBuilder.build();
    if (!subdirTraversals.isEmpty()) {
        collectPackagesUnder(graph, eventHandler, repository, subdirTraversals, builder);
    }
}

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

@Override
public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {
    final ImmutableSet<String> fullyQualifiedBuildTargets = ImmutableSet
            .copyOf(getArgumentsFormattedAsBuildTargets(params.getBuckConfig()));

    if (fullyQualifiedBuildTargets.isEmpty()) {
        params.getBuckEventBus().post(ConsoleEvent.severe("Must specify at least one build target."));
        return 1;
    }/* w  w  w.  jav a2s  .  co m*/

    if (params.getConsole().getAnsi().isAnsiTerminal()) {
        params.getBuckEventBus().post(ConsoleEvent.info(
                "'buck audit tests' is deprecated. Please use 'buck query' instead. e.g.\n\t%s\n\n"
                        + "The query language is documented at https://buckbuild.com/command/query.html",
                QueryCommand.buildAuditTestsQueryExpression(getArguments(), shouldGenerateJsonOutput())));
    }

    try (CommandThreadManager pool = new CommandThreadManager("Audit",
            getConcurrencyLimit(params.getBuckConfig()));
            PerBuildState parserState = new PerBuildState(params.getParser(), params.getBuckEventBus(),
                    pool.getExecutor(), params.getCell(), getEnableParserProfiling(),
                    SpeculativeParsing.of(true), /* ignoreBuckAutodepsFiles */ false)) {
        BuckQueryEnvironment env = BuckQueryEnvironment.from(params, parserState, getEnableParserProfiling());
        return QueryCommand.runMultipleQuery(params, env, pool.getExecutor(), "testsof('%s')",
                getArgumentsFormattedAsBuildTargets(params.getBuckConfig()), shouldGenerateJsonOutput());
    } catch (Exception e) {
        if (e.getCause() instanceof InterruptedException) {
            throw (InterruptedException) e.getCause();
        }
        params.getBuckEventBus()
                .post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
        return 1;
    }
}

From source file:com.google.errorprone.bugpatterns.LoopConditionChecker.java

private Description check(ExpressionTree condition, ImmutableList<Tree> loopBodyTrees) {
    ImmutableSet<Symbol.VarSymbol> conditionVars = LoopConditionVisitor.scan(condition);
    if (conditionVars.isEmpty()) {
        return NO_MATCH;
    }//ww  w. j a va2  s.  c om
    for (Tree tree : loopBodyTrees) {
        if (UpdateScanner.scan(tree, conditionVars)) {
            return NO_MATCH;
        }
    }
    return buildDescription(condition)
            .setMessage(String.format("condition variable(s) never modified in loop body: %s",
                    Joiner.on(", ").join(conditionVars)))
            .build();
}

From source file:google.registry.model.ofy.CommitLoggedWork.java

/** Records all mutations enrolled by this transaction to a {@link CommitLogManifest} entry. */
private void saveCommitLog(TransactionInfo info) {
    ImmutableSet<Key<?>> touchedKeys = info.getTouchedKeys();
    if (touchedKeys.isEmpty()) {
        return;/*  www . ja v  a2  s . c  o m*/
    }
    CommitLogBucket bucket = loadBucket(info.bucketKey);
    // Enforce unique monotonic property on CommitLogBucket.getLastWrittenTime().
    if (isBeforeOrAt(info.transactionTime, bucket.getLastWrittenTime())) {
        throw new TimestampInversionException(info.transactionTime, bucket.getLastWrittenTime());
    }
    Map<Key<BackupGroupRoot>, BackupGroupRoot> rootsForTouchedKeys = getBackupGroupRoots(touchedKeys);
    Map<Key<BackupGroupRoot>, BackupGroupRoot> rootsForUntouchedKeys = getBackupGroupRoots(
            difference(getObjectifySessionCacheKeys(), touchedKeys));
    // Check the update timestamps of all keys in the transaction, whether touched or merely read.
    checkBackupGroupRootTimestamps(info.transactionTime,
            union(rootsForUntouchedKeys.entrySet(), rootsForTouchedKeys.entrySet()));
    // Find any BGRs that have children which were touched but were not themselves touched.
    Set<BackupGroupRoot> untouchedRootsWithTouchedChildren = ImmutableSet
            .copyOf(filterKeys(rootsForTouchedKeys, not(in(touchedKeys))).values());
    manifest = CommitLogManifest.create(info.bucketKey, info.transactionTime, info.getDeletes());
    final Key<CommitLogManifest> manifestKey = Key.create(manifest);
    mutations = FluentIterable.from(union(info.getSaves(), untouchedRootsWithTouchedChildren))
            .transform(new Function<Object, ImmutableObject>() {
                @Override
                public CommitLogMutation apply(Object saveEntity) {
                    return CommitLogMutation.create(manifestKey, saveEntity);
                }
            }).toSet();
    ofy().save()
            .entities(new ImmutableSet.Builder<>().add(manifest)
                    .add(bucket.asBuilder().setLastWrittenTime(info.transactionTime).build()).addAll(mutations)
                    .addAll(untouchedRootsWithTouchedChildren).build())
            .now();
}

From source file:com.google.errorprone.bugpatterns.MutableMethodReturnType.java

@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
    MethodSymbol methodSymbol = ASTHelpers.getSymbol(methodTree);

    if (methodSymbol.isConstructor()) {
        return Description.NO_MATCH;
    }// ww w. j a  v a  2 s  . co m

    if (ASTHelpers.methodCanBeOverridden(methodSymbol)) {
        return Description.NO_MATCH;
    }

    if (ANNOTATED_WITH_PRODUCES_OR_PROVIDES.matches(methodTree, state)) {
        return Description.NO_MATCH;
    }

    Type returnType = methodSymbol.getReturnType();
    if (ImmutableCollections.isImmutableType(returnType)) {
        return Description.NO_MATCH;
    }

    ImmutableSet<ClassType> returnStatementsTypes = getMethodReturnTypes(methodTree);
    if (returnStatementsTypes.isEmpty()) {
        return Description.NO_MATCH;
    }
    boolean alwaysReturnsImmutableType = returnStatementsTypes.stream()
            .allMatch(ImmutableCollections::isImmutableType);
    if (!alwaysReturnsImmutableType) {
        return Description.NO_MATCH;
    }

    Optional<String> immutableReturnType = ImmutableCollections
            .mutableToImmutable(getTypeQualifiedName(returnType));
    if (!immutableReturnType.isPresent()) {
        immutableReturnType = getCommonImmutableTypeForAllReturnStatementsTypes(returnStatementsTypes);
    }
    if (!immutableReturnType.isPresent()) {
        return Description.NO_MATCH;
    }

    Type newReturnType = state.getTypeFromString(immutableReturnType.get());
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    Tree typeTree = ASTHelpers.getErasedTypeTree(methodTree.getReturnType());
    verify(typeTree != null, "Could not find return type of %s", methodTree);
    fixBuilder.replace(typeTree, SuggestedFixes.qualifyType(state, fixBuilder, newReturnType.asElement()));
    SuggestedFix fix = fixBuilder.build();

    return describeMatch(methodTree.getReturnType(), fix);
}