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.jboss.errai.ioc.rebind.ioc.bootstrapper.ProviderFactoryBodyGenerator.java

@Override
protected List<Statement> generateCreateInstanceStatements(final ClassStructureBuilder<?> bodyBlockBuilder,
        final Injectable injectable, final DependencyGraph graph, InjectionContext injectionContext) {
    final Multimap<DependencyType, Dependency> dependenciesByType = separateByType(
            injectable.getDependencies());
    assert dependenciesByType.size() == 1 : "The factory " + injectable.getFactoryName()
            + " is a Provider and should have exactly one dependency";
    final Collection<Dependency> providerInstanceDeps = dependenciesByType.get(DependencyType.ProducerMember);
    assert providerInstanceDeps.size() == 1 : "The factory " + injectable.getFactoryName()
            + " is a Provider but does not have a " + DependencyType.ProducerMember.toString() + " depenency.";

    final Dependency providerDep = providerInstanceDeps.iterator().next();
    final List<Statement> createInstanceStatements = getAndInvokeProvider(injectable, providerDep);

    return createInstanceStatements;
}

From source file:eu.interedition.collatex.medite.Matches.java

public static Matches between(VariantGraph.Vertex[][] vertices, SuffixTree<Token> suffixTree,
        Function<SortedSet<VertexMatch.WithTokenIndex>, Integer> matchEvaluator) {

    final Multimap<Integer, MatchThreadElement> matchThreads = HashMultimap.create();
    for (int rank = 0; rank < vertices.length; rank++) {
        for (VariantGraph.Vertex vertex : vertices[rank]) {
            final MatchThreadElement matchThreadElement = new MatchThreadElement(suffixTree).advance(vertex,
                    rank);//w  ww .  j  a  v  a 2  s.  co  m
            if (matchThreadElement != null) {
                matchThreads.put(rank, matchThreadElement);
            }
        }
        for (MatchThreadElement matchThreadElement : matchThreads.get(rank - 1)) {
            for (VariantGraph.Vertex vertex : vertices[rank]) {
                final MatchThreadElement advanced = matchThreadElement.advance(vertex, rank);
                if (advanced != null) {
                    matchThreads.put(rank, advanced);
                }
            }
        }
    }

    final Matches matches = new Matches(matchThreads.size());
    for (MatchThreadElement matchThreadElement : matchThreads.values()) {
        final List<SortedSet<VertexMatch.WithTokenIndex>> threadPhrases = Lists.newArrayList();
        boolean firstElement = true;
        for (MatchThreadElement threadElement : matchThreadElement.thread()) {
            final SuffixTree<Token>.EquivalenceClass equivalenceClass = threadElement.cursor.matchedClass();
            for (int mc = 0; mc < equivalenceClass.length; mc++) {
                final int tokenCandidate = equivalenceClass.members[mc];
                if (firstElement) {
                    final SortedSet<VertexMatch.WithTokenIndex> phrase = new TreeSet<VertexMatch.WithTokenIndex>();
                    phrase.add(new VertexMatch.WithTokenIndex(threadElement.vertex, threadElement.vertexRank,
                            tokenCandidate));
                    threadPhrases.add(phrase);
                } else {
                    for (SortedSet<VertexMatch.WithTokenIndex> phrase : threadPhrases) {
                        if ((phrase.last().token + 1) == tokenCandidate) {
                            phrase.add(new VertexMatch.WithTokenIndex(threadElement.vertex,
                                    threadElement.vertexRank, tokenCandidate));
                        }
                    }
                }
            }
            firstElement = false;
        }
        matches.addAll(threadPhrases);
    }
    Collections.sort(matches, maximalUniqueMatchOrdering(matchEvaluator));

    return matches;
}

From source file:net.myrrix.online.eval.AUCEvaluator.java

@Override
public EvaluationResult evaluate(MyrrixRecommender recommender, RescorerProvider provider, // ignored
        Multimap<Long, RecommendedItem> testData) throws TasteException {
    FastByIDMap<FastIDSet> converted = new FastByIDMap<FastIDSet>(testData.size());
    for (long userID : testData.keySet()) {
        Collection<RecommendedItem> userTestData = testData.get(userID);
        FastIDSet itemIDs = new FastIDSet(userTestData.size());
        converted.put(userID, itemIDs);/*www  .j  av a2s  .  c om*/
        for (RecommendedItem datum : userTestData) {
            itemIDs.add(datum.getItemID());
        }
    }
    return evaluate(recommender, converted);
}

From source file:com.zimbra.cs.db.DbBlobConsistency.java

