Example usage for com.google.common.collect SetMultimap put

List of usage examples for com.google.common.collect SetMultimap put

Introduction

In this page you can find the example usage for com.google.common.collect SetMultimap put.

Prototype

boolean put(@Nullable K key, @Nullable V value);

Source Link

Document

Stores a key-value pair in this multimap.

Usage

From source file:org.joda.beans.ser.GuavaSerIteratorFactory.java

/**
 * Gets an iterable wrapper for {@code SetMultimap}.
 * //from   w w w .  jav  a 2s .  com
 * @param keyType  the key type, not null
 * @param valueType  the value type, not null
 * @param valueTypeTypes  the generic parameters of the value type
 * @return the iterable, not null
 */
public static final SerIterable setMultimap(final Class<?> keyType, final Class<?> valueType,
        final List<Class<?>> valueTypeTypes) {
    final SetMultimap<Object, Object> map = HashMultimap.create();
    return new SerIterable() {
        @Override
        public SerIterator iterator() {
            return multimap(map, Object.class, keyType, valueType, valueTypeTypes);
        }

        @Override
        public void add(Object key, Object column, Object value, int count) {
            if (key == null) {
                throw new IllegalArgumentException("Missing key");
            }
            if (count != 1) {
                throw new IllegalArgumentException("Unexpected count");
            }
            map.put(key, value);
        }

        @Override
        public Object build() {
            return map;
        }

        @Override
        public SerCategory category() {
            return SerCategory.MAP;
        }

        @Override
        public Class<?> keyType() {
            return keyType;
        }

        @Override
        public Class<?> valueType() {
            return valueType;
        }

        @Override
        public List<Class<?>> valueTypeTypes() {
            return valueTypeTypes;
        }
    };
}

From source file:edu.cmu.lti.oaqa.baseqa.answer.yesno.scorers.ConceptOverlapYesNoScorer.java

@Override
public Map<String, Double> score(JCas jcas) throws AnalysisEngineProcessException {
    // create ctype2concepts maps and concept counts in question and snippets
    SetMultimap<String, Concept> ctype2concepts = HashMultimap.create();
    Multiset<Concept> concept2count = HashMultiset.create();
    for (Concept concept : TypeUtil.getConcepts(jcas)) {
        TypeUtil.getConceptTypes(concept).stream().map(ConceptType::getAbbreviation)
                .forEach(ctype -> ctype2concepts.put(ctype, concept));
        long count = TypeUtil.getConceptMentions(concept).stream()
                .map(cmention -> cmention.getView().getViewName()).distinct().count();
        concept2count.setCount(concept, (int) count);
    }/*from  w w w .j  av a2 s  .  c  om*/
    Set<Concept> qconcepts = TypeUtil.getConceptMentions(jcas).stream().map(ConceptMention::getConcept)
            .collect(toSet());
    // prepare cross-ctype counts
    ImmutableMap.Builder<String, Double> features = ImmutableMap.builder();
    ListMultimap<String, Double> keyword2values = ArrayListMultimap.create();
    for (String ctype : ctype2concepts.keySet()) {
        Set<Concept> concepts = ctype2concepts.get(ctype);
        // local counts
        int[] totalCounts = concepts.stream().mapToInt(concept2count::count).toArray();
        double[] questionCounts = concepts.stream().mapToDouble(concept -> qconcepts.contains(concept) ? 1 : 0)
                .toArray();
        double[] questionRatios = IntStream.range(0, concepts.size())
                .mapToDouble(i -> questionCounts[i] / totalCounts[i]).toArray();
        double[] passageRatios = DoubleStream.of(questionRatios).map(r -> 1.0 - r).toArray();
        // create feature counts aggregated for each ctype
        addAvgMaxMinFeatures(questionCounts, features, keyword2values, "question-count", ctype);
        addAvgMaxMinFeatures(questionRatios, features, keyword2values, "question-ratio", ctype);
        addAvgMaxMinFeatures(passageRatios, features, keyword2values, "passage-ratio", ctype);
        double questionRatioAvgMicro = DoubleStream.of(questionCounts).sum() / IntStream.of(totalCounts).sum();
        features.put("question-ratio-avg-micro@" + ctype, questionRatioAvgMicro);
        keyword2values.put("question-ratio-avg-micro", questionRatioAvgMicro);
        double passageRatioAvgMicro = 1.0 - questionRatioAvgMicro;
        features.put("passage-ratio-avg-macro@" + ctype, passageRatioAvgMicro);
        keyword2values.put("passage-ratio-avg-macro", passageRatioAvgMicro);
    }
    // global features
    keyword2values.asMap().entrySet().stream().map(e -> YesNoScorer.aggregateFeatures(e.getValue(), e.getKey()))
            .forEach(features::putAll);
    return features.build();
}

