Example usage for com.google.common.collect Multimap asMap

List of usage examples for com.google.common.collect Multimap asMap

Introduction

In this page you can find the example usage for com.google.common.collect Multimap asMap.

Prototype

Map<K, Collection<V>> asMap();

Source Link

Document

Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values.

Usage

From source file:de.dentrassi.pm.aspect.upgrade.UpgradeTaskProvider.java

private List<Task> updateState() {
    try (Handle handle = Profile.start(this, "updateState")) {
        final Map<String, ChannelAspectInformation> infos = ChannelAspectProcessor
                .scanAspectInformations(this.context);

        final List<Task> result = new LinkedList<>();

        final Multimap<String, Channel> missing = HashMultimap.create();

        final Multimap<Channel, String> channels = HashMultimap.create();

        for (final Channel channel : this.service.listChannels()) {
            logger.debug("Checking channel: {}", channel.getId());

            final Map<String, String> states = channel.getAspectStates();
            for (final Map.Entry<String, String> entry : states.entrySet()) {
                logger.debug("\t{}", entry.getKey());

                final ChannelAspectInformation info = infos.get(entry.getKey());
                if (info == null) {
                    missing.put(entry.getKey(), channel);
                } else {
                    logger.debug("\t{} - {} -> {}", info.getFactoryId(), entry.getValue(), info.getVersion());

                    if (!info.getVersion().equals(Version.valueOf(entry.getValue()))) {
                        result.add(makeUpgradeTask(channel, info, entry.getValue()));
                        channels.put(channel, entry.getKey());
                    }/*ww w .j a  v  a 2  s . com*/
                }
            }
        }

        for (final Map.Entry<Channel, Collection<String>> entry : channels.asMap().entrySet()) {
            final Channel channel = entry.getKey();
            final LinkTarget target = new LinkTarget(
                    String.format("/channel/%s/refreshAllAspects", channel.getId()));
            final String description = "Channel aspects active in this channel have been updated. You can refresh the whole channel.";
            result.add(new BasicTask("Refresh channel: " + makeChannelTitle(channel), 100, description, target,
                    RequestMethod.GET, PERFORM_ALL_BUTTON));
        }

        for (final Map.Entry<String, Collection<Channel>> entry : missing.asMap().entrySet()) {
            final String missingChannels = entry.getValue().stream().map(Channel::getId)
                    .collect(Collectors.joining(", "));
            result.add(new BasicTask(String.format("Fix missing channel aspect: %s", entry.getKey()), 1,
                    String.format(
                            "The channel aspect '%s' is being used but not installed in the system. Channels: %s",
                            entry.getKey(), missingChannels),
                    null));
        }

        if (!channels.isEmpty()) {
            result.add(new BasicTask("Refresh all channels", 1, "Refresh all channels in one big task",
                    new LinkTarget(String.format("/job/%s/create", UpgradeAllChannelsJob.ID)),
                    RequestMethod.POST, PERFORM_ALL_SUPER_BUTTON));
        }

        return result;
    }
}

From source file:org.sourcepit.maven.dependency.model.aether.DependencyModelBuildingGraphTransformer.java

private void pruneUnreferenced(DependencyNode graph) {
    final Multimap<DependencyNode, DependencyNode> foo = LinkedHashMultimap.create();

    graph.accept(new AbstractDependencyVisitor(false) {
        @Override//w  ww . j  a  v a 2 s.  c  o  m
        protected boolean onVisitLeave(DependencyNode parent, DependencyNode node) {
            for (Iterator<DependencyNode> it = node.getChildren().iterator(); it.hasNext();) {
                final DependencyNode childNode = (DependencyNode) it.next();
                if (!isReferenced(childNode)) {
                    foo.put(node, childNode);
                    // it.remove();
                }
            }
            return super.onVisitLeave(parent, node);
        }

        private boolean isReferenced(DependencyNode node) {
            Dependency dependency = node.getDependency();
            if (dependency != null) {
                return referencedArtifacts.contains(toArtifactKey(dependency.getArtifact()));
            }
            return true;
        }
    });

    for (Entry<DependencyNode, Collection<DependencyNode>> entry : foo.asMap().entrySet()) {
        DependencyNode parent = entry.getKey();
        parent.getChildren().removeAll(entry.getValue());
    }
}

