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.google.caliper.core.BenchmarkClassModel.java

/**
 * Returns a multimap containing the full set of parameter values to use for the benchmark. For
 * parameters on the benchmark that have values in the given user-supplied parameters, the user's
 * specified values are used. For all other parameters, the default values specified in the
 * annotation or implied by the type are used.
 *
 * @throws IllegalArgumentException if a parameter for the benchmark has neither user-specified
 *     values nor default values//  ww  w.j a  va 2  s.c  om
 */
public final ImmutableSetMultimap<String, String> fillInDefaultParameterValues(
        ImmutableSetMultimap<String, String> userParameters) {
    ImmutableSetMultimap.Builder<String, String> combined = ImmutableSetMultimap.builder();

    // For user parameters, this'll actually be the same as parameters().keySet(), since any extras
    // given at the command line are treated as errors; for VM parameters this is not the case.
    for (String name : Sets.union(parameters().keySet(), userParameters.keySet())) {
        ImmutableSet<String> values = userParameters.containsKey(name) ? userParameters.get(name)
                : parameters().get(name);
        combined.putAll(name, values);
        checkArgument(!values.isEmpty(), "ERROR: No default value provided for %s", name);
    }
    return combined.orderKeysBy(Ordering.natural()).build();
}

From source file:com.facebook.buck.jvm.java.intellij.ModuleBuildContext.java

/**
 * Record a dependency on a {@link BuildTarget}. The dependency's type will be merged if
 * multiple {@link TargetNode}s refer to it or if multiple TargetNodes include sources from
 * the same directory.// w ww .ja  v  a  2  s .  c  om
 *
 * @param sourcePaths the {@link Path}s to sources which need this dependency to build.
 *                    Can be empty.
 * @param buildTargets the {@link BuildTarget}s to depend on
 * @param dependencyType what is the dependency needed for.
 */
public void addDeps(ImmutableSet<Path> sourcePaths, ImmutableSet<BuildTarget> buildTargets,
        DependencyType dependencyType) {
    for (BuildTarget buildTarget : buildTargets) {
        if (circularDependencyInducingTargets.contains(buildTarget)) {
            continue;
        }
        if (sourcePaths.isEmpty()) {
            DependencyType.putWithMerge(dependencyTypeMap, buildTarget, dependencyType);
        } else {
            for (Path sourcePath : sourcePaths) {
                dependencyOriginMap.put(sourcePath, buildTarget);
            }
        }
    }
}

From source file:dagger.internal.codegen.ResolvedBindings.java

/**
 * The members-injection binding, regardless of owning component. Absent if these are contribution
 * bindings, or if there is no members-injection binding because the type fails validation.
 *///from   ww  w  .  j ava 2s  .  co m
Optional<MembersInjectionBinding> membersInjectionBinding() {
    ImmutableSet<MembersInjectionBinding> membersInjectionBindings = FluentIterable
            .from(allMembersInjectionBindings().values()).toSet();
    return membersInjectionBindings.isEmpty() ? Optional.empty()
            : Optional.of(Iterables.getOnlyElement(membersInjectionBindings));
}

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

/** Prints the expanded build rules from the specified build files to the console. */
@Override//from   w w  w.  j  ava2s .  c o m
int runCommandWithOptionsInternal(AuditRulesOptions options) throws IOException {
    ProjectFilesystem projectFilesystem = getProjectFilesystem();

    ProjectBuildFileParserFactory factory = new DefaultProjectBuildFileParserFactory(projectFilesystem,
            options.getBuckConfig().getPythonInterpreter(),
            // TODO(simons): When we land dynamic loading, this MUST change.
            getBuildRuleTypes().getAllDescriptions());
    try (ProjectBuildFileParser parser = factory.createParser(options.getBuckConfig().getDefaultIncludes(),
            EnumSet.noneOf(ProjectBuildFileParser.Option.class), console)) {
        PrintStream out = console.getStdOut();
        for (String pathToBuildFile : options.getArguments()) {
            // Print a comment with the path to the build file.
            out.printf("# %s\n\n", pathToBuildFile);

            // Resolve the path specified by the user.
            Path path = Paths.get(pathToBuildFile);
            if (!path.isAbsolute()) {
                Path root = projectFilesystem.getProjectRoot().toPath();
                path = root.resolve(path);
            }

            // Parse the rules from the build file.
            List<Map<String, Object>> rawRules;
            try {
                rawRules = parser.getAllRules(path);
            } catch (BuildFileParseException e) {
                throw new HumanReadableException(e);
            }

            // Format and print the rules from the raw data, filtered by type.
            final ImmutableSet<String> types = options.getTypes();
            Predicate<String> includeType = new Predicate<String>() {
                @Override
                public boolean apply(String type) {
                    return types.isEmpty() || types.contains(type);
                }
            };
            printRulesToStdout(rawRules, includeType);
        }
    } catch (BuildFileParseException e) {
        throw new HumanReadableException("Unable to create parser");
    }

    return 0;
}

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 {//from  w w w. j av a  2  s.co 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;
}

