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

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

Introduction

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

Prototype

Collection<Map.Entry<K, V>> entries();

Source Link

Document

Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances.

Usage

From source file:com.google.enterprise.adaptor.sharepoint.HtmlResponseWriter.java

public void addMetadata(Multimap<String, String> metadata) throws IOException {
    checkAndCloseSection();/*  w ww .  ja v a 2  s .  c o  m*/
    googleoffIndex();
    writer.write("<table style='border: none'>");
    for (Map.Entry<String, String> me : metadata.entries()) {
        writer.write("<tr><td>");
        writer.write(escapeContent(me.getKey()));
        writer.write("</td><td>");
        writer.write(escapeContent(me.getValue()));
        writer.write("</td></tr>");
    }
    writer.write("</table>");
    googleonIndex();
    state = State.STARTED;
}

From source file:com.github.haixing_hu.lang.Assignment.java

/**
 * Deeply clones a multi-map.//  w  w  w. j a v  a2s  .  co m
 *
 * @param <K>
 *          The type of the key of the multi-map to be cloned.
 * @param <V>
 *          The type of the value of the multi-map to be cloned.
 * @param map
 *          The source multi-map to be cloned, which could be null.
 * @return The cloned copy of the source multi-map; or null if the source
 *         multi-map is null. Note that the values in the source multi-map is
 *         also cloned into the returned multi-map, thus this is a deep clone.
 */
@SuppressWarnings("unchecked")
public static <K, V extends Cloneable<? super V>> Multimap<K, V> deepClone(@Nullable final Multimap<K, V> map) {
    if (map == null) {
        return null;
    } else {
        final Multimap<K, V> result = LinkedHashMultimap.create();
        final Collection<Map.Entry<K, V>> entries = map.entries();
        for (final Map.Entry<K, V> entry : entries) {
            final K key = entry.getKey();
            final V value = entry.getValue();
            if (value == null) {
                result.put(key, null);
            } else {
                result.put(key, (V) value.clone());
            }
        }
        return result;
    }
}

From source file:com.wolvereness.overmapped.OverMapped.java

private Multimap<String, String> processReverseDepends(final Multimap<String, String> dependencies) {
    final HashMultimap<String, String> rdepends = HashMultimap.create();
    for (final Map.Entry<String, String> dependency : dependencies.entries()) {
        rdepends.put(dependency.getValue(), dependency.getKey());
    }//ww  w. ja  v a2s.  c o  m
    return rdepends;
}

From source file:com.google.eclipse.protobuf.validation.ProtobufJavaValidator.java

private void errorOnConflicts(Range<Long> range, Multimap<EObject, Range<Long>> rangeUsages,
        EObject errorSource, EStructuralFeature errorFeature) {
    for (Map.Entry<EObject, Range<Long>> rangeUsage : rangeUsages.entries()) {
        Range<Long> usedRange = rangeUsage.getValue();
        if (range.isConnected(usedRange)) {
            EObject rangeUser = rangeUsage.getKey();

            boolean rangeIsSingular = range.hasUpperBound() && range.upperEndpoint() == range.lowerEndpoint();
            String template = rangeIsSingular ? tagNumberConflict : tagNumberRangeConflict;

            String rangeUserString;
            String usedRangeString = rangeToString(usedRange);
            if (rangeUser instanceof MessageField) {
                rangeUserString = String.format(conflictingField, nameResolver.nameOf(rangeUser),
                        usedRangeString);
            } else if (rangeUser instanceof Group) {
                rangeUserString = String.format(conflictingGroup, nameResolver.nameOf(rangeUser),
                        usedRangeString);
            } else if (rangeUser instanceof Reserved) {
                rangeUserString = String.format(conflictingReservedNumber, usedRangeString);
            } else {
                rangeUserString = String.format(conflictingExtensions, usedRangeString);
            }//from w ww  . j a v a 2  s .  com

            String message = String.format(template, rangeToString(range), rangeUserString);
            error(message, errorSource, errorFeature);

            // Don't report more than one error per element.
            return;
        }
    }
}

