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

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

Introduction

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

Prototype

public static <K, V> Builder<K, V> builder() 

Source Link

Document

Returns a new builder.

Usage

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

/**
 * Group the classes in the input jars into a multimap based on the APKModule they belong to
 *
 * @param apkModuleToJarPathMap the mapping of APKModules to the path for the jar files
 * @param translatorFunction function used to translate the class names to obfuscated names
 * @param filesystem filesystem representation for resolving paths
 * @return The mapping of APKModules to the class names they contain
 * @throws IOException/*from w  ww  .  j a  va  2 s. c  o  m*/
 */
public static ImmutableMultimap<APKModule, String> getAPKModuleToClassesMap(
        ImmutableMultimap<APKModule, Path> apkModuleToJarPathMap, Function<String, String> translatorFunction,
        ProjectFilesystem filesystem) throws IOException {
    ImmutableMultimap.Builder<APKModule, String> builder = ImmutableSetMultimap.builder();
    if (!apkModuleToJarPathMap.isEmpty()) {
        for (APKModule dexStore : apkModuleToJarPathMap.keySet()) {
            for (Path jarFilePath : apkModuleToJarPathMap.get(dexStore)) {
                ClasspathTraverser classpathTraverser = new DefaultClasspathTraverser();
                classpathTraverser.traverse(new ClasspathTraversal(ImmutableSet.of(jarFilePath), filesystem) {
                    @Override
                    public void visit(FileLike entry) {
                        if (!entry.getRelativePath().endsWith(".class")) {
                            // ignore everything but class files in the jar.
                            return;
                        }

                        String classpath = entry.getRelativePath().replaceAll("\\.class$", "");

                        if (translatorFunction.apply(classpath) != null) {
                            builder.put(dexStore, translatorFunction.apply(classpath));
                        }
                    }
                });
            }
        }
    }
    return builder.build();
}

From source file:org.sosy_lab.cpachecker.util.precondition.segkro.RefineSolverBasedItp.java

@Override
public PredicatePrecision refine(final PathPosition pTraceFromViolation,
        final PathPosition pTraceFromValidTermination)
        throws SolverException, InterruptedException, CPATransferException {

    // Compute the precondition for both traces
    PathFormula pcViolation = pre(pTraceFromViolation, FormulaMode.INSTANTIATED);
    PathFormula pcValid = pre(pTraceFromValidTermination, FormulaMode.INSTANTIATED);

    // "Enrich" the preconditions with more general predicates
    // TODO: Is this part completely useless when using QE?
    pcViolation = alterPf(pcViolation,// w  ww. jav a 2  s.co m
            interpolate(pcViolation.getFormula(), pcValid.getFormula(), pTraceFromViolation));
    pcValid = alterPf(pcValid,
            interpolate(pcValid.getFormula(), pcViolation.getFormula(), pTraceFromValidTermination));

    // Now we have an initial set of useful predicates; add them to the corresponding list.
    Builder<BooleanFormula> globalPreds = ImmutableList.builder();
    ImmutableMultimap.Builder<CFANode, BooleanFormula> localPreds = ImmutableMultimap.builder();

    globalPreds.addAll(uninstantiatedLiterals(pcViolation.getFormula()));
    globalPreds.addAll(uninstantiatedLiterals(pcValid.getFormula()));

    // Get additional predicates from the states along the trace
    //    (or the WPs along the trace)...
    //
    // -- along the trace to the violating state...
    Multimap<CFANode, BooleanFormula> predsViolation = predsFromTrace(pTraceFromViolation, pcViolation);
    localPreds.putAll(predsViolation);
    // -- along the trace to the termination state...
    Multimap<CFANode, BooleanFormula> predsFromValid = predsFromTrace(pTraceFromValidTermination, pcValid);
    localPreds.putAll(predsFromValid);

    return predicatesAsGlobalPrecision(globalPreds.build(), localPreds.build());
}

From source file:org.sonar.plugins.csharp.RoslynProfileExporter.java