From source file:org.eclipse.packagedrone.repo.aspect.upgrade.UpgradeTaskProvider.java

private List<Task> updateState() {
    try (Handle handle = Profile.start(this, "updateState")) {
        final Map<String, ChannelAspectInformation> infos = ChannelAspectProcessor
                .scanAspectInformations(this.context);

        final List<Task> result = new LinkedList<>();

        final Multimap<String, ChannelInformation> missing = HashMultimap.create();

        final Multimap<ChannelInformation, String> channels = HashMultimap.create();

        for (final ChannelInformation channel : this.service.list()) {
            logger.debug("Checking channel: {}", channel.getId());

            final Map<String, String> states = channel.getAspectStates();
            for (final Map.Entry<String, String> entry : states.entrySet()) {
                logger.debug("\t{}", entry.getKey());

                final ChannelAspectInformation info = infos.get(entry.getKey());
                if (info == null) {
                    missing.put(entry.getKey(), channel);
                } else {
                    logger.debug("\t{} - {} -> {}", info.getFactoryId(), entry.getValue(), info.getVersion());

                    if (!info.getVersion().equals(Version.valueOf(entry.getValue()))) {
                        result.add(makeUpgradeTask(channel, info, entry.getValue()));
                        channels.put(channel, entry.getKey());
                    }/* w  ww  .  j a va 2s . c  o m*/
                }
            }
        }

        for (final Map.Entry<ChannelInformation, Collection<String>> entry : channels.asMap().entrySet()) {
            final ChannelInformation channel = entry.getKey();
            final LinkTarget target = new LinkTarget(String.format("/channel/%s/refreshAllAspects",
                    UrlEscapers.urlPathSegmentEscaper().escape(channel.getId())));
            final String description = "Channel aspects active in this channel have been updated. You can refresh the whole channel.";
            result.add(new BasicTask("Refresh channel: " + channel.makeTitle(), 100, description, target,
                    RequestMethod.GET, PERFORM_ALL_BUTTON));
        }

        for (final Map.Entry<String, Collection<ChannelInformation>> entry : missing.asMap().entrySet()) {
            final String missingChannels = entry.getValue().stream().map(ChannelInformation::getId)
                    .collect(Collectors.joining(", "));
            result.add(new BasicTask(String.format("Fix missing channel aspect: %s", entry.getKey()), 1,
                    String.format(
                            "The channel aspect '%s' is being used but not installed in the system. Channels: %s",
                            entry.getKey(), missingChannels),
                    null));
        }

        if (!channels.isEmpty()) {
            result.add(new BasicTask("Refresh all channels", 1, "Refresh all channels in one big task",
                    new LinkTarget(String.format("/job/%s/create", UpgradeAllChannelsJob.ID)),
                    RequestMethod.POST, PERFORM_ALL_SUPER_BUTTON));
        }

        return result;
    }
}

From source file:com.google.devtools.build.lib.query2.RdepsUnboundedVisitor.java

