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

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

Introduction

In this page you can find the example usage for com.google.common.collect Multimap 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.agorava.core.utils.URLUtils.java

/**
 * Create a {@link Multimap} from a simple bean.
 * <p/>/*from w w  w.j  av a 2 s.  c o m*/
 * All standard properties will become keys in the target map
 * <p/>
 * Collection properties will become multi-entries
 * <p/>
 * Map properties will trigger an exception
 *
 * @param pojo the bean to convert
 * @return the multimap
 * @throws AgoravaException if one property is a Map
 */
@SuppressWarnings({ "unchecked", "MismatchedQueryAndUpdateOfCollection" })
private static Multimap<String, Object> copyIntoMultiMap(Object pojo) {
    Map<String, ?> pojoMap = new BeanMap(pojo);
    Multimap<String, Object> res = HashMultimap.create();
    for (String key : pojoMap.keySet()) {
        if (!"class".equals(key)) {
            Object value = pojoMap.get(key);
            if (value instanceof Map)
                throw new AgoravaException("Cannot convert Pojo containing a Map to a Multimap");
            if (value instanceof Collection) {
                for (Object elt : (Collection<Object>) value) {
                    res.put(key, elt);
                }
            } else
                res.put(key, value);
        }
    }
    return res;
}

From source file:org.eigenbase.rel.WindowRel.java

private static void addWindows(Multimap<WindowKey, RexOver> windowMap, RexOver over) {
    final RexWindow aggWindow = over.getWindow();

    // Look up or create a window.
    RelCollation orderKeys = getCollation(aggWindow.orderKeys);
    BitSet groupSet = BitSets.of(getProjectOrdinals(aggWindow.partitionKeys));

    WindowKey windowKey = new WindowKey(groupSet, orderKeys, aggWindow.isRows(), aggWindow.getLowerBound(),
            aggWindow.getUpperBound());//from www  . jav  a 2 s  .c  o  m
    windowMap.put(windowKey, over);
}

From source file:edu.ucsb.eucalyptus.cloud.ws.SystemState.java

private static synchronized void checkNetworks() {

    Multimap<String, VmInstance> userVms = Multimaps.newArrayListMultimap();
    for (VmInstance v : VmInstances.getInstance().listValues())
        userVms.put(v.getOwnerId(), v);

    NavigableSet<NetworkToken> revokedTokens = Sets.newTreeSet();
    for (Network activeNet : Networks.getInstance().listValues()) {
        String user = activeNet.getUserName();
        LOG.debug(String.format("checkNetworks: user=%-15s network=%-15s", user, activeNet.getNetworkName()));
        Multimap<String, String> clusterNetworkMap = Multimaps.newArrayListMultimap();

        for (VmInstance vm : userVms.get(user)) {
            clusterNetworkMap.get(vm.getPlacement()).addAll(vm.getNetworkNames());
        }/*from w  ww .  j  a v a 2s  .c o m*/

        for (NetworkToken token : activeNet.getNetworkTokens().values()) {
            if (!clusterNetworkMap.get(token.getCluster()).contains(token.getNetworkName())) {
                LOG.debug(String.format("checkNetworks: user=%-15s network=%-15s cluster=%-15s active=false",
                        user, activeNet.getNetworkName(), token.getCluster()));
                revokedTokens.add(token);
            } else {
                LOG.debug(String.format("checkNetworks: user=%-15s network=%-15s cluster=%-15s active=true",
                        user, activeNet.getNetworkName(), token.getCluster()));
            }
        }

        if (activeNet.getNetworkTokens().isEmpty())
            Networks.getInstance().deregister(activeNet.getName());
    }
    for (NetworkToken token : revokedTokens)
        SystemState.dispatchStopNetwork(token);
}

From source file:org.glowroot.agent.live.LiveWeavingServiceImpl.java