From source file:cosmos.records.impl.MultimapRecord.java

public <T1, T2> MultimapRecord(Multimap<T1, T2> untypedDoc, String docId, ColumnVisibility docVisibility,
        RecordFunction<T1, T2> function) {
    checkNotNull(untypedDoc);/*  w  w w .j  a  va 2 s  .c  o m*/
    checkNotNull(docId);
    checkNotNull(docVisibility);
    checkNotNull(function);

    this.docId = docId;
    this.docVisibility = docVisibility;
    this.document = HashMultimap.create();

    for (Entry<T1, T2> untypedEntry : untypedDoc.entries()) {
        Entry<Column, RecordValue<?>> entry = function.apply(untypedEntry);
        this.document.put(entry.getKey(), entry.getValue());
    }
}

From source file:org.lealone.cluster.dht.RangeStreamer.java

/**
 * Add ranges to be streamed for given database.
 *
 * @param db database to be streamed/*from  ww  w.ja v a2 s .  co  m*/
 * @param ranges ranges to be streamed
 */
public void addRanges(Database db, Collection<Range<Token>> ranges) {
    Multimap<Range<Token>, InetAddress> rangesWithSources = useStrictSourcesForRanges(db) ? //
            getAllRangesWithStrictSourcesFor(db, ranges) : getAllRangesWithSourcesFor(db, ranges);

    if (logger.isDebugEnabled()) {
        for (Map.Entry<Range<Token>, InetAddress> entry : rangesWithSources.entries())
            logger.debug(
                    String.format("%s: range %s exists on %s", description, entry.getKey(), entry.getValue()));
    }

    String dbName = db.getName();
    for (Map.Entry<InetAddress, Collection<Range<Token>>> entry : getRangeFetchMap(rangesWithSources,
            sourceFilters, dbName).asMap().entrySet()) {
        if (logger.isDebugEnabled()) {
            for (Range<Token> r : entry.getValue())
                logger.debug(String.format("%s: range %s from source %s for database %s", description, r,
                        entry.getKey(), dbName));
        }
        toFetch.put(dbName, entry);
    }
}

From source file:fr.ens.biologie.genomique.eoulsan.core.workflow.MatchDataProduct.java

@Override
public Set<ImmutableMap<InputPort, Data>> makeProduct(final StepInputPorts inputPorts,
        final Multimap<InputPort, Data> inputTokens) {

    checkNotNull(inputPorts, "inputPorts argument cannot be null");
    checkNotNull(inputTokens, "inputTokens argument cannot be null");

    final Set<ImmutableMap<InputPort, Data>> result = new HashSet<>();
    final int portCount = inputPorts.size();

    final Map<String, Map<InputPort, Data>> map = new HashMap<>();

    // Put tokens data in a multimap
    for (Map.Entry<InputPort, Data> e : inputTokens.entries()) {

        final String dataName = e.getValue().getName();
        final Map<InputPort, Data> portDataMap;

        if (map.containsKey(dataName)) {
            portDataMap = map.get(dataName);
        } else {/*  w  ww  .ja  v a2 s. c om*/
            portDataMap = new HashMap<>();
            map.put(dataName, portDataMap);
        }

        portDataMap.put(e.getKey(), e.getValue());
    }

    // Create the result object
    for (Map.Entry<String, Map<InputPort, Data>> e : map.entrySet()) {

        final Map<InputPort, Data> portDataMap = e.getValue();

        // Do not handle case where data for ports are missing
        if (portDataMap.size() != portCount) {
            continue;
        }

        final ImmutableMap.Builder<InputPort, Data> imb = ImmutableMap.builder();

        for (Map.Entry<InputPort, Data> e2 : portDataMap.entrySet()) {
            imb.put(e2);
        }

        result.add(imb.build());
    }

    return result;
}

From source file:to.lean.tools.gmail.importer.gmail.Mailbox.java

