List of usage examples for com.google.common.collect Multimap put
boolean put(@Nullable K key, @Nullable V value);
From source file:eu.interedition.collatex.util.ParallelSegmentationApparatus.java
public static void generate(VariantGraphRanking ranking, GeneratorCallback callback) { callback.start();/* w w w . ja v a 2 s . c o m*/ final Set<Witness> allWitnesses = ranking.witnesses(); for (Iterator<Map.Entry<Integer, Collection<VariantGraph.Vertex>>> rowIt = ranking.getByRank().asMap() .entrySet().iterator(); rowIt.hasNext();) { final Map.Entry<Integer, Collection<VariantGraph.Vertex>> row = rowIt.next(); final int rank = row.getKey(); final Collection<VariantGraph.Vertex> vertices = row.getValue(); if (vertices.size() == 1 && Iterables.getOnlyElement(vertices).tokens().isEmpty()) { // skip start and end vertex continue; } // spreading vertices with same rank according to their registered transpositions final Multimap<Integer, VariantGraph.Vertex> verticesByTranspositionRank = HashMultimap.create(); for (VariantGraph.Vertex v : vertices) { int transpositionRank = 0; for (VariantGraph.Transposition transposition : v.transpositions()) { for (VariantGraph.Vertex tv : transposition) { transpositionRank += (ranking.apply(tv).intValue() - rank); } } verticesByTranspositionRank.put(transpositionRank, v); } // render segments for (Iterator<Integer> transpositionRankIt = Ordering.natural() .immutableSortedCopy(verticesByTranspositionRank.keySet()).iterator(); transpositionRankIt .hasNext();) { final Multimap<Witness, Token> tokensByWitness = HashMultimap.create(); for (VariantGraph.Vertex v : verticesByTranspositionRank.get(transpositionRankIt.next())) { for (Token token : v.tokens()) { tokensByWitness.put(token.getWitness(), token); } } final SortedMap<Witness, Iterable<Token>> cellContents = Maps.newTreeMap(Witness.SIGIL_COMPARATOR); for (Witness witness : allWitnesses) { cellContents.put(witness, tokensByWitness.containsKey(witness) ? Iterables.unmodifiableIterable(tokensByWitness.get(witness)) : Collections.<Token>emptySet()); } callback.segment(cellContents); } } callback.end(); }
From source file:org.ambraproject.wombat.freemarker.ReplaceParametersDirective.java
@VisibleForTesting static Multimap<String, String> replaceParameters(SimpleHash parameterMap, Multimap<String, TemplateModel> replacements) throws TemplateException { Multimap<String, String> result = HashMultimap.create(); // The map is passed in as a Map<String, String[]>, but Freemarker doesn't support generics // (and wraps the map in its own data structure). Map map = parameterMap.toMap(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String[] values = (String[]) entry.getValue(); for (String value : values) { result.put((String) entry.getKey(), value); }//from ww w .j a v a 2 s.co m } for (Map.Entry<String, Collection<TemplateModel>> replacementEntry : replacements.asMap().entrySet()) { Collection<String> replacementValues = Collections2.transform(replacementEntry.getValue(), Object::toString); result.replaceValues(replacementEntry.getKey(), replacementValues); } return ImmutableSetMultimap.copyOf(result); }
From source file:org.apache.hadoop.hbase.snapshot.TakeSnapshotUtils.java
/** * @param logdir// w w w .j a v a 2 s . co m * @param toInclude list of servers to include. If empty or null, returns all servers * @return maps of servers to all their log files. If there is no log directory, returns * <tt>null</tt> */ private static Multimap<String, String> getMapOfServersAndLogs(FileSystem fs, Path logdir, Collection<String> toInclude) throws IOException { // create a path filter based on the passed directories to include PathFilter filter = toInclude == null || toInclude.size() == 0 ? null : new MatchesDirectoryNames(toInclude); // get all the expected directories FileStatus[] serverLogDirs = FSUtils.listStatus(fs, logdir, filter); if (serverLogDirs == null) return null; // map those into a multimap of servername -> [log files] Multimap<String, String> map = HashMultimap.create(); for (FileStatus server : serverLogDirs) { FileStatus[] serverLogs = FSUtils.listStatus(fs, server.getPath(), null); if (serverLogs == null) continue; for (FileStatus log : serverLogs) { map.put(server.getPath().getName(), log.getPath().getName()); } } return map; }
From source file:com.eucalyptus.blockstorage.VolumeUpdateEventListener.java
static void update() { final Multimap<String, Volume> partitionVolumeMap = HashMultimap.create(); try (final TransactionResource tx = Entities.readOnlyDistinctTransactionFor(Volume.class)) { for (final Volume v : Entities.query(Volume.named(null, null))) { partitionVolumeMap.put(v.getPartition().intern(), v); }/*from w w w .j av a2 s . co m*/ } catch (final Exception ex) { Logs.extreme().error(ex, ex); } final Map<String, Collection<Volume>> volumesByPartition = ImmutableMap.copyOf(partitionVolumeMap.asMap()); final Map<String, Supplier<Map<String, StorageVolume>>> scVolumesByPartition = Maps.newHashMap(); for (final String partition : volumesByPartition.keySet()) { scVolumesByPartition.put(partition, updateVolumesInPartition(partition));//TODO:GRZE: restoring volume state } for (final String partition : volumesByPartition.keySet()) { try { final Map<String, StorageVolume> idStorageVolumeMap = scVolumesByPartition.get(partition).get(); for (final Volume v : volumesByPartition.get(partition)) { try { final StorageVolume storageVolume = idStorageVolumeMap.get(v.getDisplayName()); if (pendingUpdates.putIfAbsent(v.getDisplayName(), System.currentTimeMillis()) == null) try { Threads.enqueue(Storage.class, VolumeUpdateEventListener.class, (Runtime.getRuntime().availableProcessors() * 2) + 1, new Callable<Void>() { @Override public Void call() throws Exception { try { volumeStateUpdate(v, storageVolume); } finally { pendingUpdates.remove(v.getDisplayName()); } return null; } }); } catch (Throwable t) { pendingUpdates.remove(v.getDisplayName()); throw Throwables.propagate(t); } } catch (final Exception ex) { LOG.error(ex); Logs.extreme().error(ex, ex); } } } catch (final Exception ex) { LOG.error(ex); Logs.extreme().error(ex, ex); } } }
From source file:org.onos.yangtools.yang.parser.repo.DependencyResolver.java
public static DependencyResolver create(final Map<SourceIdentifier, YangModelDependencyInfo> depInfo) { final Collection<SourceIdentifier> resolved = new ArrayList<>(depInfo.size()); final Collection<SourceIdentifier> pending = new ArrayList<>(depInfo.keySet()); final Map<SourceIdentifier, BelongsToDependency> submodules = Maps.newHashMap(); boolean progress; do {/*from w w w .j a va 2 s .co m*/ progress = false; final Iterator<SourceIdentifier> it = pending.iterator(); while (it.hasNext()) { final SourceIdentifier id = it.next(); final YangModelDependencyInfo dep = depInfo.get(id); boolean okay = true; final Set<ModuleImport> dependencies = dep.getDependencies(); // in case of submodule, remember belongs to if (dep instanceof YangModelDependencyInfo.SubmoduleDependencyInfo) { final String parent = ((YangModelDependencyInfo.SubmoduleDependencyInfo) dep).getParentModule(); submodules.put(id, new BelongsToDependency(parent)); } for (final ModuleImport mi : dependencies) { if (!isKnown(resolved, mi)) { LOG.debug("Source {} is missing import {}", id, mi); okay = false; break; } } if (okay) { LOG.debug("Resolved source {}", id); resolved.add(id); it.remove(); progress = true; } } } while (progress); /// Additional check only for belongs-to statement for (final Entry<SourceIdentifier, BelongsToDependency> submodule : submodules.entrySet()) { final BelongsToDependency belongs = submodule.getValue(); final SourceIdentifier sourceIdentifier = submodule.getKey(); if (!isKnown(resolved, belongs)) { LOG.debug("Source {} is missing parent {}", sourceIdentifier, belongs); pending.add(sourceIdentifier); resolved.remove(sourceIdentifier); } } if (!pending.isEmpty()) { final Multimap<SourceIdentifier, ModuleImport> imports = ArrayListMultimap.create(); for (final SourceIdentifier id : pending) { final YangModelDependencyInfo dep = depInfo.get(id); for (final ModuleImport mi : dep.getDependencies()) { if (!isKnown(pending, mi) && !isKnown(resolved, mi)) { imports.put(id, mi); } } } return new DependencyResolver(resolved, pending, imports); } else { return new DependencyResolver(resolved, Collections.<SourceIdentifier>emptyList(), ImmutableMultimap.<SourceIdentifier, ModuleImport>of()); } }
From source file:de.csenk.gwt.commons.bean.rebind.observe.ObservableBeanModel.java
/** * @param logger // ww w. j a va 2 s . co m * @param methods * @param typeOracle * @return * @throws UnableToCompleteException */ private static Map<String, ObservableBeanPropertyModel> modelProperties(TreeLogger logger, Set<ObservableBeanMethodModel> methods, TypeOracle typeOracle) throws UnableToCompleteException { final Multimap<String, ObservableBeanMethodModel> associatedMethods = LinkedListMultimap.create(); for (ObservableBeanMethodModel methodModel : methods) { final JBeanMethod action = methodModel.getAction(); if (action != JBeanMethod.SET && action != JBeanMethod.GET) continue; final String propertyName = action.inferName(methodModel.getMethod()); associatedMethods.put(propertyName, methodModel); } final Map<String, ObservableBeanPropertyModel> properties = Maps.newHashMap(); for (String propertyName : associatedMethods.keySet()) { if (properties.containsKey(propertyName)) die(logger, "Multiple getters/setters for property %s. Check spelling and for correct camel case.", propertyName); final ObservableBeanMethodModel[] propertyAccessors = Iterables .toArray(associatedMethods.get(propertyName), ObservableBeanMethodModel.class); final JType propertyType = determinePropertyType(propertyAccessors[0], typeOracle); properties.put(propertyName, ObservableBeanPropertyModel.create(propertyName, propertyType, propertyAccessors)); } return ImmutableMap.copyOf(properties); }
From source file:org.terasology.documentation.apiScraper.CompleteApiScraper.java
/** * Adds interface or class and their methods and constructors to api * are also added.//from w w w . java 2 s . co m * @param category where the apiClass belongs * @param apiClass the class or interface to be added * @param api that maps category to classes/interface/methods */ private static void addToApi(String category, Class<?> apiClass, Multimap<String, String> api) { String className = apiClass.getName(); String type; if (apiClass.isInterface()) { type = " (INTERFACE)"; } else { int modifier = apiClass.getModifiers(); if (Modifier.isAbstract(modifier)) { type = " (ABSTRACT CLASS)"; } else { type = " (CLASS)"; } } api.put(category, className + type); //Add current apiClass's constructors Constructor[] constructors = apiClass.getDeclaredConstructors(); for (Constructor constructor : constructors) { api.put(category, " - " + constructor.getName() + " (CONSTRUCTOR)"); api.put(category, " -- " + Arrays.toString(constructor.getParameterTypes()) + " (PARAMETERS)"); } //Add current apiClass's methods Method[] methods = apiClass.getDeclaredMethods(); for (Method method : methods) { if (!method.isDefault() && !method.isBridge() && !method.isSynthetic()) { //Check if it's an abstract method int modifier = method.getModifiers(); if (Modifier.isAbstract(modifier)) { type = " (ABSTRACT METHOD)"; } else { type = " (METHOD)"; } //Adds method's information api.put(category, " - " + method.getName() + type); api.put(category, " -- " + method.getReturnType() + " (RETURN)"); api.put(category, " -- " + Arrays.toString(method.getParameterTypes()) + " (PARAMETERS)"); api.put(category, " -- " + Arrays.toString(method.getExceptionTypes()) + " (EXCEPTIONS)"); } else if (method.isDefault() && apiClass.isInterface()) { api.put(category, " - " + method.getName() + " (DEFAULT METHOD)"); api.put(category, " -- " + method.getReturnType() + " (RETURN)"); api.put(category, " -- " + Arrays.toString(method.getParameterTypes()) + " (PARAMETERS)"); api.put(category, " -- " + Arrays.toString(method.getExceptionTypes()) + " (EXCEPTIONS)"); } } }
From source file:net.sourcedestination.sai.comparison.matching.MatchingGenerator.java
public static Multimap<Integer, Integer> getNodeMatchingPossibilities(final FeatureSetCompatibilityChecker fscc, Graph g1, Graph g2) {/*from ww w . ja v a 2 s. com*/ Multimap<Integer, Integer> possibilities = HashMultimap.create(); g1.getNodeIDs().forEach(n1 -> { g2.getNodeIDs().forEach(n2 -> { if (fscc.apply(g1.getNodeFeatures(n1).collect(toSet()), g2.getNodeFeatures(n2).collect(toSet()))) possibilities.put(n1, n2); }); }); return possibilities; }
From source file:fr.letroll.ttorrentandroid.tracker.TrackerService.java
private static void parseParam(@Nonnull Multimap<String, String> params, @Nonnull String key, @CheckForNull String value) { try {/*from www. j a va 2 s .c o m*/ if (value != null) value = URLDecoder.decode(value, Torrent.BYTE_ENCODING_NAME); else value = ""; params.put(key, value); } catch (UnsupportedEncodingException uee) { // Ignore, act like parameter was not there if (LOG.isDebugEnabled()) LOG.debug("Could not decode {}", value); } }
From source file:com.android.tools.idea.editors.theme.attributes.AttributesGrouper.java
@NotNull private static List<TableLabel> generateLabelsForGroup(final List<EditedStyleItem> source, final List<EditedStyleItem> sink) { // A TreeMap is used to ensure the keys are sorted in alphabetical order // ArrayLists are used for values to ensure that they stay in the same order they came in Multimap<String, EditedStyleItem> classes = Multimaps.newListMultimap( new TreeMap<String, Collection<EditedStyleItem>>(), new Supplier<List<EditedStyleItem>>() { @Override/* w ww. j ava 2 s . c o m*/ public List<EditedStyleItem> get() { return new ArrayList<EditedStyleItem>(); } }); for (EditedStyleItem item : source) { String group = item.getAttrGroup(); classes.put(group, item); } final List<TableLabel> labels = new ArrayList<TableLabel>(); int offset = 0; sink.clear(); for (String group : classes.keySet()) { final int size = classes.get(group).size(); sink.addAll(classes.get(group)); if (size != 0) { labels.add(new TableLabel(group, offset)); } offset += size; } return labels; }