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:com.google.gapid.views.Formatter.java

/**
 * @return empty list if not a constant, single value for constants, more values, for bitfileds.
 *//* w w w  .ja  va 2s  . c om*/
public static Collection<Constant> findConstant(SnippetObject obj, Primitive type) {
    final ConstantSet constants = ConstantSet.lookup(type);
    if (constants == null || constants.getEntries().length == 0) {
        return Collections.emptyList();
    }

    // first, try and find exact match
    List<Constant> byValue = constants.getByValue(obj.getObject());
    if (byValue != null && byValue.size() != 0) {
        if (byValue.size() == 1) {
            // perfect, we have just 1 match
            return byValue;
        }
        // try and find the best match
        Labels labels = Labels.fromSnippets(obj.getSnippets());
        Constant result = disambiguate(byValue, labels);
        return result == null ? Collections.emptyList() : ImmutableList.of(result);
    }

    // we can not find any exact match,
    // but for a number, maybe we can find a combination of constants that match (bit flags)
    Object value = obj.getObject();
    if (!(value instanceof Number) || value instanceof Double || value instanceof Float) {
        return Collections.emptyList();
    }

    long valueNumber = ((Number) value).longValue();
    long leftToFind = valueNumber;
    Multimap<Number, Constant> resultMap = ArrayListMultimap.create();

    for (Constant constant : constants.getEntries()) {
        long constantValue = ((Number) constant.getValue()).longValue();
        if (Long.bitCount(constantValue) == 1 && (valueNumber & constantValue) != 0) {
            resultMap.put(constantValue, constant);
            leftToFind &= ~constantValue; // remove bit
        }
    }

    // we did not find enough flags to cover this constant
    if (leftToFind != 0) {
        return Collections.emptyList();
    }

    // we found exactly 1 of each constant to cover the whole value
    if (resultMap.keySet().size() == resultMap.size()) {
        return resultMap.values();
    }

    // we have more than 1 matching constant per flag to we need to disambiguate
    Labels labels = Labels.fromSnippets(obj.getSnippets());
    for (Number key : resultMap.keySet()) {
        Collection<Constant> flagConstants = resultMap.get(key);
        if (flagConstants.size() == 1) {
            // perfect, we only have 1 value for this
            continue;
        }

        Constant con = disambiguate(flagConstants, labels);
        if (con != null) {
            // we have several values, but we found 1 to use
            resultMap.replaceValues(key, ImmutableList.of(con));
        } else {
            // we have several values and we don't know what one to use
            return Collections.emptyList();
        }
    }
    // assert all constants are disambiguated now
    assert resultMap.keySet().size() == resultMap.size();
    return resultMap.values();
}

From source file:eumetsat.pn.elasticsearch.webapp.ElasticsearchApp.java