@Override
protected Visit getVisitResult(Iterable<DepAndRdep> depAndRdeps) throws InterruptedException {
    Collection<SkyKey> validRdeps = new ArrayList<>();

    // Multimap of dep to all the reverse deps in this visitation. Used to filter out the
    // disallowed deps.
    Multimap<SkyKey, SkyKey> reverseDepMultimap = ArrayListMultimap.create();
    for (DepAndRdep depAndRdep : depAndRdeps) {
        // The "roots" of our visitation (see #preprocessInitialVisit) have a null 'dep' field.
        if (depAndRdep.dep == null) {
            validRdeps.add(depAndRdep.rdep);
        } else {// w w  w. j  a  v a2 s.  c  o  m
            reverseDepMultimap.put(depAndRdep.dep, depAndRdep.rdep);
        }
    }

    Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap = env
            .makePackageKeyToTargetKeyMap(Iterables.concat(reverseDepMultimap.values()));
    Set<PackageIdentifier> pkgIdsNeededForTargetification = packageKeyToTargetKeyMap.keySet().stream()
            .map(SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER).collect(toImmutableSet());
    packageSemaphore.acquireAll(pkgIdsNeededForTargetification);

    try {
        // Filter out disallowed deps. We cannot defer the targetification any further as we do not
        // want to retrieve the rdeps of unwanted nodes (targets).
        if (!reverseDepMultimap.isEmpty()) {
            Collection<Target> filteredTargets = env.filterRawReverseDepsOfTransitiveTraversalKeys(
                    reverseDepMultimap.asMap(), packageKeyToTargetKeyMap);
            filteredTargets.stream().map(SkyQueryEnvironment.TARGET_TO_SKY_KEY).forEachOrdered(validRdeps::add);
        }
    } finally {
        packageSemaphore.releaseAll(pkgIdsNeededForTargetification);
    }

    ImmutableList<SkyKey> uniqueValidRdeps = validRdeps.stream().filter(validRdepUniquifier::unique)
            .collect(ImmutableList.toImmutableList());

    // Retrieve the reverse deps as SkyKeys and defer the targetification and filtering to next
    // recursive visitation.
    ImmutableList.Builder<DepAndRdep> depAndRdepsToVisitBuilder = ImmutableList.builder();
    env.graph
            .getReverseDeps(
                    uniqueValidRdeps)
            .entrySet()
            .forEach(reverseDepsEntry -> depAndRdepsToVisitBuilder.addAll(Iterables.transform(
                    Iterables.filter(reverseDepsEntry.getValue(),
                            Predicates.and(SkyQueryEnvironment.IS_TTV, universe)),
                    rdep -> new DepAndRdep(reverseDepsEntry.getKey(), rdep))));

    return new Visit(/*keysToUseForResult=*/ uniqueValidRdeps,
            /*keysToVisit=*/ depAndRdepsToVisitBuilder.build());
}

From source file:com.linkedin.pinot.core.query.aggregation.function.quantile.digest.QuantileDigest.java

public String toGraphviz() {
    StringBuilder builder = new StringBuilder();

    builder.append("digraph QuantileDigest {\n").append("\tgraph [ordering=\"out\"];");

    final List<Node> nodes = new ArrayList<>();
    postOrderTraversal(root, new Callback() {
        @Override/* w  w w  . j av a  2 s . co m*/
        public boolean process(Node node) {
            nodes.add(node);
            return true;
        }
    });

    Multimap<Integer, Node> nodesByLevel = Multimaps.index(nodes, new Function<Node, Integer>() {
        @Override
        public Integer apply(Node input) {
            return input.level;
        }
    });

    for (Map.Entry<Integer, Collection<Node>> entry : nodesByLevel.asMap().entrySet()) {
        builder.append("\tsubgraph level_" + entry.getKey() + " {\n").append("\t\trank = same;\n");

        for (Node node : entry.getValue()) {
            builder.append(
                    String.format("\t\t%s [label=\"[%s..%s]@%s\\n%s\", shape=rect, style=filled,color=%s];\n",
                            idFor(node), node.getLowerBound(), node.getUpperBound(), node.level,
                            node.weightedCount, node.weightedCount > 0 ? "salmon2" : "white"));
        }

        builder.append("\t}\n");
    }

    for (Node node : nodes) {
        if (node.left != null) {
            builder.append(format("\t%s -> %s;\n", idFor(node), idFor(node.left)));
        }
        if (node.right != null) {
            builder.append(format("\t%s -> %s;\n", idFor(node), idFor(node.right)));
        }
    }

    builder.append("}\n");

    return builder.toString();
}

From source file:com.google.devtools.kythe.extractors.java.JavaCompilationUnitExtractor.java

/**
 * If the code has wildcard imports (e.g. import foo.bar.*) but doesn't
 * actually use any of the imports, errors will happen.
 * We don't get callbacks for file open of these files (since they aren't used)
 * but when java runs it will report errors if it can't find any files to match
 * the wildcard.  So we add one matching file here.
 *//*from ww  w  .j  a  va 2s. co  m*/
