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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this multimap contains no key-value pairs.

Usage

From source file:org.lanternpowered.server.scoreboard.LanternScore.java

@Override
public void setScore(int score) {
    if (this.score == score) {
        return;//from  w  w  w . j  a va2 s. c o m
    }
    this.score = score;
    final Multimap<Scoreboard, Objective> scoreboards = HashMultimap.create();
    for (Objective objective : this.objectives) {
        for (Scoreboard scoreboard : ((LanternObjective) objective).scoreboards) {
            scoreboards.put(scoreboard, objective);
        }
    }
    if (!scoreboards.isEmpty()) {
        final Map<Objective, Message> messages = new HashMap<>();
        for (Map.Entry<Scoreboard, Objective> entry : scoreboards.entries()) {
            ((LanternScoreboard) entry.getKey())
                    .sendToPlayers(() -> Collections.singletonList(messages.computeIfAbsent(entry.getValue(),
                            obj -> new MessagePlayOutScoreboardScore.CreateOrUpdate(obj.getName(),
                                    this.legacyName, score))));
        }
    }
}

From source file:eu.mondo.driver.fourstore.FourStoreGraphDriverReadWrite.java

@Override
public void insertEdges(final Multimap<String, String> edges, final String type) throws IOException {
    if (edges.isEmpty()) {
        return;// w  w  w .  j  a  va2 s.  c  om
    }

    final ArrayList<String> sourceVertices = new ArrayList<>(edges.keySet());
    final List<List<String>> sourceVerticesPartitions = Lists.partition(sourceVertices, PARTITION_SIZE);
    for (final List<String> sourceVerticesPartition : sourceVerticesPartitions) {

        final Multimap<String, String> edgePartition = ArrayListMultimap.create();
        for (final String sourceVertexURI : sourceVerticesPartition) {
            final Collection<String> targetVertexURIs = edges.get(sourceVertexURI);
            edgePartition.putAll(sourceVertexURI, targetVertexURIs);
        }

        insertEdgesPartition(edgePartition, type);
    }
}

From source file:fr.ujm.tse.lt2c.satin.rules.run.RunRHODF7b.java

@Override
protected int process(final TripleStore ts1, final TripleStore ts2, final Collection<Triple> outputTriples) {

    final long domain = AbstractDictionary.domain;
    final long range = AbstractDictionary.range;
    final long type = AbstractDictionary.type;
    final long subClassOf = AbstractDictionary.subClassOf;

    int loops = 0;

    final Multimap<Long, Long> domainMultiMap = ts2.getMultiMapForPredicate(domain);
    final Multimap<Long, Long> rangeMultiMap = ts2.getMultiMapForPredicate(range);
    final Multimap<Long, Long> typeMultiMap = ts2.getMultiMapForPredicate(type);
    if (domainMultiMap != null && !domainMultiMap.isEmpty()) {
        for (final Long o : domainMultiMap.values()) {
            loops++;/* w  ww . j av a  2  s.c  om*/
            final Triple result = new ImmutableTriple(o, subClassOf, o);
            outputTriples.add(result);
        }
    }
    if (rangeMultiMap != null && !rangeMultiMap.isEmpty()) {
        for (final Long o : rangeMultiMap.values()) {
            loops++;
            final Triple result = new ImmutableTriple(o, subClassOf, o);
            outputTriples.add(result);
        }
    }
    if (typeMultiMap != null && !typeMultiMap.isEmpty()) {
        for (final Long o : typeMultiMap.values()) {
            loops++;
            final Triple result = new ImmutableTriple(o, subClassOf, o);
            outputTriples.add(result);
        }
    }

    return loops;

}

From source file:org.apache.aurora.scheduler.preemptor.PendingTaskProcessor.java