static Multimap<String, RuleKey> activeRoslynRulesByPartialRepoKey(Iterable<RuleKey> activeRules) {
    ImmutableMultimap.Builder<String, RuleKey> builder = ImmutableMultimap.builder();

    for (RuleKey activeRule : activeRules) {
        if (activeRule.repository().startsWith(ROSLYN_REPOSITORY_PREFIX)) {
            String pluginKey = activeRule.repository().substring(ROSLYN_REPOSITORY_PREFIX.length());
            builder.put(pluginKey, activeRule);
        } else if (CSharpSonarRulesDefinition.REPOSITORY_KEY.equals(activeRule.repository())) {
            builder.put(SONARANALYZER_PARTIAL_REPO_KEY, activeRule);
        }/*  w w  w.j a v  a2 s  .c om*/
    }

    return builder.build();
}

From source file:com.facebook.presto.raptor.storage.BucketBalancer.java

@VisibleForTesting
ClusterState fetchClusterState() {/*from w ww.ja v a  2s.c  o m*/
    Set<String> activeNodes = nodeSupplier.getWorkerNodes().stream().map(Node::getNodeIdentifier)
            .collect(toSet());

    Map<String, Long> assignedNodeSize = new HashMap<>(
            activeNodes.stream().collect(toMap(node -> node, node -> 0L)));
    ImmutableMultimap.Builder<Distribution, BucketAssignment> distributionAssignments = ImmutableMultimap
            .builder();
    ImmutableMap.Builder<Distribution, Long> distributionBucketSize = ImmutableMap.builder();

    for (Distribution distribution : shardManager.getDistributions()) {
        long distributionSize = shardManager.getDistributionSizeInBytes(distribution.getId());
        long bucketSize = (long) (1.0 * distributionSize) / distribution.getBucketCount();
        distributionBucketSize.put(distribution, bucketSize);

        for (BucketNode bucketNode : shardManager.getBucketNodes(distribution.getId())) {
            String node = bucketNode.getNodeIdentifier();
            distributionAssignments.put(distribution,
                    new BucketAssignment(distribution.getId(), bucketNode.getBucketNumber(), node));
            assignedNodeSize.merge(node, bucketSize, Math::addExact);
        }
    }

    return new ClusterState(activeNodes, assignedNodeSize, distributionAssignments.build(),
            distributionBucketSize.build());
}

From source file:com.facebook.presto.accumulo.index.IndexLookup.java

private boolean getRangesWithMetrics(ConnectorSession session, String schema, String table,
        Multimap<AccumuloColumnConstraint, Range> constraintRanges, Collection<Range> rowIdRanges,
        List<TabletSplitMetadata> tabletSplits, Authorizations auths) throws Exception {
    String metricsTable = getMetricsTableName(schema, table);
    long numRows = getNumRowsInTable(metricsTable, auths);

    // Get the cardinalities from the metrics table
    Multimap<Long, AccumuloColumnConstraint> cardinalities;
    if (isIndexShortCircuitEnabled(session)) {
        cardinalities = cardinalityCache.getCardinalities(schema, table, auths, constraintRanges,
                (long) (numRows * getIndexSmallCardThreshold(session)),
                getIndexCardinalityCachePollingDuration(session));
    } else {/*from   w ww. ja v a  2 s .co  m*/
        // disable short circuit using 0
        cardinalities = cardinalityCache.getCardinalities(schema, table, auths, constraintRanges, 0,
                new Duration(0, TimeUnit.MILLISECONDS));
    }

    Optional<Entry<Long, AccumuloColumnConstraint>> entry = cardinalities.entries().stream().findFirst();
    if (!entry.isPresent()) {
        return false;
    }

    Entry<Long, AccumuloColumnConstraint> lowestCardinality = entry.get();
    String indexTable = getIndexTableName(schema, table);
    double threshold = getIndexThreshold(session);
    List<Range> indexRanges;

    // If the smallest cardinality in our list is above the lowest cardinality threshold,
    // we should look at intersecting the row ID ranges to try and get under the threshold.
    if (smallestCardAboveThreshold(session, numRows, lowestCardinality.getKey())) {
        // If we only have one column, we can skip the intersection process and just check the index threshold
        if (cardinalities.size() == 1) {
            long numEntries = lowestCardinality.getKey();
            double ratio = ((double) numEntries / (double) numRows);
            LOG.debug("Use of index would scan %d of %d rows, ratio %s. Threshold %2f, Using for table? %b",
                    numEntries, numRows, ratio, threshold, ratio < threshold);
            if (ratio >= threshold) {
                return false;
            }
        }

        // Else, get the intersection of all row IDs for all column constraints
        LOG.debug("%d indexed columns, intersecting ranges", constraintRanges.size());
        indexRanges = getIndexRanges(indexTable, constraintRanges, rowIdRanges, auths);
        LOG.debug("Intersection results in %d ranges from secondary index", indexRanges.size());
    } else {
        // Else, we don't need to intersect the columns and we can just use the column with the lowest cardinality,
        // so get all those row IDs in a set of ranges.
        LOG.debug("Not intersecting columns, using column with lowest cardinality ");
        ImmutableMultimap.Builder<AccumuloColumnConstraint, Range> lcBldr = ImmutableMultimap.builder();
        lcBldr.putAll(lowestCardinality.getValue(), constraintRanges.get(lowestCardinality.getValue()));
        indexRanges = getIndexRanges(indexTable, lcBldr.build(), rowIdRanges, auths);
    }

    if (indexRanges.isEmpty()) {
        LOG.debug("Query would return no results, returning empty list of splits");
        return true;
    }

    // Okay, we now check how many rows we would scan by using the index vs. the overall number
    // of rows
    long numEntries = indexRanges.size();
    double ratio = (double) numEntries / (double) numRows;
    LOG.debug("Use of index would scan %d of %d rows, ratio %s. Threshold %2f, Using for table? %b", numEntries,
            numRows, ratio, threshold, ratio < threshold, table);

    // If the percentage of scanned rows, the ratio, less than the configured threshold
    if (ratio < threshold) {
        // Bin the ranges into TabletMetadataSplits and return true to use the tablet splits
        binRanges(getNumIndexRowsPerSplit(session), indexRanges, tabletSplits);
        LOG.debug("Number of splits for %s.%s is %d with %d ranges", schema, table, tabletSplits.size(),
                indexRanges.size());
        return true;
    } else {
        // We are going to do too much work to use the secondary index, so return false
        return false;
    }
}

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