private void findOnDemandImportedFiles(Iterable<? extends CompilationUnitTree> compilationUnits,
        UsageAsInputReportingFileManager fileManager) throws ExtractionException {
    // Maps package names to source files that wildcard import them.
    Multimap<String, String> pkgs = HashMultimap.create();

    // Javac synthesizes an "import java.lang.*" for every compilation unit.
    pkgs.put("java.lang", "*.java");

    for (CompilationUnitTree unit : compilationUnits) {
        for (ImportTree importTree : unit.getImports()) {
            if (importTree.isStatic()) {
                continue;
            }
            String qualifiedIdentifier = importTree.getQualifiedIdentifier().toString();
            if (!qualifiedIdentifier.endsWith(".*")) {
                continue;
            }
            pkgs.put(qualifiedIdentifier.substring(0, qualifiedIdentifier.length() - 2),
                    unit.getSourceFile().getName());
        }
    }

    for (Map.Entry<String, Collection<String>> pkg : pkgs.asMap().entrySet()) {
        try {
            JavaFileObject firstClass = Iterables.getFirst(fileManager.list(StandardLocation.CLASS_PATH,
                    pkg.getKey(), Sets.newHashSet(Kind.CLASS), false), null);
            if (firstClass == null) {
                firstClass = Iterables.getFirst(fileManager.list(StandardLocation.PLATFORM_CLASS_PATH,
                        pkg.getKey(), Sets.newHashSet(Kind.CLASS), false), null);
            }
            if (firstClass != null) {
                firstClass.getCharContent(true);
            }
            JavaFileObject firstSource = Iterables.getFirst(fileManager.list(StandardLocation.SOURCE_PATH,
                    pkg.getKey(), Sets.newHashSet(Kind.SOURCE), false), null);
            if (firstSource != null) {
                firstSource.getCharContent(true);
            }
        } catch (IOException e) {
            throw new ExtractionException(
                    String.format("Unable to extract files used for on demand imports in {%s}",
                            Joiner.on(", ").join(pkg.getValue())),
                    e, false);
        }
    }
}

From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.GenericLogicDiscoverer.java

/**
 * Generic implementation for finding all the Services or Operations that have SOME of the given types as inputs or outputs.
 *
 * @param entityType   the MSM URI of the type of entity we are looking for. Only supports Service and Operation.
 * @param relationship the MSM URI of the relationship we are looking for. Only supports hasInput and hasOutput.
 * @param types        the input/output types (modelReferences that is) we are looking for
 * @return a Map mapping operation/services URIs to MatchResults.
 *///  w w  w .  j a va 2 s  .  co  m
private Map<URI, MatchResult> findSome(URI entityType, URI relationship, Set<URI> types) {

    // Ensure that we have been given correct parameters
    if (types == null || types.isEmpty()
            || (!entityType.toASCIIString().equals(MSM.Service.getURI())
                    && !entityType.toASCIIString().equals(MSM.Operation.getURI()))
            || (!relationship.toASCIIString().equals(MSM.hasInput.getURI())
                    && !entityType.toASCIIString().equals(MSM.hasOutput.getURI())
                    && !relationship.toASCIIString().equals(SAWSDL.modelReference.getURI()))) {

        return ImmutableMap.of();
    }

    // Expand the input types to get all that match enough to be consumed
    // TODO: The leastOfType should be configurable
    Table<URI, URI, MatchResult> expandedTypes;
    if (relationship.toASCIIString().equals(SAWSDL.modelReference.getURI())) {
        expandedTypes = HashBasedTable.create();
        //TODO: fix this properly
        for (URI type : types) {
            expandedTypes.putAll(this.conceptMatcher.listMatchesAtMostOfType(ImmutableSet.of(type),
                    LogicConceptMatchType.Subsume));
            expandedTypes.putAll(
                    this.conceptMatcher.listMatchesOfType(ImmutableSet.of(type), LogicConceptMatchType.Exact));
        }

    } else {
        expandedTypes = this.conceptMatcher.listMatchesAtLeastOfType(types, LogicConceptMatchType.Plugin);
    }

    // Track all the results in a multimap to push the details up the stack
    Multimap<URI, MatchResult> result = ArrayListMultimap.create();

    // Find all the entities with modelReferences to the expanded types
    // The column view is the one with all the possible matches since a class will always match itself
    Map<URI, Map<URI, MatchResult>> columnMap = expandedTypes.columnMap();
    for (URI type : columnMap.keySet()) {
        Set<URI> entities = ImmutableSet.of();
        if (relationship.toASCIIString().equals(SAWSDL.modelReference.getURI())) {
            entities = listEntitesWithModelReference(entityType, type);
        } else if (relationship.toASCIIString().equals(MSM.hasInput.getURI())
                || relationship.toASCIIString().equals(MSM.hasOutput.getURI())) {
            entities = listEntitiesWithType(entityType, relationship, type);
        }

        for (URI entity : entities) {
            result.putAll(entity, columnMap.get(type).values());
        }
    }

    // Merge the results into a single map using Union
    return Maps.transformValues(result.asMap(), MatchResultsMerger.UNION);

}

