Example usage for com.google.common.collect ImmutableMultimap get

List of usage examples for com.google.common.collect ImmutableMultimap get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMultimap get.

Prototype

@Override
public abstract ImmutableCollection<V> get(K key);

Source Link

Document

Returns an immutable collection of the values for the given key.

Usage

From source file:com.facebook.buck.android.NativeLibraryMergeEnhancer.java

@SuppressWarnings("PMD.PrematureDeclaration")
static NativeLibraryMergeEnhancementResult enhance(CxxBuckConfig cxxBuckConfig, BuildRuleResolver ruleResolver,
        SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, BuildRuleParams buildRuleParams,
        ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> nativePlatforms,
        Map<String, List<Pattern>> mergeMap, Optional<BuildTarget> nativeLibraryMergeGlue,
        ImmutableMultimap<APKModule, NativeLinkable> linkables,
        ImmutableMultimap<APKModule, NativeLinkable> linkablesAssets) throws NoSuchBuildTargetException {
    NativeLibraryMergeEnhancer.ruleFinder = ruleFinder;

    NativeLibraryMergeEnhancementResult.Builder builder = NativeLibraryMergeEnhancementResult.builder();

    ImmutableSet<APKModule> modules = ImmutableSet.<APKModule>builder().addAll(linkables.keySet())
            .addAll(linkablesAssets.keySet()).build();

    ImmutableSortedMap.Builder<String, String> sonameMapBuilder = ImmutableSortedMap.naturalOrder();

    for (APKModule module : modules) {
        // Sort by build target here to ensure consistent behavior.
        Iterable<NativeLinkable> allLinkables = FluentIterable
                .from(Iterables.concat(linkables.get(module), linkablesAssets.get(module)))
                .toSortedList(HasBuildTarget.BUILD_TARGET_COMPARATOR);

        final ImmutableSet<NativeLinkable> linkableAssetSet = ImmutableSet.copyOf(linkablesAssets.get(module));
        Map<NativeLinkable, MergedNativeLibraryConstituents> linkableMembership = makeConstituentMap(
                buildRuleParams, mergeMap, allLinkables, linkableAssetSet);

        sonameMapBuilder.putAll(makeSonameMap(
                // sonames can *theoretically* differ per-platform, but right now they don't on Android,
                // so just pick the first platform and use that to get all the sonames.
                nativePlatforms.values().iterator().next().getCxxPlatform(), linkableMembership));

        Iterable<MergedNativeLibraryConstituents> orderedConstituents = getOrderedMergedConstituents(
                buildRuleParams, linkableMembership);

        Optional<NativeLinkable> glueLinkable = Optional.empty();
        if (nativeLibraryMergeGlue.isPresent()) {
            BuildRule rule = ruleResolver.getRule(nativeLibraryMergeGlue.get());
            if (!(rule instanceof NativeLinkable)) {
                throw new RuntimeException("Native library merge glue " + rule.getBuildTarget()
                        + " for application " + buildRuleParams.getBuildTarget() + " is not linkable.");
            }/*from  w  ww .  j  a  v  a  2 s.c  o  m*/
            glueLinkable = Optional.of(((NativeLinkable) rule));
        }

        Set<MergedLibNativeLinkable> mergedLinkables = createLinkables(cxxBuckConfig, ruleResolver,
                pathResolver, buildRuleParams, glueLinkable, orderedConstituents);

        for (MergedLibNativeLinkable linkable : mergedLinkables) {
            if (Collections.disjoint(linkable.constituents.getLinkables(), linkableAssetSet)) {
                builder.putMergedLinkables(module, linkable);
            } else if (linkableAssetSet.containsAll(linkable.constituents.getLinkables())) {
                builder.putMergedLinkablesAssets(module, linkable);
            }
        }
    }
    builder.setSonameMapping(sonameMapBuilder.build());
    return builder.build();
}

From source file:com.facebook.buck.rules.keys.DefaultDependencyFileRuleKeyBuilderFactory.java

