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:org.apache.beam.sdk.util.IOChannelUtils.java

@VisibleForTesting
static void checkDuplicateScheme(Set<IOChannelFactoryRegistrar> registrars) {
    Multimap<String, IOChannelFactoryRegistrar> registrarsBySchemes = TreeMultimap
            .create(Ordering.<String>natural(), Ordering.arbitrary());

    for (IOChannelFactoryRegistrar registrar : registrars) {
        registrarsBySchemes.put(registrar.getScheme(), registrar);
    }/*from  w w w.  j  ava2s.  c o  m*/
    for (Entry<String, Collection<IOChannelFactoryRegistrar>> entry : registrarsBySchemes.asMap().entrySet()) {
        if (entry.getValue().size() > 1) {
            String conflictingRegistrars = Joiner.on(", ").join(FluentIterable.from(entry.getValue())
                    .transform(new Function<IOChannelFactoryRegistrar, String>() {
                        @Override
                        public String apply(@Nonnull IOChannelFactoryRegistrar input) {
                            return input.getClass().getName();
                        }
                    }).toSortedList(Ordering.<String>natural()));
            throw new IllegalStateException(String.format("Scheme: [%s] has conflicting registrars: [%s]",
                    entry.getKey(), conflictingRegistrars));
        }
    }
}

From source file:org.opendaylight.mdsal.dom.broker.ProducerLayout.java

private static BiMap<DOMDataTreeIdentifier, DOMDataTreeShardProducer> mapIdsToProducer(
        final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap) {
    final Multimap<DOMDataTreeShard, DOMDataTreeIdentifier> shardToId = ArrayListMultimap.create();
    // map which identifier belongs to which shard
    for (final Entry<DOMDataTreeIdentifier, DOMDataTreeShard> entry : shardMap.entrySet()) {
        shardToId.put(entry.getValue(), entry.getKey());
    }/*from w  ww . ja  v  a  2 s  .  c  o  m*/

    final Builder<DOMDataTreeIdentifier, DOMDataTreeShardProducer> idToProducerBuilder = ImmutableBiMap
            .builder();
    for (final Entry<DOMDataTreeShard, Collection<DOMDataTreeIdentifier>> entry : shardToId.asMap()
            .entrySet()) {
        if (entry.getKey() instanceof WriteableDOMDataTreeShard) {
            //create a single producer for all prefixes in a single shard
            final DOMDataTreeShardProducer producer = ((WriteableDOMDataTreeShard) entry.getKey())
                    .createProducer(entry.getValue());
            // id mapped to producers
            for (final DOMDataTreeIdentifier id : entry.getValue()) {
                idToProducerBuilder.put(id, producer);
            }
        } else {
            LOG.error("Unable to create a producer for shard that's not a WriteableDOMDataTreeShard");
        }
    }

    return idToProducerBuilder.build();
}

From source file:eu.itesla_project.modules.simulation.ImpactAnalysisTool.java

private static void prettyPrint(Multimap<String, SecurityIndex> securityIndexesPerContingency) {
    Table table = new Table(1 + SecurityIndexType.values().length, BorderStyle.CLASSIC_WIDE);
    table.addCell("Contingency");
    for (SecurityIndexType securityIndexType : SecurityIndexType.values()) {
        table.addCell(securityIndexType.toString());
    }/*from  w  w w .j  av a  2s.  co  m*/

    for (Map.Entry<String, Collection<SecurityIndex>> entry : securityIndexesPerContingency.asMap()
            .entrySet()) {
        String contingencyId = entry.getKey();
        table.addCell(contingencyId);
        for (String str : toRow(entry.getValue())) {
            table.addCell(str);
        }
    }

    System.out.println(table.render());
}

From source file:org.apache.brooklyn.core.typereg.TypePlanTransformers.java

/** returns a list of {@link BrooklynTypePlanTransformer} instances for this {@link ManagementContext}
 * which may be able to handle the given plan; the list is sorted with highest-score transformer first */
@Beta/*w w  w . j a  va  2  s . c o  m*/
public static List<BrooklynTypePlanTransformer> forType(ManagementContext mgmt, RegisteredType type,
        RegisteredTypeLoadingContext constraint) {
    Multimap<Double, BrooklynTypePlanTransformer> byScoreMulti = ArrayListMultimap.create();
    Collection<BrooklynTypePlanTransformer> transformers = all(mgmt);
    for (BrooklynTypePlanTransformer transformer : transformers) {
        double score = transformer.scoreForType(type, constraint);
        if (score > 0)
            byScoreMulti.put(score, transformer);
    }
    Map<Double, Collection<BrooklynTypePlanTransformer>> tree = new TreeMap<Double, Collection<BrooklynTypePlanTransformer>>(
            byScoreMulti.asMap());
    List<Collection<BrooklynTypePlanTransformer>> highestFirst = new ArrayList<Collection<BrooklynTypePlanTransformer>>(
            tree.values());
    Collections.reverse(highestFirst);
    return ImmutableList.copyOf(Iterables.concat(highestFirst));
}