From source file:com.google.devtools.build.lib.query2.RdepsBoundedVisitor.java

@Override
protected Visit getVisitResult(Iterable<DepAndRdepAtDepth> depAndRdepAtDepths) throws InterruptedException {
    Map<SkyKey, Integer> shallowestRdepDepthMap = new HashMap<>();
    depAndRdepAtDepths.forEach(depAndRdepAtDepth -> shallowestRdepDepthMap
            .merge(depAndRdepAtDepth.depAndRdep.rdep, depAndRdepAtDepth.rdepDepth, Integer::min));

    Collection<SkyKey> validRdeps = new ArrayList<>();

    // Multimap of dep to all the reverse deps in this visitation. Used to filter out the
    // disallowed deps.
    Multimap<SkyKey, SkyKey> reverseDepMultimap = ArrayListMultimap.create();
    for (DepAndRdepAtDepth depAndRdepAtDepth : depAndRdepAtDepths) {
        // The "roots" of our visitation (see #preprocessInitialVisit) have a null 'dep' field.
        if (depAndRdepAtDepth.depAndRdep.dep == null) {
            validRdeps.add(depAndRdepAtDepth.depAndRdep.rdep);
        } else {//from w  w  w.ja  v a 2  s . com
            reverseDepMultimap.put(depAndRdepAtDepth.depAndRdep.dep, depAndRdepAtDepth.depAndRdep.rdep);
        }
    }

    Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap = env
            .makePackageKeyToTargetKeyMap(Iterables.concat(reverseDepMultimap.values()));
    Set<PackageIdentifier> pkgIdsNeededForTargetification = packageKeyToTargetKeyMap.keySet().stream()
            .map(SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER).collect(toImmutableSet());
    packageSemaphore.acquireAll(pkgIdsNeededForTargetification);

    try {
        // Filter out disallowed deps. We cannot defer the targetification any further as we do not
        // want to retrieve the rdeps of unwanted nodes (targets).
        if (!reverseDepMultimap.isEmpty()) {
            Collection<Target> filteredTargets = env.filterRawReverseDepsOfTransitiveTraversalKeys(
                    reverseDepMultimap.asMap(), packageKeyToTargetKeyMap);
            filteredTargets.stream().map(SkyQueryEnvironment.TARGET_TO_SKY_KEY).forEachOrdered(validRdeps::add);
        }
    } finally {
        packageSemaphore.releaseAll(pkgIdsNeededForTargetification);
    }

    ImmutableList<SkyKey> uniqueValidRdeps = validRdeps.stream().filter(validRdep -> validRdepMinDepthUniquifier
            .uniqueAtDepthLessThanOrEqualTo(validRdep, shallowestRdepDepthMap.get(validRdep)))
            .collect(ImmutableList.toImmutableList());

    // Don't bother getting the rdeps of the rdeps that are already at the depth bound.
    Iterable<SkyKey> uniqueValidRdepsBelowDepthBound = Iterables.filter(uniqueValidRdeps,
            uniqueValidRdep -> shallowestRdepDepthMap.get(uniqueValidRdep) < depth);

    // Retrieve the reverse deps as SkyKeys and defer the targetification and filtering to next
    // recursive visitation.
    Map<SkyKey, Iterable<SkyKey>> unfilteredRdepsOfRdeps = env.graph
            .getReverseDeps(uniqueValidRdepsBelowDepthBound);

    ImmutableList.Builder<DepAndRdepAtDepth> depAndRdepAtDepthsToVisitBuilder = ImmutableList.builder();
    unfilteredRdepsOfRdeps.entrySet().forEach(entry -> {
        SkyKey rdep = entry.getKey();
        int depthOfRdepOfRdep = shallowestRdepDepthMap.get(rdep) + 1;
        Streams.stream(entry.getValue()).filter(Predicates.and(SkyQueryEnvironment.IS_TTV, universe))
                .forEachOrdered(rdepOfRdep -> {
                    depAndRdepAtDepthsToVisitBuilder
                            .add(new DepAndRdepAtDepth(new DepAndRdep(rdep, rdepOfRdep), depthOfRdepOfRdep));
                });
    });

    return new Visit(/*keysToUseForResult=*/ uniqueValidRdeps,
            /*keysToVisit=*/ depAndRdepAtDepthsToVisitBuilder.build());
}