@Override
public RuleKey build(BuildRule rule, ImmutableList<Path> inputs) throws IOException {

    // Create a builder which records all `SourcePath`s which are possibly used by the rule.
    Builder builder = newInstance(rule);

    // Use a multi-map to gather up all the `SourcePath`s that have relative paths that are
    // referenced in the input list, as it's possible for multiple `SourcePath`s to have the
    // same relative path (but come from different cells).
    ImmutableSet<Path> inputSet = ImmutableSet.copyOf(inputs);
    ImmutableMultimap.Builder<Path, SourcePath> relativePathToSourcePathsBuilder = ImmutableMultimap.builder();
    for (SourcePath input : builder.getInputsSoFar()) {
        Path relativePath = pathResolver.getRelativePath(input);
        if (inputSet.contains(relativePath)) {
            relativePathToSourcePathsBuilder.put(relativePath, input);
        }//ww  w  .  jav  a2s. c  o  m
    }
    final ImmutableMultimap<Path, SourcePath> relativePathToSourcePaths = relativePathToSourcePathsBuilder
            .build();

    // Now add the actual given inputs to the rule key using all possible `SourcePath`s they map to.
    // It's important that we do this by walking the `inputs` list, so that we maintain the original
    // ordering the duplicate handling.
    for (Path input : inputs) {
        ImmutableCollection<SourcePath> sourcePaths = relativePathToSourcePaths.get(input);

        // If we don't find actual inputs in the rule that correspond to this input, this likely means
        // that the rule changed to no longer use the input.  In this case, we need to throw a
        // `NoSuchFileException` error so that the build engine handles this as a signal that the dep
        // file rule key can't be used.
        if (sourcePaths.isEmpty()) {
            throw new NoSuchFileException(
                    String.format("%s: could not find any inputs matching the relative path `%s`",
                            rule.getBuildTarget(), input));
        }

        // Add each `SourcePath` using `builder.setPath()`.  We can't use `builder.setSourcePath()`
        // here since the special `RuleKeyBuilder` sub-class that dep-file rule keys use intentionally
        // override `builder.setSourcePath()` to be a noop (and just record the inputs).
        for (SourcePath sourcePath : sourcePaths) {
            builder.setPath(pathResolver.getAbsolutePath(sourcePath), pathResolver.getRelativePath(sourcePath));
        }
    }

    return builder.build();
}

From source file:org.prebake.service.tools.ext.JunitHtmlReportGenerator.java

private static Map<String, Integer> generateHtmlReportOneClass(String packageName, String className,
        Collection<Map<?, ?>> tests, Path reportDir, List<String> resultTypes) throws IOException {
    ImmutableMultimap<String, Map<?, ?>> byTestName = groupBy(tests, new Function<Map<?, ?>, String>() {
        int counter = 0;

        public String apply(Map<?, ?> test) {
            String methodName = getIfOfType(test, ReportKey.METHOD_NAME, String.class);
            if (methodName != null) {
                return methodName;
            }/*from   www  .jav a 2  s  .  co  m*/
            String testName = getIfOfType(test, ReportKey.TEST_NAME, String.class);
            if (testName != null) {
                return testName;
            }
            return "#" + (counter++);
        }
    });
    ImmutableList.Builder<Html> table = ImmutableList.builder();
    Map<String, Integer> summary = Maps.newHashMap();
    Path outFile = reportDir.resolve(className + ".html");
    mkdirs(outFile.getParent());
    String[] testNames = byTestName.keySet().toArray(NO_STRINGS);
    Arrays.sort(testNames);
    for (String testName : testNames) {
        int counter = 0;
        for (Map<?, ?> test : byTestName.get(testName)) {
            int testIndex = counter++;
            Map<String, Integer> itemSummary = generateHtmlReportOneTest(packageName, className, testName,
                    testIndex, test, reportDir.resolve(className), resultTypes);
            bagPutAll(itemSummary, summary);
            table.add(htmlLink(className + "/" + testName + "_" + testIndex + ".html", testName))
                    .add(htmlSpan("summary", summaryToHtml(itemSummary, resultTypes)));
            Object cause = test.get(ReportKey.FAILURE_MESSAGE);
            table.add(htmlFromString(cause instanceof String ? (String) cause : ""));
        }
    }
    writeReport(outFile, "class " + className, KEY_VAL_PREVIEW, table.build(), summary, tests, resultTypes,
            "index", packageName + PACKAGE_FILE_SUFFIX, className);
    return summary;
}

From source file:com.facebook.buck.apple.xcode.ProjectGenerator.java

/**
 * For all inputs by name, verify every entry has identical project level config, and pick one
 * such config to return./*from w  ww .  ja  v  a  2 s.  c  om*/
 *
 * @param configInXcodeLayoutMultimap input mapping of { Config Name -> Config List }
 * @throws com.facebook.buck.util.HumanReadableException
 *    if project-level configs are not identical for a named configuration
 */