private void syncLabels(Gmail gmailApi, BiMap<String, String> labelIdToNameMap,
        Multimap<LocalMessage, Message> localMessageToGmailMessages) throws IOException {
    BatchRequest relabelBatch = gmailApi.batch();
    for (Map.Entry<LocalMessage, Message> entry : localMessageToGmailMessages.entries()) {
        LocalMessage localMessage = entry.getKey();
        Message gmailMessage = entry.getValue();

        Set<String> gmailLabels = gmailMessage.getLabelIds() == null ? ImmutableSet.of()
                : gmailMessage.getLabelIds().stream().map(labelIdToNameMap::get).collect(Collectors.toSet());

        List<String> missingLabelIds = localMessage.getFolders().stream()
                .map(folder -> folder.equalsIgnoreCase("Inbox") ? "INBOX" : folder)
                .filter(folder -> !gmailLabels.contains(folder))
                .map(folder -> labelIdToNameMap.inverse().get(folder)).collect(Collectors.toList());

        if (localMessage.isUnread() && !gmailLabels.contains("UNREAD")) {
            missingLabelIds.add("UNREAD");
        }/*from  ww  w  . j a v a 2s .c  o  m*/
        if (localMessage.isStarred() && !gmailLabels.contains("STARRED")) {
            missingLabelIds.add("STARRED");
        }

        for (String folder : localMessage.getFolders()) {
            if (!gmailLabels.contains(folder)) {
                System.out.format("Trying to add labels %s to %s\n",
                        missingLabelIds.stream().map(labelIdToNameMap::get).collect(Collectors.joining(", ")),
                        gmailMessage.getId());
                gmailApi.users().messages()
                        .modify(user.getEmailAddress(), gmailMessage.getId(),
                                new ModifyMessageRequest().setAddLabelIds(missingLabelIds))
                        .queue(relabelBatch, new JsonBatchCallback<Message>() {
                            @Override
                            public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders)
                                    throws IOException {
                                System.err.format("For label ids %s, got error: %s\n", missingLabelIds,
                                        e.toPrettyString());
                            }

                            @Override
                            public void onSuccess(Message message, HttpHeaders responseHeaders)
                                    throws IOException {
                                System.out.format(
                                        "Successfully added labels %s to %s\n", missingLabelIds.stream()
                                                .map(labelIdToNameMap::get).collect(Collectors.joining(", ")),
                                        message.getId());
                            }
                        });
            }
        }
        if (relabelBatch.size() > 0) {
            relabelBatch.execute();
        }
    }
}

From source file:eu.esdihumboldt.cst.functions.core.join.IndexJoinIterator.java

/**
 * Joins all direct children of the given type to currentInstances.
 *//*from ww w  .  ja  va 2s. c  om*/