From source file:org.vclipse.bapi.actions.BAPIUtils.java

protected MultipleLanguageDocumentation readMultiLanguageDocumentations(JCoTable table) {
    if (table.isEmpty())
        return null;
    Multimap<Language, Integer> language2Rows = ArrayListMultimap.create();
    for (int i = 0; i < table.getNumRows(); i++) {
        table.setRow(i);//from  w  w w  . j a  v  a 2 s. c o m
        Language language;
        String languageISO = table.getString("LANGUAGE_ISO");
        if (Strings.isEmpty(languageISO)) {
            language = VcmlUtils.getLanguageByCharacter(table.getChar("LANGUAGE"));
        } else {
            language = VcmlUtils.getLanguageByISOString(languageISO);
        }
        language2Rows.put(language, i);
    }

    MultipleLanguageDocumentation multipleLanguageDocumentation = VCML.createMultipleLanguageDocumentation();
    EList<MultipleLanguageDocumentation_LanguageBlock> languageBlocks = multipleLanguageDocumentation
            .getLanguageblocks();
    for (java.util.Map.Entry<Language, Collection<Integer>> entry : language2Rows.asMap().entrySet()) {
        MultipleLanguageDocumentation_LanguageBlock languageBlock = VCML
                .createMultipleLanguageDocumentation_LanguageBlock();
        languageBlocks.add(languageBlock);
        languageBlock.setLanguage(entry.getKey());
        EList<FormattedDocumentationBlock> formattedDocumentationBlocks = languageBlock
                .getFormattedDocumentationBlocks();
        Collection<Integer> indices = entry.getValue();
        for (int i : indices) {
            table.setRow(i);
            FormattedDocumentationBlock fdb = VCML.createFormattedDocumentationBlock();
            formattedDocumentationBlocks.add(fdb);
            fdb.setFormat(table.getString("TXT_FORM"));
            fdb.setValue(table.getString("TXT_LINE"));
        }
    }
    return multipleLanguageDocumentation;
}

From source file:grakn.core.graql.reasoner.atom.binary.RelationAtom.java

@Override
public Stream<ConceptMap> materialise() {
    RelationType relationType = getSchemaConcept().asRelationType();
    Multimap<Role, Variable> roleVarMap = getRoleVarMap();
    ConceptMap substitution = getParentQuery().getSubstitution();

    //NB: if the relation is implicit, it will created as a reified relation

    //if the relation already exists, only assign roleplayers, otherwise create a new relation
    Relation relation = substitution.containsVar(getVarName()) ? substitution.get(getVarName()).asRelation()
            : RelationTypeImpl.from(relationType).addRelationInferred();

    roleVarMap.asMap().forEach(
            (key, value) -> value.forEach(var -> relation.assign(key, substitution.get(var).asThing())));

    ConceptMap relationSub = ConceptUtils.mergeAnswers(getRoleSubstitution(),
            getVarName().isReturned() ? new ConceptMap(ImmutableMap.of(getVarName(), relation))
                    : new ConceptMap());

    ConceptMap answer = ConceptUtils.mergeAnswers(substitution, relationSub);
    return Stream.of(answer);
}