@Override
protected Map<String, Object> search(String searchTerms, String filterString, int from, int size) {
    Map<String, Object> data = new HashMap<>();
    // put "session" parameters here rightaway so it can be used in template even when empty result
    data.put("search_terms", searchTerms);
    data.put("filter_terms", filterString);

    URL url;//w  w  w  . ja va 2 s. com
    try {
        url = new URL(searchEndpointUrlString);
    } catch (MalformedURLException e) {
        log.error("Search enpoint URL malformed: {}", e.getMessage());
        addMessage(data, MessageLevel.danger, "Search endpoint URL is malformed: " + e.getMessage());
        return data;
    }

    List<Map<String, String>> resHits = new ArrayList<>();
    Map<String, String> resHit = null;

    Multimap<String, String> filterTermsMap = parseFiltersTerms(filterString);
    Set<String> hiddenFacets = new HashSet<>(); // to create the list of filters to hide

    String filterConstruct = "";
    if (filterTermsMap.size() > 0) {
        int i = 0;
        String filterTerms = "";
        for (String key : filterTermsMap.keySet()) {
            for (String term : filterTermsMap.get(key)) {
                if (i == 0) {
                    filterTerms += "{ \"term\" : { \"" + FACETS2HIERACHYNAMES.get(key) + "\":\"" + term
                            + "\"}}";
                } else {
                    filterTerms += ",{ \"term\" : { \"" + FACETS2HIERACHYNAMES.get(key) + "\":\"" + term
                            + "\"}}";
                }

                // hide the facets that are used for filtering
                hiddenFacets.add(key + ":" + term);

                i++;
            }
        }

        filterConstruct = " \"bool\" : { \"must\" : [" + filterTerms + "] }";
    }

    int lengthOfTitle = 300;
    int lengthOfAbstract = 5000;
    int boostFactorTitle = 10;

    String body = "{ " + // pagination information
            "\"from\" : " + from + ", \"size\" : " + size + "," + // request highlighted info
            "\"highlight\" : { \"pre_tags\" : [\"<em><strong>\"], \"post_tags\" : [\"</strong></em>\"], "
            + "                  \"fields\" : { \"identificationInfo.title\": {\"fragment_size\" : "
            + lengthOfTitle + ", \"number_of_fragments\" : 1}, "
            + "                                 \"identificationInfo.abstract\": {\"fragment_size\" : "
            + lengthOfAbstract + ", \"number_of_fragments\" : 1} } } , " + // request facets to refine search (here the maximum number of facets can be configured)
            " \"facets\" :   { \"satellites\": { \"terms\" : { \"field\" : \"hierarchyNames.satellite\", \"size\":5 } }, "
            + "                  \"instruments\": { \"terms\" : { \"field\" : \"hierarchyNames.instrument\", \"size\":5  } }, "
            + "                  \"categories\": { \"terms\" : { \"field\" : \"hierarchyNames.category\", \"size\": 5 } }, "
            + "                  \"societal Benefit Area\": { \"terms\" : { \"field\" : \"hierarchyNames.societalBenefitArea\", \"size\":5 } }, "
            + "                  \"distribution\": { \"terms\" : { \"field\" : \"hierarchyNames.distribution\", \"size\":5 } } "
            + "                }," + // add query info
            "\"query\" : { \"filtered\": { \"query\": "
            + "              { \"simple_query_string\" : { \"fields\" : [\"identificationInfo.title^"
            + boostFactorTitle + "\", \"identificationInfo.abstract\"], " + "\"query\" : \"" + searchTerms
            + "\" } " + "}" + ",\"filter\": {" + filterConstruct + "}" + " }}}";

    log.trace("elastic-search request: {}", body);

    //measure elapsed time
    Stopwatch stopwatch = Stopwatch.createStarted();

    WebResponse response = rClient.doGetRequest(url, new HashMap<String, String>(),
            new HashMap<String, String>(), body, log.isDebugEnabled());

    if (response == null) {
        log.error("Response from {} is null!", this.name);
        data.put("total_hits", 0);
        data = addMessage(data, MessageLevel.danger, "Response is null from " + this.name);
    } else {
        log.trace("Got response: {}", response);

        if (response.status == 200) {
            JSONParser parser = new JSONParser();
            JSONObject jsObj;
            try {
                jsObj = (JSONObject) parser.parse(response.body);
            } catch (ParseException e) {
                log.error("Could not parse search server response: {}", e);
                addMessage(data, MessageLevel.danger, "Could not parse server response: " + e.getMessage());
                return data;
            }

            Long hitcount = (Long) ((Map<?, ?>) jsObj.get("hits")).get("total");
            data.put("total_hits", hitcount);
            if (hitcount < 1)
                addMessage(data, MessageLevel.info, "No results found!");

            // compute the pagination information to create the pagination bar
            Map<String, Object> pagination = computePaginationParams(hitcount.intValue(), from);
            data.put("pagination", pagination);

            @SuppressWarnings("unchecked")
            List<Map<String, Object>> hits = (List<Map<String, Object>>) ((Map<?, ?>) jsObj.get("hits"))
                    .get("hits");

            //to get the highlight
            Map<?, ?> highlight = null;
            for (Map<String, Object> hit : hits) {
                resHit = new HashMap<>();

                resHit.put("id", (String) hit.get("_id"));
                resHit.put("score", String.format("%.4g%n", ((Double) hit.get("_score"))));

                // can have or not title or abstract
                // strategy. If it doesn't have an abstract or a title match then take it from the _source
                highlight = (Map<?, ?>) hit.get("highlight");

                if (highlight.containsKey("identificationInfo.title")) {
                    resHit.put("title",
                            (String) ((JSONArray) highlight.get("identificationInfo.title")).get(0));
                } else {
                    resHit.put("title", ((String) (((Map<?, ?>) (((Map<?, ?>) hit.get("_source"))
                            .get("identificationInfo"))).get("title"))));
                }

                if (highlight.containsKey("identificationInfo.abstract")) {
                    resHit.put("abstract",
                            (String) ((JSONArray) highlight.get("identificationInfo.abstract")).get(0));
                } else {
                    resHit.put("abstract", ((String) (((Map<?, ?>) (((Map<?, ?>) hit.get("_source"))
                            .get("identificationInfo"))).get("abstract"))));
                }

                JSONObject info = (JSONObject) ((JSONObject) hit.get("_source")).get("identificationInfo");
                JSONArray keywords = (JSONArray) info.get("keywords");
                resHit.put("keywords", Joiner.on(", ").join(keywords.iterator()));

                resHit.put("thumbnail", info.get("thumbnail").toString());
                resHit.put("status", info.get("status").toString());

                resHits.add(resHit);
            }

            data.put("hits", resHits);

            data.put("facets", jsObj.get("facets"));

            data.put("tohide", hiddenFacets);

        } else { // non-200 resonse
            log.error("Received non-200 response: {}", response);
            data = addMessage(data, MessageLevel.danger, "Non 200 response: " + response.toString());
        }
    }

    stopwatch.stop();

    data.put("elapsed", (double) (stopwatch.elapsed(TimeUnit.MILLISECONDS)) / (double) 1000);

    return data;
}