@Timed("pending_task_processor_run")
@Override/*from w  w w . ja  va2s .c  o  m*/
public void run() {
    metrics.recordTaskProcessorRun();
    storage.read(store -> {
        Multimap<String, PreemptionVictim> slavesToActiveTasks = clusterState.getSlavesToActiveTasks();

        if (slavesToActiveTasks.isEmpty()) {
            // No preemption victims to consider.
            return null;
        }

        // Group the offers by slave id so they can be paired with active tasks from the same slave.
        Map<String, HostOffer> slavesToOffers = Maps.uniqueIndex(offerManager.getOffers(), OFFER_TO_SLAVE_ID);

        Set<String> allSlaves = Sets
                .newHashSet(Iterables.concat(slavesToOffers.keySet(), slavesToActiveTasks.keySet()));

        // The algorithm below attempts to find a reservation for every task group by matching
        // it against all available slaves until a preemption slot is found. Groups are evaluated
        // in a round-robin fashion to ensure fairness (e.g.: G1, G2, G3, G1, G2).
        // A slave is removed from further matching once a reservation is made. Similarly, all
        // identical task group instances are removed from further iteration if none of the
        // available slaves could yield a preemption proposal. A consuming iterator is used for
        // task groups to ensure iteration order is preserved after a task group is removed.
        LoadingCache<IJobKey, AttributeAggregate> jobStates = attributeCache(store);
        List<TaskGroupKey> pendingGroups = fetchIdlePendingGroups(store);
        Iterator<TaskGroupKey> groups = Iterators.consumingIterator(pendingGroups.iterator());
        TaskGroupKey lastGroup = null;
        Iterator<String> slaveIterator = allSlaves.iterator();

        while (!pendingGroups.isEmpty()) {
            boolean matched = false;
            TaskGroupKey group = groups.next();
            ITaskConfig task = group.getTask();

            metrics.recordPreemptionAttemptFor(task);
            // start over only if a different task group is being processed
            if (!group.equals(lastGroup)) {
                slaveIterator = allSlaves.iterator();
            }
            while (slaveIterator.hasNext()) {
                String slaveId = slaveIterator.next();
                Optional<ImmutableSet<PreemptionVictim>> candidates = preemptionVictimFilter
                        .filterPreemptionVictims(task, slavesToActiveTasks.get(slaveId),
                                jobStates.getUnchecked(task.getJob()),
                                Optional.fromNullable(slavesToOffers.get(slaveId)), store);

                metrics.recordSlotSearchResult(candidates, task);
                if (candidates.isPresent()) {
                    // Slot found -> remove slave to avoid multiple task reservations.
                    slaveIterator.remove();
                    slotCache.put(new PreemptionProposal(candidates.get(), slaveId), group);
                    matched = true;
                    break;
                }
            }
            if (!matched) {
                // No slot found for the group -> remove group and reset group iterator.
                pendingGroups.removeAll(ImmutableSet.of(group));
                groups = Iterators.consumingIterator(pendingGroups.iterator());
                metrics.recordUnmatchedTask();
            }
            lastGroup = group;
        }
        return null;
    });
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraVerifier.java

protected static void sanityCheckRingConsistency(Set<InetSocketAddress> currentAddrs, String keyspace,
        boolean isSsl, boolean safetyDisabled, int socketTimeoutMillis, int socketQueryTimeoutMillis) {
    Multimap<Set<TokenRange>, InetSocketAddress> tokenRangesToHost = HashMultimap.create();
    for (InetSocketAddress addr : currentAddrs) {
        Cassandra.Client client = null;/*from   ww w . j a v  a2  s .c  om*/
        try {
            client = CassandraClientFactory.getClientInternal(addr, isSsl, socketTimeoutMillis,
                    socketQueryTimeoutMillis);
            try {
                client.describe_keyspace(keyspace);
            } catch (NotFoundException e) {
                log.info(
                        "Tried to check ring consistency for node {} before keyspace was fully setup; aborting check for now.",
                        addr, e);
                return;
            }
            tokenRangesToHost.put(ImmutableSet.copyOf(client.describe_ring(keyspace)), addr);
        } catch (Exception e) {
            log.warn("failed to get ring info from host: {}", addr, e);
        } finally {
            if (client != null) {
                client.getOutputProtocol().getTransport().close();
            }
        }
    }

    if (tokenRangesToHost.isEmpty()) {
        log.error(
                "Failed to get ring info for entire Cassandra cluster ({}); ring could not be checked for consistency.",
                keyspace);
        return;
    }

    if (tokenRangesToHost.keySet().size() == 1) {
        return;
    }

    RuntimeException e = new IllegalStateException(
            "Hosts have differing ring descriptions.  This can lead to inconsistent reads and lost data. ");
    log.error("QA-86204 " + e.getMessage() + tokenRangesToHost, e);

    if (tokenRangesToHost.size() > 2) {
        for (Entry<Set<TokenRange>, Collection<InetSocketAddress>> entry : tokenRangesToHost.asMap()
                .entrySet()) {
            if (entry.getValue().size() == 1) {
                log.error("Host: " + entry.getValue().iterator().next()
                        + " disagrees with the other nodes about the ring state.");
            }
        }
    }

    if (tokenRangesToHost.keySet().size() == 2) {
        ImmutableList<Set<TokenRange>> sets = ImmutableList.copyOf(tokenRangesToHost.keySet());
        Set<TokenRange> set1 = sets.get(0);
        Set<TokenRange> set2 = sets.get(1);
        log.error("Hosts are split.  group1: " + tokenRangesToHost.get(set1) + " group2: "
                + tokenRangesToHost.get(set2));
    }

    logErrorOrThrow(e.getMessage(), safetyDisabled);
}

From source file:eu.mondo.driver.mongo.MongoGraphDriver.java

@Override
public void insertEdges(final Multimap<String, String> edges, final String edgeURI) throws IOException {
    if (edges.isEmpty()) {
        return;// www.  j  a  v a 2  s .  co  m
    }

    for (String sourceVertexURI : edges.keySet()) {
        for (String destinationVertexURI : edges.get(sourceVertexURI)) {
            insertEdge(sourceVertexURI, destinationVertexURI, edgeURI);
        }
    }

}

From source file:eu.mondo.driver.mongo.MongoGraphDriver.java

@Override
public void deleteEdges(final Multimap<String, String> vertexURIs, final String edgeURI) throws IOException {
    if (vertexURIs.isEmpty()) {
        return;//www  .  j av  a2s .c  o  m
    }

    for (String sourceVertexURI : vertexURIs.keySet()) {
        for (String destinationVertexURI : vertexURIs.get(sourceVertexURI)) {
            deleteEdge(sourceVertexURI, destinationVertexURI, edgeURI);
        }
    }
}

From source file:net.shibboleth.idp.attribute.filter.matcher.saml.impl.MappedAttributeInMetadataMatcher.java

/** {@inheritDoc} */
@Override//  ww  w  .java 2 s.c  om
@Nonnull
public Set<IdPAttributeValue<?>> getMatchingValues(@Nonnull final IdPAttribute attribute,
        @Nonnull final AttributeFilterContext filterContext) {

    ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this);
    final Multimap<String, ? extends IdPAttribute> requestedAttributes = getRequestedAttributes(filterContext);

    if (null == requestedAttributes || requestedAttributes.isEmpty()) {
        if (matchIfMetadataSilent) {
            log.debug("{} The peer's metadata did not have appropriate requested attributes available"
                    + ", returning all the input values", getLogPrefix());
            return ImmutableSet.copyOf(attribute.getValues());
        } else {
            log.debug("{} The peer's metadata did not have appropriate requested attributes available"
                    + ", returning no values", getLogPrefix());
            return Collections.emptySet();
        }
    }

    final Collection<? extends IdPAttribute> requestedAttributeList = requestedAttributes
            .get(attribute.getId());

    if (null == requestedAttributeList) {
        log.debug("{} Attribute {} not found in metadata", getLogPrefix(), attribute.getId());
        return Collections.emptySet();
    }

    final Set<IdPAttributeValue<?>> values = new HashSet<>();

    for (final IdPAttribute requestedAttribute : requestedAttributeList) {

        if (null == requestedAttribute) {
            log.info("{} Attribute {} found in metadata but with no values that"
                    + " could be decoded, values not matched", getLogPrefix(), attribute.getId());
            continue;
        }

        if (requestedAttribute instanceof IdPRequestedAttribute
                && !((IdPRequestedAttribute) requestedAttribute).getIsRequired() && onlyIfRequired) {
            log.debug("{} Attribute {} found in metadata, but was not required, values not matched",
                    getLogPrefix(), attribute.getId());
            continue;
        }

        values.addAll(filterValues(attribute, requestedAttribute.getValues()));
    }
    return values;
}