From source file:de.dennishoersch.web.css.parser.Parser.java

private static List<Style> parseStyles(String styles) {
    Multimap<String, Style> reduced = LinkedHashMultimap.create();
    for (String style_ : _STYLE_SPLITTER.split(styles)) {
        Style style = new Style(style_);
        reduced.put(style.getName(), style);
    }/*from ww  w.jav a  2 s. co  m*/

    // Wenn keiner der Werte zu einem Style ein Vendor-Prefix enthlt, dann
    // kann der letzte alle anderen berschreiben
    List<Style> result = Lists.newArrayList();
    for (Map.Entry<String, Collection<Style>> entry : reduced.asMap().entrySet()) {
        Collection<Style> values = entry.getValue();
        if (Iterables.any(values, HasVendorPrefixValue.INSTANCE)) {
            result.addAll(values);
        } else {
            result.add(Iterables.getLast(values));
        }
    }
    return result;
}

From source file:org.apache.hadoop.hbase.snapshot.TakeSnapshotUtils.java

/**
 * Verify that all the expected logs got referenced
 * @param fs filesystem where the logs live
 * @param logsDir original logs directory
 * @param serverNames names of the servers that involved in the snapshot
 * @param snapshot description of the snapshot being taken
 * @param snapshotLogDir directory for logs in the snapshot
 * @throws IOException/*from ww w.  ja  v  a2s . c  om*/
 */
public static void verifyAllLogsGotReferenced(FileSystem fs, Path logsDir, Set<String> serverNames,
        SnapshotDescription snapshot, Path snapshotLogDir) throws IOException {
    assertTrue(snapshot, "Logs directory doesn't exist in snapshot", fs.exists(logsDir));
    // for each of the server log dirs, make sure it matches the main directory
    Multimap<String, String> snapshotLogs = getMapOfServersAndLogs(fs, snapshotLogDir, serverNames);
    Multimap<String, String> realLogs = getMapOfServersAndLogs(fs, logsDir, serverNames);
    if (realLogs != null) {
        assertNotNull(snapshot, "No server logs added to snapshot", snapshotLogs);
    } else {
        assertNull(snapshot, "Snapshotted server logs that don't exist", snapshotLogs);
    }

    // check the number of servers
    Set<Entry<String, Collection<String>>> serverEntries = realLogs.asMap().entrySet();
    Set<Entry<String, Collection<String>>> snapshotEntries = snapshotLogs.asMap().entrySet();
    assertEquals(snapshot, "Not the same number of snapshot and original server logs directories",
            serverEntries.size(), snapshotEntries.size());

    // verify we snapshotted each of the log files
    for (Entry<String, Collection<String>> serverLogs : serverEntries) {
        // if the server is not the snapshot, skip checking its logs
        if (!serverNames.contains(serverLogs.getKey()))
            continue;
        Collection<String> snapshotServerLogs = snapshotLogs.get(serverLogs.getKey());
        assertNotNull(snapshot, "Snapshots missing logs for server:" + serverLogs.getKey(), snapshotServerLogs);

        // check each of the log files
        assertEquals(snapshot, "Didn't reference all the log files for server:" + serverLogs.getKey(),
                serverLogs.getValue().size(), snapshotServerLogs.size());
        for (String log : serverLogs.getValue()) {
            assertTrue(snapshot, "Snapshot logs didn't include " + log, snapshotServerLogs.contains(log));
        }
    }
}

From source file:org.gradle.model.internal.manage.binding.DefaultStructBindingsStore.java

private static boolean isManagedProperty(StructBindingExtractionContext<?> extractionContext,
        String propertyName, Multimap<PropertyAccessorType, StructMethodBinding> accessorBindings) {
    Boolean managed = null;/*w w  w  .j  av  a  2s . c  o  m*/
    for (Map.Entry<PropertyAccessorType, Collection<StructMethodBinding>> accessorEntry : accessorBindings
            .asMap().entrySet()) {
        Collection<StructMethodBinding> bindings = accessorEntry.getValue();
        boolean managedPropertyAccessor = isManagedPropertyAccessor(extractionContext, propertyName, bindings);
        if (managed == null) {
            managed = managedPropertyAccessor;
        } else if (managed != managedPropertyAccessor) {
            extractionContext.add(propertyName,
                    "it must have either only abstract accessor methods or only implemented accessor methods");
            managed = false;
            break;
        }
    }
    assert managed != null;
    return managed;
}

From source file:uk.ac.ebi.intact.dataexchange.cvutils.CvUtils.java

/**
 * Returns the id of the parent which is common to the children provided. If none is found, it returns null.
 *
 * @param children A CvTerms with a common parent
 * @return the common parent for the children
 *///from   www.j av  a2s .  c  om