From source file:ome.services.query.HierarchyNavigator.java

/**
 * Batch bulk database queries to prime the cache for {@link #doLookup(String, String, Long)}.
 * It is not necessary to call this method, but it is advised if many lookups are anticipated.
 * @param toType the type of the objects to which the query objects may be related, not <code>null</code>
 * @param fromType the query object's type, not <code>null</code>
 * @param fromIds the query objects' database IDs, none <code>null</code>
 *//* www .  j a v a  2 s.  c o m*/
protected void prepareLookups(String toType, String fromType, Collection<Long> fromIds) {
    /* note which query object IDs have not already had results cached */
    final Set<Long> fromIdsToQuery = new HashSet<Long>(fromIds);
    for (final long fromId : fromIds) {
        if (cache.getFromCache(fromType, fromId, toType) != null) {
            fromIdsToQuery.remove(fromId);
        }
    }
    if (fromIdsToQuery.isEmpty()) {
        /* ... all of them are already cached */
        return;
    }
    /* collate the results from multiple batches */
    final SetMultimap<Long, Long> fromIdsToIds = HashMultimap.create();
    for (final List<Long> fromIdsToQueryBatch : Iterables.partition(fromIdsToQuery, 256)) {
        for (final Object[] queryResult : doQuery(toType, fromType, fromIdsToQueryBatch)) {
            fromIdsToIds.put((Long) queryResult[0], (Long) queryResult[1]);
        }
    }
    /* cache the results by query object */
    for (final Entry<Long, Collection<Long>> fromIdToIds : fromIdsToIds.asMap().entrySet()) {
        cache.putIntoCache(fromType, fromIdToIds.getKey(), toType, ImmutableSet.copyOf(fromIdToIds.getValue()));
    }
    /* note empty results so that the database is not again queried */
    for (final Long fromId : Sets.difference(fromIdsToQuery, fromIdsToIds.keySet())) {
        cache.putIntoCache(fromType, fromId, toType, ImmutableSet.<Long>of());
    }
}

From source file:com.palantir.atlasdb.keyvalue.impl.TableSplittingKeyValueService.java

@Override
public void truncateTables(Set<String> tableNames) {
    SetMultimap<KeyValueService, String> tablesToTruncateByKvs = HashMultimap.create();
    for (String tableName : tableNames) {
        tablesToTruncateByKvs.put(getDelegate(tableName), tableName);
    }/*from   w w w . ja  v  a  2s  . c om*/
    for (KeyValueService kvs : tablesToTruncateByKvs.keySet()) {
        kvs.truncateTables(tablesToTruncateByKvs.get(kvs));
    }
}

From source file:tiger.NewDependencyCollector.java

/**
 * NOTE: the key of the returned map is of the raw type if the related
 * {@link NewDependencyInfo#getDependant()} is for a generic class.
 *///w w w .j  a  va  2s .  com
public static SetMultimap<NewBindingKey, NewDependencyInfo> collectionToMultimap(
        Collection<NewDependencyInfo> dependencies) {
    SetMultimap<NewBindingKey, NewDependencyInfo> result = HashMultimap.create();
    for (NewDependencyInfo info : dependencies) {
        NewBindingKey key = info.getDependant();
        TypeName typeName = key.getTypeName();
        // For generic type with type variable, only keep raw type.
        if (typeName instanceof ParameterizedTypeName) {
            ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
            TypeName anyParameter = Preconditions.checkNotNull(
                    Iterables.getFirst(parameterizedTypeName.typeArguments, null),
                    String.format("ParameterizedTypeName of %s has no parameter.", key));
            if (anyParameter instanceof TypeVariableName) {
                typeName = parameterizedTypeName.rawType;
                key = NewBindingKey.get(typeName, key.getQualifier());
            }
        }

        result.put(key, info);
    }
    return result;
}

From source file:org.jboss.weld.bootstrap.ConcurrentValidator.java