private static Set<Class<?>> getExistingModifiableSubClasses(Set<PointcutClassName> pointcutClassNames,
        Class<?>[] classes, Instrumentation instrumentation) {
    List<Class<?>> matchingClasses = Lists.newArrayList();
    Multimap<Class<?>, Class<?>> subClasses = ArrayListMultimap.create();
    for (Class<?> clazz : classes) {
        if (!instrumentation.isModifiableClass(clazz)) {
            continue;
        }/*w w  w  .  j  a  va  2 s.co m*/
        Class<?> superclass = clazz.getSuperclass();
        if (superclass != null) {
            subClasses.put(superclass, clazz);
        }
        for (Class<?> iface : clazz.getInterfaces()) {
            subClasses.put(iface, clazz);
        }
        for (PointcutClassName pointcutClassName : pointcutClassNames) {
            if (pointcutClassName.appliesTo(clazz.getName())) {
                matchingClasses.add(clazz);
                break;
            }
        }
    }
    Set<Class<?>> matchingSubClasses = Sets.newHashSet();
    for (Class<?> matchingClass : matchingClasses) {
        addToMatchingSubClasses(matchingClass, matchingSubClasses, subClasses);
    }
    return matchingSubClasses;
}

From source file:eu.tomylobo.routes.util.Ini.java