public static void export(DbConnection conn, Mailbox mbox, String tableName, String idColName,
        Multimap<Integer, Integer> idRevs, String path) throws ServiceException {
    Set<Integer> mail_itemIds = new HashSet<Integer>();
    Multimap<Integer, Integer> rev_itemIds = HashMultimap.create();
    for (Integer itemId : idRevs.keySet()) {
        Collection<Integer> revs = idRevs.get(itemId);
        for (int rev : revs) {
            if (rev == 0) {
                mail_itemIds.add(itemId);
            } else {
                rev_itemIds.put(itemId, rev);
            }/*from  w w w  .  ja v  a 2 s. c om*/
        }
    }
    PreparedStatement stmt = null;

    if (!(Db.getInstance() instanceof MySQL)) {
        throw ServiceException.INVALID_REQUEST("export is only supported for MySQL", null);
    }
    ZimbraLog.sqltrace.info("Exporting %d items in table %s to %s.", idRevs.size(), tableName, path);

    try {
        StringBuffer sql = new StringBuffer();
        boolean revisionTable = tableName.startsWith(DbMailItem.TABLE_REVISION);
        sql.append("SELECT * FROM ").append(DbMailbox.qualifyTableName(mbox, tableName)).append(" WHERE ")
                .append(DbMailItem.IN_THIS_MAILBOX_AND);

        if (!revisionTable || mail_itemIds.size() > 0) {
            if (mail_itemIds.size() == 0) {
                sql.append(idColName).append(" in ('')");
            } else {
                sql.append(DbUtil.whereIn(idColName, mail_itemIds.size()));
            }
        }
        if (revisionTable) {
            if (mail_itemIds.size() > 0 && rev_itemIds.size() > 0) {
                sql.append(" OR ");
            }
            if (rev_itemIds.size() > 0) {
                sql.append(DbUtil.whereIn(Db.getInstance().concat(idColName, "'-'", "version"),
                        rev_itemIds.size()));
            }
        }
        sql.append(" INTO OUTFILE ?");
        stmt = conn.prepareStatement(sql.toString());
        int pos = 1;
        pos = DbMailItem.setMailboxId(stmt, mbox, pos);
        for (int itemId : mail_itemIds) {
            stmt.setInt(pos++, itemId);
        }

        if (revisionTable) {
            for (Integer itemId : rev_itemIds.keySet()) {
                Collection<Integer> revs = rev_itemIds.get(itemId);
                for (int rev : revs) {
                    stmt.setString(pos++, itemId + "-" + rev);
                }
            }
        }
        stmt.setString(pos++, path);
        stmt.execute();
    } catch (SQLException e) {
        throw ServiceException.FAILURE("exporting table " + tableName + " to " + path, e);
    } finally {
        DbPool.quietCloseStatement(stmt);
    }
}

From source file:io.crate.sql.tree.ObjectLiteral.java

public ObjectLiteral(@Nullable Multimap<String, Expression> values) {
    if (values == null) {
        this.values = ImmutableMultimap.of();
    } else {/* w  ww . j  av  a2  s  .  c o  m*/
        this.values = values;
        if (values.size() != values.keySet().size()) {
            throw new IllegalArgumentException("object contains duplicate keys: " + values);
        }
    }
}

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

public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    if (!params.keySet().equals(EXPECTED_KEYS)) {
        throw new TemplateException("ReplaceParametersDirective requires keys: " + EXPECTED_KEYS, environment);
    }/*  w  ww .  j a  v a 2 s .c o  m*/

    // I have no idea why freemarker feels the need to invent their own collection classes...
    SimpleHash parameterMap = (SimpleHash) params.get(PARAMETER_MAP_KEY);
    Multimap<String, TemplateModel> replacements = TemplateModelUtil
            .getAsMultimap((TemplateModel) params.get(REPLACEMENTS_KEY));
    Multimap<String, String> outputParams = replaceParameters(parameterMap, replacements);
    List<NameValuePair> paramList = new ArrayList<>(outputParams.size());
    for (String key : outputParams.keySet()) {
        for (String value : outputParams.get(key)) {
            paramList.add(new BasicNameValuePair(key, value));
        }
    }
    environment.getOut().write(URLEncodedUtils.format(paramList, "UTF-8"));
}

From source file:org.yakindu.sct.model.stext.expressions.STextExpressionParser.java