@Override
public void validateBeanNames(final BeanManagerImpl beanManager) {
    final SetMultimap<String, Bean<?>> namedAccessibleBeans = Multimaps
            .newSetMultimap(new HashMap<String, Collection<Bean<?>>>(), HashSetSupplier.<Bean<?>>instance());

    for (Bean<?> bean : beanManager.getAccessibleBeans()) {
        if (bean.getName() != null) {
            namedAccessibleBeans.put(bean.getName(), bean);
        }/* w w w.ja  v a2s  . co m*/
    }

    final List<String> accessibleNamespaces = new ArrayList<String>();
    for (String namespace : beanManager.getAccessibleNamespaces()) {
        accessibleNamespaces.add(namespace);
    }

    final SpecializationAndEnablementRegistry registry = beanManager.getServices()
            .get(SpecializationAndEnablementRegistry.class);
    executor.invokeAllAndCheckForExceptions(
            new IterativeWorkerTaskFactory<String>(namedAccessibleBeans.keySet()) {
                protected void doWork(String name) {
                    Set<Bean<?>> resolvedBeans = beanManager.getBeanResolver().resolve(
                            Beans.removeDisabledBeans(namedAccessibleBeans.get(name), beanManager, registry));
                    if (resolvedBeans.size() > 1) {
                        throw ValidatorLogger.LOG.ambiguousElName(name,
                                WeldCollections.toMultiRowString(resolvedBeans));
                    }
                    if (accessibleNamespaces.contains(name)) {
                        throw ValidatorLogger.LOG.beanNameIsPrefix(name);
                    }
                }
            });
}

From source file:com.mgmtp.perfload.core.client.web.io.XmlRequestFlowReader.java

/**
 * Reads the XML resource transforming it into an objewct tree.
 * //from  ww  w . ja v a2  s . c om
 * @return the request flow instance
 */
public RequestFlow readFlow() throws ParserConfigurationException, SAXException, DocumentException {
    Element root = loadDocument().getRootElement();

    @SuppressWarnings("unchecked")
    List<Element> requests = root.elements();
    List<RequestTemplate> templates = newArrayListWithCapacity(requests.size());

    for (Element requestElem : requests) {
        String type = requestElem.attributeValue("type");
        String skip = defaultString(emptyToNull(requestElem.attributeValue("skip")), "false");
        String uri = requestElem.attributeValue("uri");
        String uriAlias = emptyToNull(requestElem.attributeValue("uriAlias"));
        String validateResponse = defaultString(emptyToNull(requestElem.attributeValue("validateResponse")),
                "true");

        @SuppressWarnings("unchecked")
        List<Element> params = requestElem.elements("param");
        SetMultimap<String, String> paramsMultiMap = HashMultimap.create(params.size(), 3);
        for (Element paramElem : params) {
            String key = paramElem.attributeValue("name");
            String value = paramElem.getText();
            paramsMultiMap.put(key, value);
        }

        @SuppressWarnings("unchecked")
        List<Element> headers = requestElem.elements("header");
        SetMultimap<String, String> headersMultiMap = HashMultimap.create(headers.size(), 3);
        for (Element headerElem : headers) {
            String key = headerElem.attributeValue("name");
            String value = headerElem.getText();
            headersMultiMap.put(key, value);
        }

        Element bodyElement = requestElem.element("body");
        Body body = null;
        if (bodyElement != null) {
            String bodyContent = emptyToNull(bodyElement.getText());
            String resPath = bodyElement.attributeValue("resourcePath");
            String resourceType = bodyElement.attributeValue("resourceType");

            checkState(bodyContent != null ^ (resPath != null && resourceType != null),
                    "Must specify either body content or resource path and type. [" + requestElem.asXML()
                            + "]");

            if (bodyContent != null) {
                body = Body.create(bodyContent);
            } else {
                body = Body.create(resPath, resourceType);
            }
        }

        @SuppressWarnings("unchecked")
        List<Element> headerExtractions = requestElem.elements("headerExtraction");
        List<HeaderExtraction> extractHeadersList = newArrayListWithCapacity(headerExtractions.size());
        for (Element extractHeaderElem : headerExtractions) {
            String name = extractHeaderElem.attributeValue("name");
            String placeholderName = extractHeaderElem.attributeValue("placeholderName");
            extractHeadersList.add(new HeaderExtraction(name, placeholderName));
        }

        @SuppressWarnings("unchecked")
        List<Element> detailExtractions = requestElem.elements("detailExtraction");
        List<DetailExtraction> extractDetailsList = newArrayListWithCapacity(detailExtractions.size());
        for (Element extractDetailElem : detailExtractions) {
            String name = extractDetailElem.attributeValue("name");

            String groupIndexString = extractDetailElem.attributeValue("groupIndex");
            //            int groupIndex = groupIndexString != null ? Integer.parseInt(groupIndexString) : 1;

            String defaultValue = extractDetailElem.attributeValue("defaultValue");

            String indexedString = extractDetailElem.attributeValue("indexed");
            //            boolean indexed = indexedString != null ? Boolean.parseBoolean(indexedString) : false;

            String failIfNotFoundString = extractDetailElem.attributeValue("failIfNotFound");
            //            boolean failIfNotFound = failIfNotFoundString == null || Boolean.valueOf(failIfNotFoundString);

            String pattern = extractDetailElem.getText().trim();

            DetailExtraction ed = new DetailExtraction(name, pattern, groupIndexString, defaultValue,
                    indexedString, failIfNotFoundString);
            extractDetailsList.add(ed);
        }

        templates.add(new RequestTemplate(type, skip, uri, uriAlias, headersMultiMap, paramsMultiMap, body,
                extractHeadersList, extractDetailsList, validateResponse));
    }

    return new RequestFlow(resourceName, templates);
}