From source file:eu.mondo.driver.fourstore.FourStoreGraphDriverReadWrite.java

@Override
public void insertEdgesWithVertex(final Multimap<String, String> edges, final String edgeType,
        final String targetVertexType) throws IOException {
    if (edges.isEmpty()) {
        return;/*www .ja  va 2  s  .  co  m*/
    }

    final ArrayList<String> sourceVertices = new ArrayList<>(edges.keySet());
    final List<List<String>> sourceVerticesPartitions = Lists.partition(sourceVertices, PARTITION_SIZE);
    for (final List<String> sourceVerticesPartition : sourceVerticesPartitions) {

        final Multimap<String, String> edgePartition = ArrayListMultimap.create();
        for (final String sourceVertexURI : sourceVerticesPartition) {
            final Collection<String> targetVertexURIs = edges.get(sourceVertexURI);
            edgePartition.putAll(sourceVertexURI, targetVertexURIs);
        }

        insertEdgesWithVertexPartition(edgePartition, edgeType, targetVertexType);
    }

}

From source file:com.google.api.explorer.client.embedded.EmbeddedParameterForm.java

private void setParameterValues(Multimap<String, String> paramValues) {
    if (paramValues != null && !paramValues.isEmpty()) {
        for (String key : paramValues.keySet()) {
            if (nameToEditor.containsKey(key)) {
                nameToEditor.get(key).setValue(Lists.newArrayList(paramValues.get(key)));
            }/*from w ww  . java  2 s  . co  m*/
        }
    }
}