@SuppressWarnings("javadoc")
private void join(FamilyInstance[] currentInstances, int currentType) {
    // Join all types that are direct children of the last type.
    for (int i = currentType + 1; i < joinDefinition.directParent.length; i++) {
        if (joinDefinition.directParent[i] == currentType) {
            // Get join condition for the direct child type.
            Multimap<Integer, JoinCondition> joinConditions = joinDefinition.joinTable.get(i);

            // Collect intersection of conditions. null marks beginning
            // in contrast to an empty set.
            Set<ResolvableInstanceReference> possibleInstances = null;

            // ParentType -> JoinConditions
            for (Map.Entry<Integer, JoinCondition> joinCondition : joinConditions.entries()) {
                PropertyEntityDefinition baseProp = joinCondition.getValue().baseProperty;
                QName baseTypeName = baseProp.getType().getName();
                List<QName> basePropertyPath = baseProp.getPropertyPath().stream()
                        .map(pp -> pp.getChild().getName()).collect(Collectors.toList());

                PropertyEntityDefinition joinProp = joinCondition.getValue().joinProperty;
                QName joinTypeName = joinProp.getType().getName();
                List<QName> joinPropertyPath = joinProp.getPropertyPath().stream()
                        .map(pp -> pp.getChild().getName()).collect(Collectors.toList());

                List<IndexedPropertyValue> currentValues = index.getInstancePropertyValues(baseTypeName,
                        basePropertyPath, currentInstances[joinCondition.getKey()].getId());

                if (currentValues == null || currentValues.isEmpty()) {
                    possibleInstances = Collections.emptySet();
                    break;
                }

                HashSet<ResolvableInstanceReference> matches = new HashSet<ResolvableInstanceReference>();
                for (IndexedPropertyValue currentValue : currentValues) {
                    if (currentValue.getValues() == null || currentValue.getValues().isEmpty()) {
                        continue;
                    }

                    // Find instances that have the current property value
                    Collection<ResolvableInstanceReference> instancesWithValues = index
                            .getInstancesByValue(joinTypeName, joinPropertyPath, currentValue.getValues());
                    matches.addAll(instancesWithValues);
                }

                if (possibleInstances == null) {
                    possibleInstances = matches;
                } else {
                    // Remove candidates that don't have the current
                    // property value
                    Iterator<ResolvableInstanceReference> it = possibleInstances.iterator();
                    while (it.hasNext()) {
                        ResolvableInstanceReference cand = it.next();
                        if (!matches.contains(cand)) {
                            it.remove();
                        }
                    }
                }

                if (possibleInstances.isEmpty()) {
                    break;
                }
            }

            if (possibleInstances != null && !possibleInstances.isEmpty()) {
                FamilyInstance parent = currentInstances[currentType];
                for (ResolvableInstanceReference ref : possibleInstances) {
                    FamilyInstance child;
                    child = new FamilyInstanceImpl(ref.resolve());
                    parent.addChild(child);
                    currentInstances[i] = child;
                    join(currentInstances, i);
                }
                currentInstances[i] = null;
            }
        }
    }
}

From source file:org.assertj.guava.api.MultimapAssert.java

/**
 * Verifies that the actual {@link Multimap} contains all entries of the given one (it might contain more entries).
 * <p>//from w w w  .  ja  v  a2s  .  c om
 * Example :
 *
 * <pre><code class='java'> Multimap&lt;String, String&gt; actual = ArrayListMultimap.create();
 * actual.putAll("Spurs", newArrayList("Tony Parker", "Tim Duncan", "Manu Ginobili"));
 * actual.putAll("Bulls", newArrayList("Michael Jordan", "Scottie Pippen", "Derrick Rose"));
 *
 * Multimap&lt;String, String&gt; other = TreeMultimap.create();
 * other.putAll("Spurs", newHashSet("Tony Parker", "Tim Duncan"));
 * other.putAll("Bulls", newHashSet("Michael Jordan", "Scottie Pippen"));
 *
 * // assertion will pass as other is a subset of actual.
 * assertThat(actual).containsAllEntriesOf(other);
 * 
 * // this assertion FAILS as other does not contain "Spurs -&gt; "Manu Ginobili" and "Bulls" -&gt; "Derrick Rose"
 * assertThat(other).containsAllEntriesOf(actual);</code></pre>
 *
 * @param other {@link Multimap} to compare actual's entries with.
 * @return this {@link MultimapAssert} for assertions chaining.
 * @throws AssertionError if the actual {@link Multimap} is {@code null}.
 * @throws IllegalArgumentException if the other {@link Multimap} is {@code null}.
 * @throws AssertionError if actual {@link Multimap} does not have contain all the given {@link Multimap} entries.
 */
public final MultimapAssert<K, V> containsAllEntriesOf(Multimap<? extends K, ? extends V> other) {
    Objects.instance().assertNotNull(info, actual);
    throwIllegalArgumentExceptionIfTrue(other == null,
            "The multimap to compare actual with should not be null");

    Set<?> entriesNotFoundInActual = difference(newLinkedHashSet(other.entries()),
            newLinkedHashSet(actual.entries()));
    if (entriesNotFoundInActual.isEmpty())
        return myself;
    throw failures.failure(info, shouldContain(actual, other, entriesNotFoundInActual));
}