Example usage for com.google.common.collect ImmutableMap entrySet

List of usage examples for com.google.common.collect ImmutableMap entrySet

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap entrySet.

Prototype

public final ImmutableSet<Entry<K, V>> entrySet() 

Source Link

Usage

From source file:com.facebook.buck.python.PexStep.java

/** Return the manifest as a JSON blob to write to the pex processes stdin.
 * <p>/* w  ww. j  a  v  a2s  .  co  m*/
 * We use stdin rather than passing as an argument to the processes since
 * manifest files can occasionally get extremely large, and surpass exec/shell
 * limits on arguments.
 */
@Override
protected Optional<String> getStdin(ExecutionContext context) {
    // Convert the map of paths to a map of strings before converting to JSON.
    ImmutableMap<Path, Path> resolvedModules;
    try {
        resolvedModules = getExpandedSourcePaths(modules);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ImmutableMap.Builder<String, String> modulesBuilder = ImmutableMap.builder();
    for (ImmutableMap.Entry<Path, Path> ent : resolvedModules.entrySet()) {
        modulesBuilder.put(ent.getKey().toString(), ent.getValue().toString());
    }
    ImmutableMap.Builder<String, String> resourcesBuilder = ImmutableMap.builder();
    for (ImmutableMap.Entry<Path, Path> ent : resources.entrySet()) {
        resourcesBuilder.put(ent.getKey().toString(), ent.getValue().toString());
    }
    ImmutableMap.Builder<String, String> nativeLibrariesBuilder = ImmutableMap.builder();
    for (ImmutableMap.Entry<Path, Path> ent : nativeLibraries.entrySet()) {
        nativeLibrariesBuilder.put(ent.getKey().toString(), ent.getValue().toString());
    }
    ImmutableList.Builder<String> prebuiltLibrariesBuilder = ImmutableList.builder();
    for (Path req : prebuiltLibraries) {
        prebuiltLibrariesBuilder.add(req.toString());
    }
    try {
        return Optional.of(context.getObjectMapper()
                .writeValueAsString(ImmutableMap.of("modules", modulesBuilder.build(), "resources",
                        resourcesBuilder.build(), "nativeLibraries", nativeLibrariesBuilder.build(),
                        "prebuiltLibraries", prebuiltLibrariesBuilder.build())));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.facebook.buck.core.config.AbstractAliasConfig.java

/**
 * In a {@link BuckConfig}, an alias can either refer to a fully-qualified build target, or an
 * alias defined earlier in the {@code alias} section. The mapping produced by this method
 * reflects the result of resolving all aliases as values in the {@code alias} section.
 *///from  ww w  . ja  va  2s .c om
private ImmutableSetMultimap<String, BuildTarget> createAliasToBuildTargetMap(
        ImmutableMap<String, String> rawAliasMap) {
    // We use a LinkedHashMap rather than an ImmutableMap.Builder because we want both (1) order to
    // be preserved, and (2) the ability to inspect the Map while building it up.
    SetMultimap<String, BuildTarget> aliasToBuildTarget = LinkedHashMultimap.create();
    for (Map.Entry<String, String> aliasEntry : rawAliasMap.entrySet()) {
        String alias = aliasEntry.getKey();
        validateAliasName(alias);

        // Determine whether the mapping is to a build target or to an alias.
        List<String> values = Splitter.on(' ').splitToList(aliasEntry.getValue());
        for (String value : values) {
            Set<BuildTarget> buildTargets;
            if (isValidAliasName(value)) {
                buildTargets = aliasToBuildTarget.get(value);
                if (buildTargets.isEmpty()) {
                    throw new HumanReadableException("No alias for: %s.", value);
                }
            } else if (value.isEmpty()) {
                continue;
            } else {
                // Here we parse the alias values with a BuildTargetParser to be strict. We could be
                // looser and just grab everything between "//" and ":" and assume it's a valid base path.
                buildTargets = ImmutableSet.of(getDelegate().getBuildTargetForFullyQualifiedTarget(value,
                        EmptyTargetConfiguration.INSTANCE));
            }
            aliasToBuildTarget.putAll(alias, buildTargets);
        }
    }
    return ImmutableSetMultimap.copyOf(aliasToBuildTarget);
}

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 ww . jav a2 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;
}

From source file:com.facebook.buck.java.intellij.IjProjectTemplateDataPreparer.java

public ImmutableSet<DependencyEntry> getDependencies(IjModule module) {
    ImmutableMap<IjProjectElement, IjModuleGraph.DependencyType> deps = moduleGraph.getDepsFor(module);
    IjDependencyListBuilder dependencyListBuilder = new IjDependencyListBuilder();

    for (Map.Entry<IjProjectElement, IjModuleGraph.DependencyType> entry : deps.entrySet()) {
        IjProjectElement element = entry.getKey();
        IjModuleGraph.DependencyType dependencyType = entry.getValue();
        element.addAsDependency(dependencyType, dependencyListBuilder);
    }/*from  ww  w.  j  a v  a 2s  . c om*/
    return dependencyListBuilder.build();
}

From source file:org.apache.atlas.repository.memory.ReplaceIdWithInstance.java

ImmutableMap<?, ?> convertToInstances(ImmutableMap val, Multiplicity m, DataTypes.MapType mapType)
        throws AtlasException {

    if (val == null || (mapType.getKeyType().getTypeCategory() != DataTypes.TypeCategory.CLASS
            && mapType.getValueType().getTypeCategory() != DataTypes.TypeCategory.CLASS)) {
        return val;
    }//from w ww .  j  a  v  a  2  s .c o m
    ImmutableMap.Builder b = ImmutableMap.builder();
    for (Map.Entry elem : (Iterable<Map.Entry>) val.entrySet()) {
        Object oldKey = elem.getKey();
        Object oldValue = elem.getValue();
        Object newKey = oldKey;
        Object newValue = oldValue;

        if (oldKey instanceof Id) {
            Id id = (Id) elem;
            ITypedReferenceableInstance r = getInstance(id);
        }

        if (oldValue instanceof Id) {
            Id id = (Id) elem;
            ITypedReferenceableInstance r = getInstance(id);
        }

        b.put(newKey, newValue);
    }
    return b.build();
}

From source file:com.facebook.buck.macho.ObjectPathsAbsolutifier.java

private void unsanitizeObjectFiles(ImmutableMap<Path, Path> originalToUpdatedPathMap) throws IOException {
    for (Map.Entry<Path, Path> entry : originalToUpdatedPathMap.entrySet()) {
        Path source = entry.getKey();
        if (Files.isDirectory(source)) {
            continue;
        }//  w  ww. j  a v  a  2s .  c o m
        Path destination = entry.getValue();

        if (Files.notExists(destination.getParent())) {
            Files.createDirectories(destination.getParent());
        }
        Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
        if (!destination.toFile().setLastModified(source.toFile().lastModified())) {
            LOG.warn("Unable to set modification date for file %s", source);
        }

        if (destination.getFileName().toString().endsWith(".o")) {
            CompDirReplacer.replaceCompDirInFile(destination, oldCompDir, newCompDir,
                    nulTerminatedCharsetDecoder);
        } else if (destination.getFileName().toString().endsWith(".a")) {
            fixCompDirInStaticLibrary(destination);
        }
    }
}

From source file:com.facebook.buck.rage.VcsInfoCollector.java

public SourceControlInfo gatherScmInformation()
        throws InterruptedException, VersionControlCommandFailedException {
    String currentRevisionId = vcCmdLineInterface.currentRevisionId();
    ImmutableMap<String, String> bookmarksRevisionIds = vcCmdLineInterface
            .bookmarksRevisionsId(TRACKED_BOOKMARKS);
    String baseRevisionId = vcCmdLineInterface.commonAncestor(currentRevisionId,
            bookmarksRevisionIds.get("remote/master"));
    ImmutableSet<String> changedFiles = vcCmdLineInterface.changedFiles(baseRevisionId);

    ImmutableSet.Builder<String> baseBookmarks = ImmutableSet.builder();
    for (Map.Entry<String, String> bookmark : bookmarksRevisionIds.entrySet()) {
        if (bookmark.getValue().startsWith(baseRevisionId)) {
            baseBookmarks.add(bookmark.getKey());
        }/*from  w w w. ja v  a2  s. c o m*/
    }

    Optional<String> diff = Optional
            .of(vcCmdLineInterface.diffBetweenRevisions(baseRevisionId, currentRevisionId));

    return SourceControlInfo.builder().setCurrentRevisionId(currentRevisionId)
            .setRevisionIdOffTracked(baseRevisionId).setBasedOffWhichTracked(baseBookmarks.build())
            .setDiff(diff).setDirtyFiles(changedFiles).build();
}

From source file:com.facebook.buck.versions.VersionUniverseVersionSelector.java

private ImmutableMap<BuildTarget, Version> selectVersions(BuildTarget root,
        ImmutableMap<BuildTarget, ImmutableSet<Version>> domain) throws VersionException {

    TargetNode<?, ?> node = targetGraph.get(root);
    ImmutableMap.Builder<BuildTarget, Version> selectedVersions = ImmutableMap.builder();

    Optional<Map.Entry<String, VersionUniverse>> universe = getVersionUniverse(node);
    LOG.verbose("%s: selected universe: %s", root.getBuildTarget(), universe);
    for (Map.Entry<BuildTarget, ImmutableSet<Version>> ent : domain.entrySet()) {
        Version version;/* www. ja  v  a2  s  . c o m*/
        if (universe.isPresent()
                && ((version = universe.get().getValue().getVersions().get(ent.getKey())) != null)) {
            if (!ent.getValue().contains(version)) {
                throw new VersionException(root, String.format(
                        "%s has no version %s (specified by universe %s) in available versions: %s", version,
                        ent.getKey(), universe.get().getKey(), Joiner.on(", ").join(ent.getValue())));
            }
        } else {
            version = Iterables.get(ent.getValue(), 0);
        }
        selectedVersions.put(ent.getKey(), version);
    }

    return selectedVersions.build();
}

From source file:io.fabric8.container.process.ProcessControllerFactoryService.java

protected void onConfigurationChanged() {
    ProcessManager manager = getProcessManager();
    FabricService fabric = getFabricService();
    if (manager != null && fabric != null) {
        ImmutableMap<String, Installation> map = manager.listInstallationMap();
        ImmutableSet<Map.Entry<String, Installation>> entries = map.entrySet();
        for (Map.Entry<String, Installation> entry : entries) {
            String id = entry.getKey();
            Installation installation = entry.getValue();
            try {
                Container container = null;
                try {
                    container = fabric.getContainer(id);
                } catch (Exception e) {
                    LOG.debug("No container for id: " + id + ". " + e, e);
                }/*from w w  w .  j a  v  a 2s.c  o  m*/
                if (container != null && installation != null) {
                    ChildContainerController controllerForContainer = getControllerForContainer(container);
                    if (controllerForContainer instanceof ProcessManagerController) {
                        ProcessManagerController processManagerController = (ProcessManagerController) controllerForContainer;
                        processManagerController.updateInstallation(container, installation);
                    }
                }
            } catch (Exception e) {
                LOG.warn("Failed to get PID for process " + id + ". " + e, e);
            }
        }
    }

}

From source file:com.facebook.buck.thrift.ThriftPythonEnhancer.java

@Override
public PythonLibrary createBuildRule(TargetGraph targetGraph, BuildRuleParams params,
        BuildRuleResolver resolver, ThriftConstructorArg args, ImmutableMap<String, ThriftSource> sources,
        ImmutableSortedSet<BuildRule> deps) {

    ImmutableMap.Builder<Path, SourcePath> modulesBuilder = ImmutableMap.builder();

    // Iterate over all the thrift source, finding the python modules they generate and
    // building up a map of them.
    for (ImmutableMap.Entry<String, ThriftSource> ent : sources.entrySet()) {
        ThriftSource source = ent.getValue();
        Path outputDir = source.getOutputDir();

        for (String module : getGeneratedSources(params.getBuildTarget(), args, ent.getKey(),
                source.getServices())) {
            Path path = outputDir.resolve("gen-" + getLanguage()).resolve(module);
            modulesBuilder.put(Paths.get(module.endsWith(".py") ? module : module + ".py"),
                    new BuildTargetSourcePath(source.getCompileRule().getBuildTarget(), path));
        }//from   w w  w. ja  v a  2 s.  c  o m

    }

    ImmutableMap<Path, SourcePath> modules = modulesBuilder.build();

    // Create params which only use the language specific deps.
    BuildRuleParams langParams = params.copyWithChanges(params.getBuildTarget(), Suppliers.ofInstance(deps),
            Suppliers.ofInstance(ImmutableSortedSet.of()));

    // Construct a python library and return it as our language specific build rule.  Dependents
    // will use this to pull the generated sources into packages/PEXs.
    Function<? super PythonPlatform, ImmutableMap<Path, SourcePath>> resources = Functions
            .constant(ImmutableMap.<Path, SourcePath>of());
    return new PythonLibrary(langParams, new SourcePathResolver(new SourcePathRuleFinder(resolver)),
            Functions.constant(modules), resources, Optional.of(true));
}