private static Multimap<String, String> loadSection(BufferedReader stream) throws IOException {
    Multimap<String, String> section = LinkedListMultimap.create();

    String line;//www  . ja va2s . c  om
    while ((line = stream.readLine()) != null) {
        if (line.trim().isEmpty())
            break;

        Matcher matcher = linePattern.matcher(line);

        if (!matcher.matches()) {
            System.err.println("Malformed line in file.");
            continue;
        }

        String key = matcher.group(1);
        String value = matcher.group(2);

        section.put(key, value);
    }
    return section;
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.listmetrics.ListMetricManager.java

public static void addMetricBatch(List<ListMetric> dataBatch) {
    // sort the collection by common items to require fewer lookups
    Multimap<PrefetchFields, ListMetric> dataBatchPrefetchMap = LinkedListMultimap.create();
    for (final ListMetric item : dataBatch) {
        PrefetchFields prefetchFields = new PrefetchFields(item.getAccountId(), item.getNamespace(),
                item.getMetricName());/*from w  ww . ja  v  a2  s  . c o  m*/
        dataBatchPrefetchMap.put(prefetchFields, item);
    }
    // do db stuff in a certain number of operations per connection
    for (List<PrefetchFields> prefetchFieldsListPartial : Iterables.partition(dataBatchPrefetchMap.keySet(),
            LIST_METRIC_NUM_DB_OPERATIONS_PER_TRANSACTION)) {
        try (final TransactionResource db = Entities.transactionFor(ListMetric.class)) {
            int numOperations = 0;
            for (PrefetchFields prefetchFields : prefetchFieldsListPartial) {
                // Prefetch all list metrics with same metric name/namespace/account id
                Map<NonPrefetchFields, ListMetric> dataCache = Maps.newHashMap();
                Criteria criteria = Entities.createCriteria(ListMetric.class)
                        .add(Restrictions.eq("accountId", prefetchFields.getAccountId()))
                        .add(Restrictions.eq("namespace", prefetchFields.getNamespace()))
                        .add(Restrictions.eq("metricName", prefetchFields.getMetricName()));
                List<ListMetric> results = (List<ListMetric>) criteria.list();
                for (ListMetric result : results) {
                    dataCache.put(new NonPrefetchFields(result.getMetricType(), result.getDimensionMap()),
                            result);
                }
                for (ListMetric listMetric : dataBatchPrefetchMap.get(prefetchFields)) {
                    NonPrefetchFields cacheKey = new NonPrefetchFields(listMetric.getMetricType(),
                            listMetric.getDimensionMap());
                    if (dataCache.containsKey(cacheKey)) {
                        dataCache.get(cacheKey).updateTimeStamps();
                    } else {
                        Entities.persist(listMetric);
                        dataCache.put(cacheKey, listMetric);
                    }
                }
                numOperations++;
                if (numOperations % LIST_METRIC_NUM_DB_OPERATIONS_UNTIL_SESSION_FLUSH == 0) {
                    Entities.flushSession(ListMetric.class);
                    Entities.clearSession(ListMetric.class);
                }
            }
            db.commit();
        }
    }
}

From source file:it.unibz.inf.ontop.owlrefplatform.core.basicoperations.DBMetadataUtil.java

/***
 * Generates a map for each predicate in the body of the rules in 'program'
 * that contains the Primary Key data for the predicates obtained from the
 * info in the metadata./*from ww  w .  j a va2s .co m*/
  *
  * It also returns the columns with unique constraints
  *
  * For instance, Given the table definition
  *   Tab0[col1:pk, col2:pk, col3, col4:unique, col5:unique],
  *
  * The methods will return the following Multimap:
  *  { Tab0 -> { [col1, col2], [col4], [col5] } }
  *
 * 
 * @param metadata
 * @param program
 */
public static Multimap<Predicate, List<Integer>> extractPKs(DBMetadata metadata) {

    Multimap<Predicate, List<Integer>> pkeys = HashMultimap.create();
    for (DatabaseRelationDefinition relation : metadata.getDatabaseRelations()) {
        Predicate predicate = Relation2DatalogPredicate.createPredicateFromRelation(relation);

        // primary key and unique constraints
        for (UniqueConstraint uc : relation.getUniqueConstraints()) {
            List<Integer> pkeyIdx = new ArrayList<>(uc.getAttributes().size());
            for (Attribute att : uc.getAttributes())
                pkeyIdx.add(att.getIndex());

            pkeys.put(predicate, pkeyIdx);
        }
    }
    return pkeys;
}

From source file:org.spf4j.perf.impl.ms.tsdb.TSDBMeasurementStore.java

private static Multimap<String, TSTable> getCounters(final Collection<TSTable> columnInfos) {
    Multimap<String, TSTable> result = HashMultimap.create();
    for (TSTable info : columnInfos) {
        if (isCounterOnly(info)) {
            String groupName = info.getTableName();
            if (groupName.startsWith("(")) {
                int cidx = groupName.indexOf(',');
                if (cidx > 0) {
                    groupName = groupName.substring(1, cidx);
                }// ww  w .  j a  v a 2 s. c  o m
            }
            result.put(groupName, info);
        }
    }
    return result;
}

From source file:pt.ua.tm.neji.test.ProteinToSpecies.java

private synchronized static Multimap<String, String> load(final InputStream inputStream) {

    logger.info("Loading protein to species mapping...");
    Multimap<String, String> map = HashMultimap.create();

    try (InputStreamReader isr = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(isr);) {
        String line;/*from  w  w w .  j av  a2 s.  c om*/

        while ((line = br.readLine()) != null) {
            String[] parts = line.split("\t");
            String uniprot = parts[0];
            String species = parts[2];

            if (species.contains("|")) {
                parts = species.split("[|]");
                String speciesSpecific = parts[0];
                String speciesGenus = parts[1];

                map.put(uniprot, speciesGenus);
                map.put(uniprot, speciesSpecific);
            } else {
                map.put(uniprot, species);
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException("There was a problem loading the mapping file.", ex);
    }

    logger.info("Done!");

    return map;
}

From source file:ai.grakn.graql.internal.query.QueryOperationExecutor.java

/**
 * <a href=https://en.wikipedia.org/wiki/Composition_of_relations>Compose</a> two {@link Multimap}s together,
 * treating them like many-to-many relations.
 *///  w  w w.  j  a  va 2 s. com
private static <K, T, V> Multimap<K, V> composeMultimaps(Multimap<K, T> map1, Multimap<T, V> map2) {
    Multimap<K, V> composed = HashMultimap.create();

    for (Map.Entry<K, T> entry1 : map1.entries()) {
        K key = entry1.getKey();
        T intermediateValue = entry1.getValue();

        for (V value : map2.get(intermediateValue)) {
            composed.put(key, value);
        }
    }

    return composed;
}