public static CvDagObject findLowestCommonAncestor(CvDagObject... children) {
    if (children.length < 2) {
        throw new IllegalArgumentException("At least two children have to be provided to find a common parent");
    }

    Multimap<String, String> cvMap = LinkedHashMultimap.create();

    // get all the parents for each child
    for (CvDagObject child : children) {
        cvMap.put(child.getIdentifier(), child.getIdentifier());
        cvMap.putAll(child.getIdentifier(), findAllParentsForTerm(child));
    }

    // calculate the common parents by interesecting all the collections of parents for each child
    List<String> commonParents = null;

    for (Collection<String> parents : cvMap.asMap().values()) {
        List<String> parentsList = new LinkedList<String>(parents);
        if (commonParents == null) {
            commonParents = parentsList;
        } else {
            commonParents = ListUtils.intersection(commonParents, parentsList);
        }

    }

    // the first child of the commonParents collection is the lowest common ancestor
    if (!commonParents.isEmpty()) {
        String parentId = commonParents.iterator().next();
        return findParentById(children[0], parentId);
    }

    return null;
}

From source file:grakn.core.graql.gremlin.RelationTypeInference.java

public static Set<Fragment> inferRelationTypes(TransactionOLTP tx, Set<Fragment> allFragments) {

    Set<Fragment> inferredFragments = new HashSet<>();

    Map<Variable, Type> labelVarTypeMap = getLabelVarTypeMap(tx, allFragments);
    if (labelVarTypeMap.isEmpty())
        return inferredFragments;

    Multimap<Variable, Type> instanceVarTypeMap = getInstanceVarTypeMap(allFragments, labelVarTypeMap);

    Multimap<Variable, Variable> relationRolePlayerMap = getRelationRolePlayerMap(allFragments,
            instanceVarTypeMap);/*www.  j a  v a2s .  c o  m*/
    if (relationRolePlayerMap.isEmpty())
        return inferredFragments;

    // for each type, get all possible relation type it could be in
    Multimap<Type, RelationType> relationMap = HashMultimap.create();
    labelVarTypeMap.values().stream().distinct().forEach(type -> addAllPossibleRelations(relationMap, type));

    // inferred labels should be kept separately, even if they are already in allFragments set
    Map<Label, Statement> inferredLabels = new HashMap<>();
    relationRolePlayerMap.asMap().forEach((relationVar, rolePlayerVars) -> {

        Set<Type> possibleRelationTypes = rolePlayerVars.stream().filter(instanceVarTypeMap::containsKey)
                .map(rolePlayer -> getAllPossibleRelationTypes(instanceVarTypeMap.get(rolePlayer), relationMap))
                .reduce(Sets::intersection).orElse(Collections.emptySet());

        //TODO: if possibleRelationTypes here is empty, the query will not match any data
        if (possibleRelationTypes.size() == 1) {

            Type relationType = possibleRelationTypes.iterator().next();
            Label label = relationType.label();

            // add label fragment if this label has not been inferred
            if (!inferredLabels.containsKey(label)) {
                Statement labelVar = var();
                inferredLabels.put(label, labelVar);
                Fragment labelFragment = Fragments.label(new TypeProperty(label.getValue()), labelVar.var(),
                        ImmutableSet.of(label));
                inferredFragments.add(labelFragment);
            }

            // finally, add inferred isa fragments
            Statement labelVar = inferredLabels.get(label);
            IsaProperty isaProperty = new IsaProperty(labelVar);
            EquivalentFragmentSet isaEquivalentFragmentSet = EquivalentFragmentSets.isa(isaProperty,
                    relationVar, labelVar.var(), relationType.isImplicit());
            inferredFragments.addAll(isaEquivalentFragmentSet.fragments());
        }
    });

    return inferredFragments;
}

From source file:org.ambraproject.wombat.freemarker.ReplaceParametersDirective.java

@VisibleForTesting
static Multimap<String, String> replaceParameters(SimpleHash parameterMap,
        Multimap<String, TemplateModel> replacements) throws TemplateException {
    Multimap<String, String> result = HashMultimap.create();

    // The map is passed in as a Map<String, String[]>, but Freemarker doesn't support generics
    // (and wraps the map in its own data structure).
    Map map = parameterMap.toMap();
    Iterator iter = map.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        String[] values = (String[]) entry.getValue();
        for (String value : values) {
            result.put((String) entry.getKey(), value);
        }/*from  www . j  av a 2 s.com*/
    }

    for (Map.Entry<String, Collection<TemplateModel>> replacementEntry : replacements.asMap().entrySet()) {
        Collection<String> replacementValues = Collections2.transform(replacementEntry.getValue(),
                Object::toString);
        result.replaceValues(replacementEntry.getKey(), replacementValues);
    }

    return ImmutableSetMultimap.copyOf(result);
}