From source file:com.facebook.buck.ide.intellij.IjProjectCommandHelper.java

/** Run intellij specific project generation actions. */
private int runIntellijProjectGenerator(final TargetGraphAndTargets targetGraphAndTargets)
        throws IOException, InterruptedException {
    ImmutableSet<BuildTarget> requiredBuildTargets = writeProjectAndGetRequiredBuildTargets(
            targetGraphAndTargets);/* w  w  w . j a  v  a  2  s  .  com*/

    if (requiredBuildTargets.isEmpty()) {
        return 0;
    }

    if (projectConfig.isSkipBuildEnabled()) {
        ConsoleEvent.severe("Please remember to buck build --deep the targets you intent to work with.");
        return 0;
    }

    return processAnnotations
            ? buildRequiredTargetsWithoutUsingCacheForAnnotatedTargets(targetGraphAndTargets,
                    requiredBuildTargets)
            : runBuild(requiredBuildTargets);
}

From source file:com.google.api.codegen.transformer.go.GoGapicSurfaceTransformer.java

@VisibleForTesting
List<RetryConfigDefinitionView> generateRetryConfigDefinitions(InterfaceContext context,
        List<MethodModel> methods) {
    Set<RetryConfigDefinitionView.Name> retryNames = new HashSet<>();
    for (MethodModel method : methods) {
        MethodConfig conf = context.getMethodConfig(method);
        retryNames.add(RetryConfigDefinitionView.Name.create(conf.getRetrySettingsConfigName(),
                conf.getRetryCodesConfigName()));
    }//  w  ww  .  j  ava 2 s.c o  m

    TreeMap<RetryConfigDefinitionView.Name, RetryConfigDefinitionView> retryDef = new TreeMap<>();
    Map<String, ImmutableSet<String>> retryCodesDef = context.getInterfaceConfig().getRetryCodesDefinition();
    ImmutableMap<String, RetryParamsDefinitionProto> retryParamsDef = context.getInterfaceConfig()
            .getRetrySettingsDefinition();
    for (RetryConfigDefinitionView.Name name : retryNames) {
        ImmutableSet<String> codes = retryCodesDef.get(name.retryCodesConfigName());
        if (codes.isEmpty()) {
            continue;
        }
        List<String> retryCodeNames = new ArrayList<>();
        for (String code : codes) {
            retryCodeNames.add(context.getNamer().getStatusCodeName(code));
        }
        retryDef.put(name, RetryConfigDefinitionView.newBuilder().name(name).retryCodes(retryCodeNames)
                .params(retryParamsDef.get(name.retrySettingsConfigName())).build());
    }
    if (!retryDef.isEmpty()) {
        context.getImportTypeTable().saveNicknameFor("time;;;");
        context.getImportTypeTable().saveNicknameFor("google.golang.org/grpc/codes;;;");
    }
    return new ArrayList<>(retryDef.values());
}

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

private void aggregateModules(AggregationTreeNode parentNode) {
    if (parentNode.getChildren().isEmpty()) {
        return;//  w ww  .  ja  v  a  2s  . c  o m
    }

    AggregationModule nodeModule = parentNode.getModule();

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

    Path moduleBasePath = parentNode.getModuleBasePath();

    LOG.verbose("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();
        }
    }

    Map<Path, AggregationModule> modulesToAggregate = collectModulesToAggregate(rootModuleType, parentNode,
            modulePathsToAggregate);

    modulesToAggregate.keySet().forEach(parentNode::removeChild);

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

From source file:com.google.devtools.build.lib.remote.GrpcRemoteCache.java

Digest uploadBlob(byte[] blob) throws IOException, InterruptedException {
    Digest digest = Digests.computeDigest(blob);
    ImmutableSet<Digest> missing = getMissingDigests(ImmutableList.of(digest));
    if (!missing.isEmpty()) {
        uploader.uploadBlob(new Chunker(blob));
    }//  w  w w .j a  v a  2 s .  c  o  m
    return digest;
}

From source file:com.google.devtools.build.lib.remote.GrpcRemoteCache.java

/**
 * Put the file contents cache if it is not already in it. No-op if the file is already stored in
 * cache. The given path must be a full absolute path.
 *
 * @return The key for fetching the file contents blob from cache.
 *//*w  w  w . j  ava 2 s.  c om*/
private Digest uploadFileContents(Path file) throws IOException, InterruptedException {
    Digest digest = Digests.computeDigest(file);
    ImmutableSet<Digest> missing = getMissingDigests(ImmutableList.of(digest));
    if (!missing.isEmpty()) {
        uploader.uploadBlob(new Chunker(file));
    }
    return digest;
}