private static ImmutableMap<String, ConfigInXcodeLayout> collectProjectLevelConfigsIfIdenticalOrFail(
        ImmutableMultimap<String, ConfigInXcodeLayout> configInXcodeLayoutMultimap) {

    ImmutableMap.Builder<String, ConfigInXcodeLayout> builder = ImmutableMap.builder();

    for (String configName : configInXcodeLayoutMultimap.keySet()) {
        ConfigInXcodeLayout firstConfig = null;
        for (ConfigInXcodeLayout config : configInXcodeLayoutMultimap.get(configName)) {
            if (firstConfig == null) {
                firstConfig = config;
            } else if (!firstConfig.projectLevelConfigFile.equals(config.projectLevelConfigFile)
                    || !firstConfig.projectLevelInlineSettings.equals(config.projectLevelInlineSettings)) {
                throw new HumanReadableException(String.format(
                        "Project level configurations should be identical:\n"
                                + "  Config named: `%s` in `%s` and `%s` ",
                        configName, firstConfig.buildTarget, config.buildTarget));
            }
        }
        Preconditions.checkNotNull(firstConfig);

        builder.put(configName, firstConfig);
    }

    return builder.build();
}

From source file:com.facebook.buck.android.CompileStringsStep.java

@Override
public int execute(ExecutionContext context) {
    ProjectFilesystem filesystem = context.getProjectFilesystem();
    try {/*from   w w w  . j a  v  a2  s .co m*/
        buildResourceNameToIdMap(filesystem, rDotJavaSrcDir.resolve("R.txt"), resourceNameToIdMap);
    } catch (IOException e) {
        context.logError(e, "Failure parsing R.txt file.");
        return 1;
    }

    ImmutableMultimap<String, Path> filesByLocale = groupFilesByLocale(filteredStringFiles);
    Map<String, StringResources> resourcesByLocale = Maps.newHashMap();
    for (String locale : filesByLocale.keySet()) {
        try {
            resourcesByLocale.put(locale, compileStringFiles(filesystem, filesByLocale.get(locale)));
        } catch (IOException e) {
            context.logError(e, "Error parsing string file for locale: %s", locale);
            return 1;
        }
    }

    // Merge region specific locale resources with the corresponding base locale resources.
    //
    // For example, if there are separate string resources in an android project for locale
    // "es" and "es_US", when an application running on a device with locale set to "Spanish
    // (United States)" requests for a string, the Android runtime first looks for the string in
    // "es_US" set of resources, and if not found, returns the resource from the "es" set.
    // We merge these because we want the individual string json files to be self contained for
    // simplicity.
    for (String regionSpecificLocale : regionSpecificToBaseLocaleMap.keySet()) {
        String baseLocale = regionSpecificToBaseLocaleMap.get(regionSpecificLocale);
        if (!resourcesByLocale.containsKey(baseLocale)) {
            continue;
        }

        resourcesByLocale.put(regionSpecificLocale, resourcesByLocale.get(regionSpecificLocale)
                .getMergedResources(resourcesByLocale.get(baseLocale)));
    }

    for (String locale : filesByLocale.keySet()) {
        try {
            filesystem.writeBytesToPath(resourcesByLocale.get(locale).getBinaryFileContent(),
                    destinationDir.resolve(locale + ".fbstr"));
        } catch (IOException e) {
            context.logError(e, "Error creating binary file for locale: %s", locale);
            return 1;
        }
    }

    return 0;
}

From source file:com.google.idea.blaze.base.run.testmap.FilteredTargetMap.java

private Collection<TargetIdeInfo> targetsForSourceFileImpl(ImmutableMultimap<TargetKey, TargetKey> rdepsMap,
        File sourceFile) {/*from  ww  w  .  j  a  v  a 2  s  .co m*/
    List<TargetIdeInfo> result = Lists.newArrayList();
    Collection<TargetKey> roots = rootsMap.get(sourceFile);

    Queue<TargetKey> todo = Queues.newArrayDeque();
    for (TargetKey label : roots) {
        todo.add(label);
    }
    Set<TargetKey> seen = Sets.newHashSet();
    while (!todo.isEmpty()) {
        TargetKey targetKey = todo.remove();
        if (!seen.add(targetKey)) {
            continue;
        }

        TargetIdeInfo target = targetMap.get(targetKey);
        if (filter.test(target)) {
            result.add(target);
        }
        for (TargetKey rdep : rdepsMap.get(targetKey)) {
            todo.add(rdep);
        }
    }
    return result;
}

From source file:com.google.devtools.build.lib.analysis.util.BuildViewForTesting.java