public ImmutableMultimap<Integer, Record> getResultingSourceMapping(XmlDocument xmlDocument)
        throws ParserConfigurationException, SAXException, IOException {

    SourceFile inMemory = SourceFile.UNKNOWN;

    XmlDocument loadedWithLineNumbers = XmlLoader.load(xmlDocument.getSelectors(),
            xmlDocument.getSystemPropertyResolver(), inMemory, xmlDocument.prettyPrint(), XmlDocument.Type.MAIN,
            Optional.<String>absent() /* mainManifestPackageName */);

    ImmutableMultimap.Builder<Integer, Record> mappingBuilder = ImmutableMultimap.builder();
    for (XmlElement xmlElement : loadedWithLineNumbers.getRootNode().getMergeableElements()) {
        parse(xmlElement, mappingBuilder);
    }//from   ww  w.  j  a va  2  s  .c o m
    return mappingBuilder.build();
}

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

private void generateProjects(Map<Path, ProjectGenerator> projectGenerators,
        ListeningExecutorService listeningExecutorService, String workspaceName, Path outputDirectory,
        WorkspaceGenerator workspaceGenerator, ImmutableSet<BuildTarget> targetsInRequiredProjects,
        ImmutableMultimap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder,
        ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder,
        Optional<BuildTarget> targetToBuildWithBuck) throws IOException, InterruptedException {
    if (combinedProject) {
        generateCombinedProject(workspaceName, outputDirectory, workspaceGenerator, targetsInRequiredProjects,
                buildTargetToPbxTargetMapBuilder, targetToProjectPathMapBuilder, targetToBuildWithBuck);
    } else {// ww  w  .  j a  v  a  2 s .  c o  m
        generateProject(projectGenerators, listeningExecutorService, workspaceGenerator,
                targetsInRequiredProjects, buildTargetToPbxTargetMapBuilder, targetToProjectPathMapBuilder,
                targetToBuildWithBuck);
    }
}

From source file:org.apache.beam.fn.harness.control.ProcessBundleHandler.java

/**
 * Converts a {@link org.apache.beam.fn.v1.BeamFnApi.FunctionSpec} into a {@link DoFnRunner}.
 *///from   ww w.  jav a  2  s  . c o  m