From source file:org.waveprotocol.box.server.waveserver.MemoryPerUserWaveViewHandlerImpl.java

@Override
public ListenableFuture<Void> onParticipantAdded(WaveletName waveletName, ParticipantId user) {
    Multimap<WaveId, WaveletId> perUserView = explicitPerUserWaveViews.getIfPresent(user);
    if (perUserView != null) {
        if (!perUserView.containsEntry(waveletName.waveId, waveletName.waveletId)) {
            perUserView.put(waveletName.waveId, waveletName.waveletId);
            if (LOG.isFineLoggable()) {
                LOG.fine("Added wavelet: " + waveletName + " to the view of user: " + user.getAddress());
                LOG.fine("View size is now: " + perUserView.size());
            }//from   w  w  w.  j  a  va2 s. c o  m
        }
    }
    SettableFuture<Void> task = SettableFuture.create();
    task.set(null);
    return task;
}

From source file:it.unibz.inf.ontop.r2rml.R2RMLWriter.java

private ImmutableList<OBDAMappingAxiom> splitMappingAxiom(OBDAMappingAxiom mappingAxiom,
        String delimiterSubstring) {
    Multimap<Function, Function> subjectTermToTargetTriples = ArrayListMultimap.create();
    for (Function targetTriple : mappingAxiom.getTargetQuery()) {
        Function subjectTerm = getFirstFunctionalTerm(targetTriple)
                .orElseThrow(() -> new IllegalStateException("Invalid OBDA mapping"));
        subjectTermToTargetTriples.put(subjectTerm, targetTriple);
    }/*  w  w  w.jav a  2s.  c o  m*/
    // If the partition per target triple subject is non trivial
    if (subjectTermToTargetTriples.size() > 1) {
        // Create ids for the new mapping axioms
        Map<Function, String> subjectTermToMappingIndex = new HashMap<>();
        int i = 1;
        for (Function subjectTerm : subjectTermToTargetTriples.keySet()) {
            subjectTermToMappingIndex.put(subjectTerm, mappingAxiom.getId() + delimiterSubstring + i);
            i++;
        }
        // Generate one mapping axiom per subject
        return subjectTermToTargetTriples.asMap().entrySet().stream()
                .map(e -> OBDA_DATA_FACTORY.getRDBMSMappingAxiom(subjectTermToMappingIndex.get(e.getKey()),
                        mappingAxiom.getSourceQuery(), new ArrayList<Function>(e.getValue())))
                .collect(ImmutableCollectors.toList());
    }
    return ImmutableList.of(mappingAxiom);
}

From source file:com.squareup.osstrich.JavadocPublisher.java