private OrderedSetMultimap<Attribute, ConfiguredTargetAndData> getPrerequisiteMapForTesting(
        final ExtendedEventHandler eventHandler, ConfiguredTarget target,
        BuildConfigurationCollection configurations, ToolchainContext toolchainContext) throws EvalException,
        InvalidConfigurationException, InterruptedException, InconsistentAspectOrderException {
    OrderedSetMultimap<Attribute, Dependency> depNodeNames = getDirectPrerequisiteDependenciesForTesting(
            eventHandler, target, configurations, toolchainContext);

    ImmutableMultimap<Dependency, ConfiguredTargetAndData> cts = skyframeExecutor
            .getConfiguredTargetMapForTesting(eventHandler, target.getConfigurationKey(),
                    ImmutableSet.copyOf(depNodeNames.values()));

    OrderedSetMultimap<Attribute, ConfiguredTargetAndData> result = OrderedSetMultimap.create();
    for (Map.Entry<Attribute, Dependency> entry : depNodeNames.entries()) {
        result.putAll(entry.getKey(), cts.get(entry.getValue()));
    }//ww w  . j  a v  a 2  s .  c  o  m
    return result;
}

From source file:com.android.manifmerger.Actions.java

public String blame(XmlDocument xmlDocument) throws IOException, SAXException, ParserConfigurationException {

    ImmutableMultimap<Integer, Record> resultingSourceMapping = getResultingSourceMapping(xmlDocument);
    LineReader lineReader = new LineReader(new StringReader(xmlDocument.prettyPrint()));

    StringBuilder actualMappings = new StringBuilder();
    String line;//w ww  .j a  v  a 2 s  .c om
    int count = 0;
    while ((line = lineReader.readLine()) != null) {
        actualMappings.append(count + 1).append(line).append("\n");
        if (resultingSourceMapping.containsKey(count)) {
            for (Record record : resultingSourceMapping.get(count)) {
                actualMappings.append(count + 1).append("-->").append(record.getActionLocation().toString())
                        .append("\n");
            }
        }
        count++;
    }
    return actualMappings.toString();
}

From source file:com.facebook.buck.apple.project_generator.XCodeProjectCommandHelper.java

/** Run xcode specific project generation actions. */
private int runXcodeProjectGenerator(ListeningExecutorService executor,
        final TargetGraphAndTargets targetGraphAndTargets, ImmutableSet<BuildTarget> passedInTargetsSet)
        throws IOException, InterruptedException {
    int exitCode = 0;
    AppleConfig appleConfig = buckConfig.getView(AppleConfig.class);
    ImmutableSet<ProjectGenerator.Option> options = buildWorkspaceGeneratorOptions(readOnly,
            isWithTests(buckConfig), isWithDependenciesTests(buckConfig), combinedProject,
            appleConfig.shouldUseHeaderMapsInXcodeProject(), appleConfig.shouldMergeHeaderMapsInXcodeProject(),
            appleConfig.shouldGenerateHeaderSymlinkTreesOnly());

    ImmutableSet<BuildTarget> requiredBuildTargets = generateWorkspacesForTargets(buckEventBus, cell,
            buckConfig, executorService, targetGraphAndTargets, passedInTargetsSet, options,
            getFocusModules(executor), new HashMap<>(), combinedProject);
    if (!requiredBuildTargets.isEmpty()) {
        ImmutableMultimap<Path, String> cellPathToCellName = cell.getCellPathResolver().getCellPaths()
                .asMultimap().inverse();
        ImmutableList<String> arguments = RichStream.from(requiredBuildTargets).map(target -> {
            if (!target.getCellPath().equals(cell.getRoot())) {
                Optional<String> cellName = cellPathToCellName.get(target.getCellPath()).stream().findAny();
                if (cellName.isPresent()) {
                    return target.withUnflavoredBuildTarget(UnflavoredBuildTarget.of(target.getCellPath(),
                            cellName, target.getBaseName(), target.getShortName()));
                } else {
                    throw new IllegalStateException(
                            "Failed to find cell name for cell path while constructing parameters to "
                                    + "build dependencies for project generation. " + "Build target: " + target
                                    + " cell path: " + target.getCellPath());
                }/*from  ww w .  ja  va 2 s .c  om*/
            } else {
                return target;
            }
        }).map(Object::toString).toImmutableList();
        exitCode = buildRunner.apply(arguments);
    }
    return exitCode;
}

From source file:com.facebook.buck.android.apkmodule.APKModuleGraph.java

private void verifyNoSharedSeeds() {
    ImmutableMultimap<BuildTarget, String> sharedSeeds = sharedSeedsSupplier.get();
    if (!sharedSeeds.isEmpty()) {
        StringBuilder errorMessage = new StringBuilder();
        for (BuildTarget seed : sharedSeeds.keySet()) {
            errorMessage.append("BuildTarget: ").append(seed).append(" is used as seed in multiple modules: ");
            for (String module : sharedSeeds.get(seed)) {
                errorMessage.append(module).append(' ');
            }/*from w  w w  . j  av  a  2 s  . com*/
            errorMessage.append('\n');
        }
        throw new IllegalArgumentException(errorMessage.toString());
    }
}