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

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

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of key-value pairs in this multimap.

Usage

From source file:org.eclipse.xtext.serializer.sequencer.AssignmentFinder.java

protected Set<AbstractElement> findValidAssignmentsForContainmentRef(EObject semanticObj,
        Multimap<AbstractElement, ISerializationContext> assignments, EObject value) {
    Multimap<ISerializationContext, AbstractElement> children = ArrayListMultimap.create();
    for (Entry<AbstractElement, Collection<ISerializationContext>> e : assignments.asMap().entrySet()) {
        AbstractElement ele = e.getKey();
        if (ele instanceof RuleCall) {
            EClassifier classifier = ((RuleCall) ele).getRule().getType().getClassifier();
            if (!classifier.isInstance(value))
                continue;
        }//w  w w . j  av  a2  s  .  com
        for (ISerializationContext container : e.getValue()) {
            ISerializationContext child = SerializationContext.forChild(container, ele, value);
            children.put(child, ele);
        }
    }
    if (children.size() < 2)
        return Sets.newHashSet(children.values());
    Set<ISerializationContext> found = contextFinder.findByContents(value, children.keySet());
    Set<AbstractElement> result = Sets.newLinkedHashSet();
    for (ISerializationContext ctx : children.keySet())
        if (found.contains(ctx))
            result.addAll(children.get(ctx));
    return result;
}

From source file:org.jclouds.ec2.compute.extensions.EC2SecurityGroupExtension.java

@Override
public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,
        Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds,
        SecurityGroup group) {/*from   w w  w. ja  v  a2s  . c o  m*/
    String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
    String name = group.getName();

    if (Iterables.size(ipRanges) > 0) {
        for (String cidr : ipRanges) {
            client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, name, protocol,
                    startPort, endPort, cidr);
        }
    }

    if (tenantIdGroupNamePairs.size() > 0) {
        for (String userId : tenantIdGroupNamePairs.keySet()) {
            for (String groupName : tenantIdGroupNamePairs.get(userId)) {
                client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, name,
                        new UserIdGroupPair(userId, groupName));
            }
        }
    }

    return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode());
}

From source file:org.jclouds.ec2.compute.extensions.EC2SecurityGroupExtension.java

@Override
public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,
        Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds,
        SecurityGroup group) {/*  ww w.j a  v  a2 s  .  c om*/
    String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
    String name = group.getName();

    if (Iterables.size(ipRanges) > 0) {
        for (String cidr : ipRanges) {
            client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, name, protocol,
                    startPort, endPort, cidr);
        }
    }

    if (tenantIdGroupNamePairs.size() > 0) {
        for (String userId : tenantIdGroupNamePairs.keySet()) {
            for (String groupName : tenantIdGroupNamePairs.get(userId)) {
                client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, name,
                        new UserIdGroupPair(userId, groupName));
            }
        }
    }

    return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode());
}

From source file:com.tinspx.util.collect.CollectUtils.java

public static <K> boolean equalIgnoreOrder(@Nullable Multimap<K, ?> a, @Nullable Multimap<? super K, ?> b) {
    if (a == null || b == null) {
        return a == null && b == null;
    }/*from   w  w w  .ja  v a  2 s.  c  o  m*/
    if (a.size() != b.size()) {
        return false;
    }
    if (a.keySet().size() != b.keySet().size()) {
        return false;
    }
    if (a.equals(b)) {
        return true;
    }
    if (a instanceof SetMultimap && b instanceof SetMultimap) {
        return false;
    }
    for (K key : a.keySet()) {
        if (!equalIgnoreOrder(a.get(key), b.get(key))) {
            return false;
        }
    }
    //a and b have the same number distinct keys so don't need to iterate
    //over b keys
    return true;
}

From source file:com.torodb.torod.db.postgresql.query.QueryEvaluator.java

@Nonnull
private Map<Integer, DatabaseQuery> createDatabaseQueryByStructure(@Nullable QueryCriteria criteria,
        DSLContext dsl) {/*  w w w .j  av  a 2  s . co  m*/

    Map<Integer, DatabaseQuery> result;

    if (criteria == null) {
        BiMap<Integer, DocStructure> allStructures = colSchema.getStructuresCache().getAllStructures();
        result = Maps.newHashMapWithExpectedSize(allStructures.size());

        for (Integer sid : colSchema.getStructuresCache().getAllStructures().keySet()) {
            result.put(sid, SelectAllDatabaseQuery.getInstance());
        }
    } else {
        Multimap<Integer, QueryCriteria> candidateStructures = QueryStructureFilter.filterStructures(colSchema,
                criteria);

        if (candidateStructures.isEmpty()) {
            result = Collections.emptyMap();
        } else {
            result = Maps.newHashMapWithExpectedSize(candidateStructures.size());

            for (Map.Entry<Integer, QueryCriteria> entry : candidateStructures.entries()) {
                Integer sid = entry.getKey();
                DocStructure rootStructure = colSchema.getStructuresCache().getStructure(sid);

                DatabaseQuery databaseQuery = createDatabaseQuery(entry.getValue(), sid, rootStructure, dsl);
                if (!(databaseQuery instanceof FalseDatabaseQuery)) {
                    result.put(sid, databaseQuery);
                }
            }
        }
    }

    return result;
}

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  w ww .j ava 2 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:com.twitter.aurora.scheduler.thrift.SchedulerThriftInterface.java