private int publishArtifacts(String repoUrl, String groupId, List<Artifact> artifacts) throws IOException {
    initGitDirectory(repoUrl);/*from   w w  w.  j  a  v  a 2 s  . c o m*/

    StringBuilder commitMessage = new StringBuilder();
    commitMessage.append("Publish Javadoc\n" + "\n" + "Artifacts published:");

    Multimap<String, Artifact> published = TreeMultimap.create();
    for (Artifact artifact : artifacts) {
        if (fetchJavadoc(artifact)) {
            published.put(majorVersion(artifact.latestVersion), artifact);
            commitMessage.append("\n").append(artifact);
        }
    }

    writeIndexFiles(groupId, published);

    if (!published.isEmpty()) {
        gitCommitAndPush(commitMessage.toString());
    }

    return published.size();
}

From source file:org.eclipse.xtext.xbase.ui.imports.MultiOrganizeImportsHandler.java

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchSite activeSite = HandlerUtil.getActiveSite(event);
    MultiOrganizeImportAction javaDelegate = new MultiOrganizeImportAction(activeSite);
    ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
    if (currentSelection instanceof IStructuredSelection) {
        IStructuredSelection structuredSelection = (IStructuredSelection) currentSelection;
        if (shouldRunJavaOrganizeImports()) {
            ICompilationUnit[] compilationUnits = javaDelegate.getCompilationUnits(structuredSelection);
            if (compilationUnits.length > 0) {
                javaDelegate.run(structuredSelection);
            }/*ww  w  .  j  a va 2 s.co  m*/
        }
        final Multimap<IProject, IFile> files = collectFiles(structuredSelection);
        Shell shell = activeSite.getShell();

        IRunnableWithProgress op = new IRunnableWithProgress() {

            @Override
            public void run(IProgressMonitor mon) throws InvocationTargetException, InterruptedException {
                mon.beginTask(Messages.OrganizeImports, files.size() * 2);
                mon.setTaskName(Messages.OrganizeImports + " - Calculating Import optimisations for "
                        + files.size() + " Xtend files");
                final List<Change> organizeImports = importOrganizerProvider.get().organizeImports(files, mon);
                for (int i = 0; !mon.isCanceled() && i < organizeImports.size(); i++) {
                    Change change = organizeImports.get(i);
                    mon.setTaskName("Performing changes - Xtend " + (i + 1) + " of " + files.size() + "");
                    try {
                        mon.subTask(change.getName());
                        change.perform(new SubProgressMonitor(mon, 1));
                    } catch (CoreException e) {
                        throw new InvocationTargetException(e);
                    }
                    if (mon.isCanceled()) {
                        throw new InterruptedException();
                    }
                }
            }
        };
        try {
            new ProgressMonitorDialog(shell).run(true, true, op);
        } catch (InvocationTargetException e) {
            handleException(e);
        } catch (InterruptedException e) {
            // user cancelled, ok
        }
    }
    return event.getApplicationContext();
}

From source file:com.bigdata.dastor.locator.AbstractReplicationStrategy.java

/**
 * returns multimap of {live destination: ultimate targets}, where if target is not the same
 * as the destination, it is a "hinted" write, and will need to be sent to
 * the ultimate target when it becomes alive again.
 *//*from  ww  w  .j  a v  a2s .c  o m*/
public Multimap<InetAddress, InetAddress> getHintedEndpoints(String table, Collection<InetAddress> targets) {
    Multimap<InetAddress, InetAddress> map = HashMultimap.create(targets.size(), 1);

    IEndPointSnitch endPointSnitch = DatabaseDescriptor.getEndPointSnitch(table);

    // first, add the live endpoints
    for (InetAddress ep : targets) {
        if (FailureDetector.instance.isAlive(ep))
            map.put(ep, ep);
    }

    // if everything was alive or we're not doing HH on this keyspace, stop with just the live nodes
    if (map.size() == targets.size() || !StorageProxy.isHintedHandoffEnabled())
        return map;

    // assign dead endpoints to be hinted to the closest live one, or to the local node
    // (since it is trivially the closest) if none are alive.  This way, the cost of doing
    // a hint is only adding the hint header, rather than doing a full extra write, if any
    // destination nodes are alive.
    //
    // we do a 2nd pass on targets instead of using temporary storage,
    // to optimize for the common case (everything was alive).
    InetAddress localAddress = FBUtilities.getLocalAddress();
    for (InetAddress ep : targets) {
        if (map.containsKey(ep))
            continue;

        InetAddress destination = map.isEmpty() ? localAddress
                : endPointSnitch.getSortedListByProximity(localAddress, map.keySet()).get(0);
        map.put(destination, ep);
    }

    return map;
}