From source file:org.jboss.errai.validation.rebind.GwtValidatorGenerator.java

@SuppressWarnings("unchecked")
private SetMultimap<MetaClass, Annotation> getValidationConfig(Collection<MetaClass> validationAnnotations,
        GeneratorContext context) {//ww  w.ja v  a 2s  .  c  om
    SetMultimap<MetaClass, Annotation> beans = HashMultimap.create();
    for (MetaClass annotation : validationAnnotations) {
        for (MetaField field : ClassScanner
                .getFieldsAnnotatedWith((Class<? extends Annotation>) annotation.asClass(), null, context)) {
            beans.put(field.getDeclaringClass(),
                    field.getAnnotation((Class<? extends Annotation>) annotation.asClass()));
        }
        for (MetaMethod method : ClassScanner
                .getMethodsAnnotatedWith((Class<? extends Annotation>) annotation.asClass(), null, context)) {
            beans.put(method.getDeclaringClass(),
                    method.getAnnotation((Class<? extends Annotation>) annotation.asClass()));
        }
        for (MetaClass type : ClassScanner
                .getTypesAnnotatedWith((Class<? extends Annotation>) annotation.asClass(), null, context)) {
            beans.put(type, type.getAnnotation((Class<? extends Annotation>) annotation.asClass()));
        }
    }

    return beans;
}

From source file:com.palantir.typescript.search.SearchResultTreeContentProvider.java

private void setSearchResult(SearchResult searchResult) {
    this.children.clear();

    for (Object element : searchResult.getElements()) {
        SetMultimap<Integer, FindReferenceMatch> matchesByLineNumber = TreeMultimap.create();

        // collect the matches for each line
        for (Match match : searchResult.getMatches(element)) {
            FindReferenceMatch findReferenceMatch = (FindReferenceMatch) match;
            int lineNumber = findReferenceMatch.getReference().getLineNumber();

            matchesByLineNumber.put(lineNumber, findReferenceMatch);
        }/*from  w  ww.  ja  va2 s. c om*/

        // add the lines
        for (Integer lineNumber : matchesByLineNumber.keySet()) {
            Set<FindReferenceMatch> lineMatches = matchesByLineNumber.get(lineNumber);
            LineResult lineResult = new LineResult(lineMatches);

            this.add(searchResult, lineResult);
        }
    }
}

From source file:org.onosproject.vpls.config.impl.VplsConfigurationImpl.java

/**
 * Retrieves the VPLS names and related interfaces names from the configuration.
 *
 * @return a map of VPLS names and related interface names
 *//*from  ww  w .  ja  v a 2 s. c om*/
private SetMultimap<String, String> getConfigInterfaces() {
    SetMultimap<String, String> confIntfByVpls = HashMultimap.create();

    vplsAppConfig.vplss().forEach(vpls -> {
        if (vpls.ifaces().isEmpty()) {
            confIntfByVpls.put(vpls.name(), EMPTY);
        } else {
            vpls.ifaces().forEach(iface -> confIntfByVpls.put(vpls.name(), iface));
        }
    });

    return confIntfByVpls;
}