private Optional<String> rewriteConfig(ConfigRewrite command, MutableStoreProvider storeProvider) {

    Optional<String> error = Optional.absent();
    switch (command.getSetField()) {
    case JOB_REWRITE:
        JobConfigRewrite jobRewrite = command.getJobRewrite();
        IJobConfiguration existingJob = IJobConfiguration.build(jobRewrite.getOldJob());
        IJobConfiguration rewrittenJob;//  w w  w  .j a va2s. c  o m
        try {
            rewrittenJob = ConfigurationManager
                    .validateAndPopulate(IJobConfiguration.build(jobRewrite.getRewrittenJob()));
        } catch (TaskDescriptionException e) {
            // We could add an error here, but this is probably a hint of something wrong in
            // the client that's causing a bad configuration to be applied.
            throw Throwables.propagate(e);
        }
        if (!existingJob.getKey().equals(rewrittenJob.getKey())) {
            error = Optional.of("Disallowing rewrite attempting to change job key.");
        } else if (!existingJob.getOwner().equals(rewrittenJob.getOwner())) {
            error = Optional.of("Disallowing rewrite attempting to change job owner.");
        } else {
            JobStore.Mutable jobStore = storeProvider.getJobStore();
            Multimap<String, IJobConfiguration> matches = jobsByKey(jobStore, existingJob.getKey());
            switch (matches.size()) {
            case 0:
                error = Optional.of("No jobs found for key " + JobKeys.toPath(existingJob));
                break;

            case 1:
                Map.Entry<String, IJobConfiguration> match = Iterables.getOnlyElement(matches.entries());
                IJobConfiguration storedJob = match.getValue();
                if (!storedJob.equals(existingJob)) {
                    error = Optional.of("CAS compare failed for " + JobKeys.toPath(storedJob));
                } else {
                    jobStore.saveAcceptedJob(match.getKey(), rewrittenJob);
                }
                break;

            default:
                error = Optional.of("Multiple jobs found for key " + JobKeys.toPath(existingJob));
            }
        }
        break;

    case INSTANCE_REWRITE:
        InstanceConfigRewrite instanceRewrite = command.getInstanceRewrite();
        InstanceKey instanceKey = instanceRewrite.getInstanceKey();
        Iterable<IScheduledTask> tasks = storeProvider.getTaskStore().fetchTasks(Query
                .instanceScoped(IJobKey.build(instanceKey.getJobKey()), instanceKey.getInstanceId()).active());
        Optional<IAssignedTask> task = Optional.fromNullable(Iterables.getOnlyElement(tasks, null))
                .transform(Tasks.SCHEDULED_TO_ASSIGNED);
        if (!task.isPresent()) {
            error = Optional.of("No active task found for " + instanceKey);
        } else if (!task.get().getTask().newBuilder().equals(instanceRewrite.getOldTask())) {
            error = Optional.of("CAS compare failed for " + instanceKey);
        } else {
            ITaskConfig newConfiguration = ITaskConfig
                    .build(ConfigurationManager.applyDefaultsIfUnset(instanceRewrite.getRewrittenTask()));
            boolean changed = storeProvider.getUnsafeTaskStore().unsafeModifyInPlace(task.get().getTaskId(),
                    newConfiguration);
            if (!changed) {
                error = Optional.of("Did not change " + task.get().getTaskId());
            }
        }
        break;

    default:
        throw new IllegalArgumentException("Unhandled command type " + command.getSetField());
    }

    return error;
}

From source file:com.torodb.torod.db.backends.query.QueryEvaluator.java

@Nonnull
private Map<Integer, DatabaseQuery> createDatabaseQueryByStructure(@Nullable QueryCriteria criteria,
        DSLContext dsl) {/*  w ww.  java2  s  .  com*/

    Map<Integer, DatabaseQuery> result;

    if (criteria == null) {
        BiMap<Integer, DocStructure> allStructures = colSchema.getStructuresCache().getAllStructures();
        result = Maps.newHashMapWithExpectedSize(allStructures.size());

        DatabaseQuery databaseQuery = SelectAllDatabaseQuery.getInstance();

        for (Integer sid : colSchema.getStructuresCache().getAllStructures().keySet()) {
            result.put(sid, databaseQuery);
        }
    } else {
        Multimap<Integer, QueryCriteria> candidateStructures = QueryStructureFilter.filterStructures(colSchema,
                criteria);

        if (candidateStructures.isEmpty()) {
            result = Collections.emptyMap();
        } else {
            result = Maps.newHashMapWithExpectedSize(candidateStructures.size());

            for (Map.Entry<Integer, QueryCriteria> entry : candidateStructures.entries()) {
                Integer sid = entry.getKey();
                DocStructure rootStructure = colSchema.getStructuresCache().getStructure(sid);

                DatabaseQuery databaseQuery = createDatabaseQuery(entry.getValue(), sid, rootStructure, dsl);

                if (!(databaseQuery instanceof FalseDatabaseQuery)) {
                    result.put(sid, databaseQuery);
                }
            }
        }
    }

    return result;
}