private <InputT, OutputT> DoFnRunner<InputT, OutputT> createDoFnRunner(BeamFnApi.FunctionSpec functionSpec,
        Map<String, Collection<ThrowingConsumer<WindowedValue<OutputT>>>> outputMap) {
    ByteString serializedFn;
    try {
        serializedFn = functionSpec.getData().unpack(BytesValue.class).getValue();
    } catch (InvalidProtocolBufferException e) {
        throw new IllegalArgumentException(String.format("Unable to unwrap DoFn %s", functionSpec), e);
    }
    DoFnInfo<?, ?> doFnInfo = (DoFnInfo<?, ?>) SerializableUtils
            .deserializeFromByteArray(serializedFn.toByteArray(), "DoFnInfo");

    checkArgument(
            Objects.equals(new HashSet<>(Collections2.transform(outputMap.keySet(), Long::parseLong)),
                    doFnInfo.getOutputMap().keySet()),
            "Unexpected mismatch between transform output map %s and DoFnInfo output map %s.",
            outputMap.keySet(), doFnInfo.getOutputMap());

    ImmutableMultimap.Builder<TupleTag<?>, ThrowingConsumer<WindowedValue<OutputT>>> tagToOutput = ImmutableMultimap
            .builder();
    for (Map.Entry<Long, TupleTag<?>> entry : doFnInfo.getOutputMap().entrySet()) {
        tagToOutput.putAll(entry.getValue(), outputMap.get(Long.toString(entry.getKey())));
    }
    @SuppressWarnings({ "unchecked", "rawtypes" })
    final Map<TupleTag<?>, Collection<ThrowingConsumer<WindowedValue<?>>>> tagBasedOutputMap = (Map) tagToOutput
            .build().asMap();

    OutputManager outputManager = new OutputManager() {
        Map<TupleTag<?>, Collection<ThrowingConsumer<WindowedValue<?>>>> tupleTagToOutput = tagBasedOutputMap;

        @Override
        public <T> void output(TupleTag<T> tag, WindowedValue<T> output) {
            try {
                Collection<ThrowingConsumer<WindowedValue<?>>> consumers = tupleTagToOutput.get(tag);
                if (consumers == null) {
                    /* This is a normal case, e.g., if a DoFn has output but that output is not
                     * consumed. Drop the output. */
                    return;
                }
                for (ThrowingConsumer<WindowedValue<?>> consumer : consumers) {
                    consumer.accept(output);
                }
            } catch (Throwable t) {
                throw new RuntimeException(t);
            }
        }
    };

    @SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
    DoFnRunner<InputT, OutputT> runner = DoFnRunners.simpleRunner(PipelineOptionsFactory.create(), /* TODO */
            (DoFn) doFnInfo.getDoFn(), NullSideInputReader.empty(), /* TODO */
            outputManager, (TupleTag) doFnInfo.getOutputMap().get(doFnInfo.getMainOutput()),
            new ArrayList<>(doFnInfo.getOutputMap().values()), new FakeStepContext(),
            (WindowingStrategy) doFnInfo.getWindowingStrategy());
    return runner;
}

From source file:org.jdbi.v3.guava.GuavaCollectors.java

private static <K, V, MB extends ImmutableMultimap.Builder<K, V>> MB combine(MB a, MB b) {
    a.putAll(b.build());
    return a;
}

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

private void parse(XmlElement element, ImmutableMultimap.Builder<Integer, Record> mappings) {
    DecisionTreeRecord decisionTreeRecord = mRecords.get(element.getId());
    if (decisionTreeRecord != null) {
        Actions.NodeRecord nodeRecord = findNodeRecord(decisionTreeRecord);
        if (nodeRecord != null) {
            mappings.put(element.getPosition().getStartLine(), nodeRecord);
        }//from  w  w  w. j av a 2  s  .c  om
        for (XmlAttribute xmlAttribute : element.getAttributes()) {
            Actions.AttributeRecord attributeRecord = findAttributeRecord(decisionTreeRecord, xmlAttribute);
            if (attributeRecord != null) {
                mappings.put(xmlAttribute.getPosition().getStartLine(), attributeRecord);
            }
        }
    }
    for (XmlElement xmlElement : element.getMergeableElements()) {
        parse(xmlElement, mappings);
    }
}