public EObject parseExpression(String expression, String ruleName, String specification) {
    StextResource resource = getResource();
    resource.setURI(URI.createURI("path", true));
    ParserRule parserRule = XtextFactory.eINSTANCE.createParserRule();
    parserRule.setName(ruleName);/*from  www  .j a  v  a2s .  c om*/
    IParseResult result = parser.parse(parserRule, new StringReader(expression));
    EObject rootASTElement = result.getRootASTElement();
    resource.getContents().add(rootASTElement);
    ListBasedDiagnosticConsumer diagnosticsConsumer = new ListBasedDiagnosticConsumer();
    Statechart sc = SGraphFactory.eINSTANCE.createStatechart();
    sc.setDomainID(domainId);
    sc.setName("sc");
    if (specification != null) {
        sc.setSpecification(specification);
    }
    resource.getContents().add(sc);
    linker.linkModel(sc, diagnosticsConsumer);
    linker.linkModel(rootASTElement, diagnosticsConsumer);
    resource.resolveLazyCrossReferences(CancelIndicator.NullImpl);
    resource.resolveLazyCrossReferences(CancelIndicator.NullImpl);
    Multimap<SpecificationElement, Diagnostic> diagnostics = resource.getLinkingDiagnostics();
    if (diagnostics.size() > 0) {
        throw new LinkingException(diagnostics.toString());
    }
    if (result.hasSyntaxErrors()) {
        StringBuilder errorMessages = new StringBuilder();
        Iterable<INode> syntaxErrors = result.getSyntaxErrors();
        for (INode iNode : syntaxErrors) {
            errorMessages.append(iNode.getSyntaxErrorMessage());
            errorMessages.append("\n");
        }
        throw new SyntaxException("Could not parse expression, syntax errors: " + errorMessages);
    }
    if (diagnosticsConsumer.hasConsumedDiagnostics(Severity.ERROR)) {
        throw new LinkingException("Error during linking: " + diagnosticsConsumer.getResult(Severity.ERROR));
    }
    return rootASTElement;
}

From source file:org.apache.pulsar.broker.loadbalance.impl.WRRPlacementStrategy.java

/**
 * <code>/*from   w w w .  j  a v  a  2s  .c  o  m*/
 * Function : getByWeightedRoundRobin
 *            returns ResourceUnit selected by WRR algorithm based on available resource on RU
 * ^
 * |
 * |
 * |
 * |                |                        |                                |     |
 * |                |                        |                                |     |
 * |   Broker 2     |       Broker 3         |         Broker 1               |  B4 |
 * |                |                        |                                |     |
 * +----------------+------------------------+--------------------------------+--------->
 * 0                20                       50                               90    100
 *
 * This is weighted Round robin, we calculate weight based on availability of resources;
 * total availability is taken as a full range then each broker is given range based on
 *  its resource availability, if the number generated within total range happens to be in
 * broker's range, that broker is selected
 * </code>
 */
public ResourceUnit findBrokerForPlacement(Multimap<Long, ResourceUnit> finalCandidates) {
    if (finalCandidates.isEmpty()) {
        return null;
    }
    log.debug("Total Final Candidates selected - [{}]", finalCandidates.size());
    int totalAvailability = 0;
    for (Map.Entry<Long, ResourceUnit> candidateOwner : finalCandidates.entries()) {
        totalAvailability += candidateOwner.getKey().intValue();
    }
    ResourceUnit selectedRU = null;
    if (totalAvailability <= 0) {
        // todo: this means all the brokers are overloaded and we can't assign this namespace to any broker
        // for now, pick anyone and return that one, because when we don't have ranking we put O for each broker
        return Iterables.get(finalCandidates.get(0L), rand.nextInt(finalCandidates.size()));
    }
    int weightedSelector = rand.nextInt(totalAvailability);
    log.debug("Generated Weighted Selector Number - [{}] ", weightedSelector);
    int weightRangeSoFar = 0;
    for (Map.Entry<Long, ResourceUnit> candidateOwner : finalCandidates.entries()) {
        weightRangeSoFar += candidateOwner.getKey();
        if (weightedSelector < weightRangeSoFar) {
            selectedRU = candidateOwner.getValue();
            log.debug(" Weighted Round Robin Selected RU - [{}]", candidateOwner.getValue().getResourceId());
            break;
        }
    }
    return selectedRU;
}

From source file:org.jclouds.net.util.IpPermissions.java

protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
        Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks) {
    super(ipProtocol, fromPort, toPort, tenantIdGroupPairs, groupIds,
            tenantIdGroupPairs.size() == 0 ? cidrBlocks : ImmutableSet.<String>of());
}

From source file:com.netflix.simianarmy.client.aws.chaos.TagsChaosCrawler.java

@Override
public List<InstanceGroup> groups(String... names) {
    Multimap<String, Instance> instances = getInstancesGroupedByTags(tags);

    if (instances.isEmpty()) {
        return ImmutableList.of();
    }//from w  w  w. ja va 2  s . com

    List<InstanceGroup> result = new ArrayList<>(instances.size());
    for (Map.Entry<String, Collection<Instance>> group : instances.asMap().entrySet()) {
        if (names != null && indexOf(names, group.getKey()) < 0)
            continue;
        InstanceGroup instanceGroup = new BasicInstanceGroup(group.getKey(), Type.TAGGED_EC2,
                awsClient.region());
        result.add(instanceGroup);
        for (Instance instance : group.getValue()) {
            instanceGroup.addInstance(instance.getInstanceId());
        }
    }
    return result;
}