From source file:de.iteratec.iteraplan.businesslogic.service.SearchServiceImpl.java

/** {@inheritDoc} */
public SearchDTO getSearchDTO(SearchDialogMemory searchDialogMemory) {
    UserContext.getCurrentPerms().assureFunctionalPermission(TypeOfFunctionalPermission.SEARCH);

    String searchField = searchDialogMemory.getSearchField();

    SearchDTO dto = new SearchDTO();

    if (StringUtils.isEmpty(searchField)) {
        return dto;
    }// w  ww  .  ja v  a 2s  .co  m

    // Use an ArrayListMultimap, to ensure the order of the results is preserved.
    Multimap<String, SearchRowDTO> searchMap = ArrayListMultimap.create();

    // Modify the queryString
    String modQueryString = modifyQueryString(searchField);

    // execute the search and put the results into the searchMap
    executeSearchQuery(searchMap, modQueryString, searchDialogMemory.getBuildingBlockTypeFilter());

    dto.setSearchMultiMap(searchMap);

    // if no results were found, and the string is not surrounded by '*' but only one word
    if (searchMap.size() == 0 && isQueryStringModifiable(modQueryString)) {
        Multimap<String, SearchRowDTO> altSearchMap = ArrayListMultimap.create();
        String altQueryString = modifyQueryString(modQueryString);
        executeSearchQuery(altSearchMap, altQueryString, searchDialogMemory.getBuildingBlockTypeFilter());
        dto.setNumberOfAlternativeResults(altSearchMap.size());
        dto.setAlternativeQueryString(altQueryString);
    }

    dto.setSearchMultiMap(searchMap);
    return dto;

}

From source file:com.b2international.snowowl.snomed.core.ecl.SnomedEclRefinementEvaluator.java

/**
 * Handles attribute refinements inside attribute group refinements.
 *///from w w w  .j  a  v a2  s.c  o m
protected Promise<Collection<Property>> evalGroup(final BranchContext context,
        final Range<Long> groupCardinality, final AttributeConstraint refinement) {
    if (refinement.isReversed()) {
        throw new BadRequestException("Reversed attributes are not supported in group refinements");
    } else {
        return evalRefinement(context, refinement, true, groupCardinality).thenWith(input -> {
            final Cardinality cardinality = refinement.getCardinality();
            // two cases here, one is the [1..x] the other is [0..x]
            if (cardinality != null && cardinality.getMin() == 0
                    && cardinality.getMax() != UNBOUNDED_CARDINALITY) {
                // XXX internal evaluation returns negative matches, that should be excluded from the focusConcept set
                final Function<Property, Object> idProvider = refinement.isReversed() ? Property::getValue
                        : Property::getObjectId;

                final Set<String> matchingIds = FluentIterable.from(input).transform(idProvider)
                        .filter(String.class).toSet();
                return focusConcepts.resolveToConceptsWithGroups(context)
                        .then(new Function<Multimap<String, Integer>, Collection<Property>>() {
                            @Override
                            public Collection<Property> apply(Multimap<String, Integer> groupsById) {
                                if (groupsById.isEmpty()) {
                                    return Sets.newHashSet();
                                } else {
                                    final Collection<Property> matchingProperties = newHashSetWithExpectedSize(
                                            groupsById.size() - matchingIds.size());
                                    for (Entry<String, Integer> entry : groupsById.entries()) {
                                        final String id = entry.getKey();
                                        if (!matchingIds.contains(id)) {
                                            matchingProperties.add(new Property(id, entry.getValue()));
                                        }
                                    }
                                    return matchingProperties;
                                }
                            }
                        });
            } else {
                return Promise.immediate(input);
            }
        }).failWith(throwable -> {
            if (throwable instanceof MatchAll) {
                return focusConcepts.resolveToConceptsWithGroups(context)
                        .then(new Function<Multimap<String, Integer>, Collection<Property>>() {
                            @Override
                            public Collection<Property> apply(Multimap<String, Integer> groupsById) {
                                final Collection<Property> matchingProperties = newHashSetWithExpectedSize(
                                        groupsById.size());
                                for (Entry<String, Integer> entry : groupsById.entries()) {
                                    matchingProperties.add(new Property(entry.getKey(), entry.getValue()));
                                }
                                return matchingProperties;
                            }
                        });
            }
            throw new SnowowlRuntimeException(throwable);
        });
    }
}