From source file:com.facebook.presto.accumulo.tools.RewriteIndex.java

private void flushDeleteEntries(Connector connector, AccumuloTable table, long start, BatchWriter indexWriter,
        Multimap<ByteBuffer, Mutation> queryIndexEntries, Map<ByteBuffer, RowStatus> rowIdStatuses)
        throws MutationsRejectedException, TableNotFoundException {
    if (queryIndexEntries.size() > 0) {
        setRowIdStatuses(connector, table, start, queryIndexEntries, rowIdStatuses);

        AtomicLong numDeleteRows = new AtomicLong(0);
        ImmutableList.Builder<Mutation> builder = ImmutableList.builder();
        queryIndexEntries.asMap().entrySet().forEach(entry -> {
            if (rowIdStatuses.get(entry.getKey()) == RowStatus.ABSENT) {
                builder.addAll(entry.getValue());
                numDeleteRows.incrementAndGet();
            }/*from w w w.jav a2  s  .c  o  m*/
        });
        List<Mutation> deleteMutations = builder.build();

        numDeletedIndexEntries += deleteMutations.size();

        if (!dryRun) {
            indexWriter.addMutations(deleteMutations);
        }
    }
}

From source file:ninja.servlet.NinjaServletContext.java

/**
 * Utility method to convert a Guava Multimap to an unmodifiable Map that
 * uses a List<T> as a value. Optimized for the case where values are already
 * internally stored as a List<T> (e.g. ArrayListMultimap).
 * @param <T> The value type/*from   ww w .  ja v  a  2s .com*/
 * @param multimap The multimap to convert from
 * @return The unmodifiable converted map
 */
private <T> Map<String, List<T>> toUnmodifiableMap(Multimap<String, T> multimap) {
    Map<String, List<T>> map = new HashMap<>(multimap.size());

    for (Entry<String, Collection<T>> entry : multimap.asMap().entrySet()) {
        Collection<T> value = entry.getValue();
        if (value == null) {
            Collections.emptyList();
        } else if (value instanceof List) {
            map.put(entry.getKey(), (List<T>) value);
        } else {
            map.put(entry.getKey(), new ArrayList<>(value));
        }
    }

    return Collections.unmodifiableMap(map);
}

From source file:org.apache.cassandra.locator.AbstractReplicationStrategy.java

/**
 * returns <tt>Multimap</tt> of {live destination: ultimate targets}, where if target is not the same
 * as the destination, it is a "hinted" write, and will need to be sent to
 * the ultimate target when it becomes alive again.
 *//*  w  w w.java  2s.  co m*/
public Multimap<InetAddress, InetAddress> getHintedEndpoints(Collection<InetAddress> targets) {
    Multimap<InetAddress, InetAddress> map = HashMultimap.create(targets.size(), 1);

    // first, add the live endpoints
    for (InetAddress ep : targets) {
        if (FailureDetector.instance.isAlive(ep))
            map.put(ep, ep);
    }

    // if everything was alive or we're not doing HH on this keyspace, stop with just the live nodes
    if (map.size() == targets.size() || !StorageProxy.isHintedHandoffEnabled())
        return map;

    // assign dead endpoints to be hinted to the closest live one, or to the local node
    // (since it is trivially the closest) if none are alive.  This way, the cost of doing
    // a hint is only adding the hint header, rather than doing a full extra write, if any
    // destination nodes are alive.
    //
    // we do a 2nd pass on targets instead of using temporary storage,
    // to optimize for the common case (everything was alive).
    InetAddress localAddress = FBUtilities.getLocalAddress();
    for (InetAddress ep : targets) {
        if (map.containsKey(ep))
            continue;
        if (!StorageProxy.shouldHint(ep)) {
            if (logger.isDebugEnabled())
                logger.debug("not hinting " + ep + " which has been down "
                        + Gossiper.instance.getEndpointDowntime(ep) + "ms");
            continue;
        }

        //hint destination
        InetAddress destination = map.isEmpty() ? localAddress
                : snitch.getSortedListByProximity(localAddress, map.keySet()).get(0);
        map.put(destination, ep);
    }

    return map;
}