List of usage examples for com.google.common.collect Multimap put
boolean put(@Nullable K key, @Nullable V value);
From source file:jef.tools.collection.CollectionUtil.java
/** * MapKey?Value,Value?key//from w w w . jav a 2 s .co m * * ?Map * <pre><tt>{tom: 100},{jack: 95},{king: 88}, {mar: 77}, {jim: 88}</tt></pre> * ?map * <pre><tt>{100:[tom]}, {95:[jack]}, {88: [king,jim]}, {77:[mar]}</tt></pre> * @param <K> * @param <V> * @param map * @return A new Multimap that reverse key and value */ public static <K, V> Multimap<V, K> inverse(Map<K, V> map) { Multimap<V, K> result = ArrayListMultimap.create(); for (Entry<K, V> e : map.entrySet()) { result.put(e.getValue(), e.getKey()); } return result; }
From source file:org.glowroot.local.ui.ClasspathCache.java
private static void loadClassNamesFromJarInputStream(JarInputStream jarIn, File jarFile, Multimap<String, File> newClassNameLocations) throws IOException { JarEntry jarEntry;//from w w w. jav a 2 s.c o m while ((jarEntry = jarIn.getNextJarEntry()) != null) { if (jarEntry.isDirectory()) { continue; } String name = jarEntry.getName(); if (!name.endsWith(".class")) { continue; } String className = name.substring(0, name.lastIndexOf('.')).replace('/', '.'); newClassNameLocations.put(className, jarFile); } }
From source file:org.eclipse.incquery.validation.runtime.ValidationUtil.java
/** * @param result/* www .ja v a 2s . c om*/ * @param ce */ @SuppressWarnings("unchecked") private static void processConstraintConfigurationElement(Multimap<String, Constraint<IPatternMatch>> result, IConfigurationElement ce) { try { List<String> ids = new ArrayList<String>(); for (IConfigurationElement child : ce.getChildren()) { if (child.getName().equals("enabledForEditor")) { String id = child.getAttribute("editorId"); if (id != null && !id.equals("")) { ids.add(id); } } } Object o = ce.createExecutableExtension("class"); if (o instanceof Constraint<?>) { if (ids.isEmpty()) { ids.add("*"); } for (String id : ids) { result.put(id, (Constraint<IPatternMatch>) o); } } } catch (CoreException e) { logger.error("Error loading EMF-IncQuery Validation Constraint", e); } }
From source file:org.ow2.proactive.scheduler.authentication.ManageUsers.java
private static void updateUserGroups(String login, Collection<String> groups, Multimap<String, String> groupsMap) { if (!groups.isEmpty()) { groupsMap.removeAll(login);//from ww w . j a v a 2 s . c o m for (String group : groups) { if (!group.isEmpty()) { groupsMap.put(login, group); System.out.println("Adding group " + group + " to user " + login); } } } }
From source file:com.ardor3d.util.TextureManager.java
/** * Deletes all textures from card for a specific gl context. This will gather all texture ids believed to be on the * card for the given context and try to delete them. If a deleter is passed in, textures that are part of the * currently active context (if one is active) will be deleted immediately. If a deleter is not passed in, we do not * have an active context, or we encounter textures that are not part of the current context, then we will queue * those textures to be deleted later using the GameTaskQueueManager. * // ww w.j ava 2 s . c om * If a non null map is passed into futureStore, it will be populated with Future objects for each queued context. * These objects may be used to discover when the deletion tasks have all completed. * * @param deleter * if not null, this renderer will be used to immediately delete any textures in the currently active * context. All other textures will be queued to delete in their own contexts. * @param context * the context to delete for. * @param futureStore * if not null, this map will be populated with any Future task handles created during cleanup. */ public static void cleanAllTextures(final Renderer deleter, final RenderContext context, final Map<Object, Future<Void>> futureStore) { // gather up expired textures... these don't exist in our cache Multimap<Object, Integer> idMap = gatherGCdIds(); final Object glRep = context.getGlContextRep(); // Walk through the cached items and gather those too. for (final TextureKey key : _tCache.keySet()) { // possibly lazy init if (idMap == null) { idMap = ArrayListMultimap.create(); } final Integer id = key.getTextureIdForContext(glRep); if (id != 0) { idMap.put(context.getGlContextRep(), id); key.removeFromIdCache(glRep); } } // delete the ids if (!idMap.isEmpty()) { handleTextureDelete(deleter, idMap, futureStore); } }
From source file:com.google.template.soy.shared.internal.MainEntryPointUtils.java
/** * Maps output paths to indices of inputs that should be emitted to them. * * @param locale The locale for the file path, or null if not applicable. * @param outputPathFormat The format string defining how to format output file paths. * @param inputPathsPrefix The input path prefix, or empty string if none. * @param fileNodes A list of the SoyFileNodes being written. * @return A map of output file paths to their respective input indicies. *//*from w ww .j av a 2s . c om*/ public static Multimap<String, Integer> mapOutputsToSrcs(@Nullable String locale, String outputPathFormat, String inputPathsPrefix, ImmutableList<SoyFileNode> fileNodes) { Multimap<String, Integer> outputs = ArrayListMultimap.create(); // First, check that the parent directories for all output files exist, and group the output // files by the inputs that go there. // This means that the compiled source from multiple input files might be written to a single // output file, as is the case when there are multiple inputs, and the output format string // contains no wildcards. for (int i = 0; i < fileNodes.size(); ++i) { SoyFileNode inputFile = fileNodes.get(i); String inputFilePath = inputFile.getFilePath(); String outputFilePath = MainEntryPointUtils.buildFilePath(outputPathFormat, locale, inputFilePath, inputPathsPrefix); BaseUtils.ensureDirsExistInPath(outputFilePath); outputs.put(outputFilePath, i); } return outputs; }
From source file:gr.forth.ics.swkm.model2.importer.DbSynchronizer.java
static DbSynchronizer forModel(Model model) throws SQLException { Collection<Uri> resources = Sets.newHashSet(); for (Resource r : model.resources()) { resources.add(r.getUri());//from w w w. j av a 2s. c o m } resources.add(RdfSchema.RESOURCE); resources.add(RdfSchema.CLASS); /* * To find a set of resources, three steps are taken: * 1) Load matching classes, metaclasses, metaproperties * 2) Load matching properties * 3) Load domains and ranges of loaded properties */ //multiple post Ids can be mapped to different resources, because labels //are disjoint for different types, for example both a class *and* a property //may exist where both have their post Ids = 405 Map<TypedId, StoredResource> storedResources = Maps.newHashMap(); Multimap<String, String> namesBySpace = HashMultimap.create(); for (Uri uri : resources) { namesBySpace.put(uri.getNamespaceUri().toString(Delimiter.WITH), uri.getLocalName()); } //Step 1: Load matching classes, metaclasses, metaproperties /* * Note: SUBCLASS table, as well the other similar ones, have multiple rows per id: * one row per direct ancestor of that resource. So when we query that table to find * the resource's index, multiple rows can be returned, and we convert the result * from bag-semantics to set-semantics. */ //Input needed: [localNames, ns] * 3 PreparedStatement classesOrMetatypes = Jdbc.prepared( //classes "SELECT DISTINCT c.att2, sc.att2, c.att0, 1 " + //localName, index, post "FROM t" + DbConstants.getIdFor(RdfSchema.CLASS) + " c, NAMESPACE ns, SUBCLASS sc " + "WHERE c.att2 = ANY(?) AND c.att1 = ns.att0 AND ns.att1 = ? AND c.att0 = sc.att0 " + "UNION ALL " + //metaclasses "SELECT DISTINCT mc.att2, smc.att2, mc.att0, 2 " + //localName, index, post "FROM METACLASS mc, NAMESPACE ns, SUBMETACLASS smc " + "WHERE mc.att2 = ANY(?) AND mc.att1 = ns.att0 AND ns.att1 = ? AND smc.att0 = mc.att0 " + "UNION ALL " + //metaproperties "SELECT DISTINCT mc.att2, smp.att2, mc.att0, 3 " + //localName, index, post "FROM METACLASS mc, NAMESPACE ns, SUBMETAPROPERTY smp " + "WHERE mc.att2 = ANY(?) AND mc.att1 = ns.att0 AND ns.att1 = ? AND smp.att0 = mc.att0"); Iterator<String> nsIterator = namesBySpace.keySet().iterator(); while (nsIterator.hasNext()) { String ns = nsIterator.next(); Collection<String> localNames = namesBySpace.get(ns); Array array = Jdbc.connection().createArrayOf("text", localNames.toArray()); for (int i = 1; i < 6; i += 2) { classesOrMetatypes.setArray(i, array); classesOrMetatypes.setString(i + 1, ns); } ResultSet rs = classesOrMetatypes.executeQuery(); while (rs.next()) { final String localName = rs.getString(1); final int index = rs.getInt(2); final int post = rs.getInt(3); final RdfType type; switch (rs.getInt(4)) { case 1: type = RdfType.CLASS; break; case 2: type = RdfType.METACLASS; break; case 3: type = RdfType.METAPROPERTY; break; default: throw new AssertionError(); } storedResources.put(new TypedId(type, post), new StoredResource(new Uri(ns, localName), new Interval(index, post), type)); //don't search this localName in properties, we already found it here //caution: if localNames becomes empty, it will remove its entry, //thus would interfere with the keySet iteration if (localNames.size() == 1 && localNames.contains(localName)) { nsIterator.remove(); break; //done with this namespace } localNames.remove(localName); } rs.close(); } //Step 2: Load matching properties Map<Integer, StoredProperty> storedProperties = Maps.newHashMap(); //Input needed: [localNames, ns] PreparedStatement properties = Jdbc.prepared( //localName, index, post, domainId, domainKind, rangeId, rangeKind "SELECT DISTINCT p.att2, sp.att2, p.att0, p.att3, p.att5, p.att4, p.att6 " + "FROM t" + DbConstants.getIdFor(Rdf.PROPERTY) + " p, NAMESPACE ns, SUBPROPERTY sp " + "WHERE p.att2 = ANY(?) AND p.att1 = ns.att0 AND ns.att1 = ? AND p.att0 = sp.att0"); //storedResources are only given as an optimization KindsAnalyzer kindsAnalyzer = new KindsAnalyzer(storedResources); for (String ns : namesBySpace.keySet()) { Collection<String> localNames = namesBySpace.get(ns); Array array = Jdbc.connection().createArrayOf("text", localNames.toArray()); properties.setArray(1, array); properties.setString(2, ns); ResultSet rs = properties.executeQuery(); while (rs.next()) { final String localName = rs.getString(1); final int index = rs.getInt(2); final int post = rs.getInt(3); final int domainId = rs.getInt(4); final int domainKind = rs.getInt(5); final int rangeId = rs.getInt(6); final int rangeKind = rs.getInt(7); storedProperties.put(post, new StoredProperty(new Uri(ns, localName), new Interval(index, post), domainId, domainKind, rangeId, rangeKind)); kindsAnalyzer.recordResourceIdAndKind(domainId, domainKind); kindsAnalyzer.recordResourceIdAndKind(rangeId, rangeKind); } rs.close(); } //Step 3: Load domains and ranges of loaded properties if (!kindsAnalyzer.getClassIds().isEmpty()) { //load classes which were domain or range of some property //Input needed: [id] PreparedStatement classesById = Jdbc.prepared("SELECT DISTINCT ns.att1, c.att2, sc.att2, c.att0 " + //ns, localName, index, post "FROM t" + DbConstants.getIdFor(RdfSchema.CLASS) + " c, NAMESPACE ns, SUBCLASS sc " + "WHERE c.att1 = ns.att0 AND c.att0 = ANY(?) AND sc.att0 = c.att0", Jdbc.connection().createArrayOf("int", kindsAnalyzer.getClassIds().toArray())); ResultSet rs = classesById.executeQuery(); while (rs.next()) { final String ns = rs.getString(1); final String localName = rs.getString(2); final int index = rs.getInt(3); final int post = rs.getInt(4); storedResources.put(new TypedId(RdfType.CLASS, post), new StoredResource(new Uri(ns, localName), new Interval(index, post), RdfType.CLASS)); } rs.close(); } if (!kindsAnalyzer.getMetatypeIds().isEmpty()) { //load metaclasses/metaproperties which were domain or range of some property //Input needed: [id] PreparedStatement metaclassesById = Jdbc .prepared("SELECT DISTINCT ns.att1, c.att2, sc.att2, c.att0, 1 " + //ns, localName, index, post "FROM METACLASS c, NAMESPACE ns, SUBMETACLASS sc " + "WHERE c.att1 = ns.att0 AND c.att0 = ANY(?) AND sc.att0 = c.att0 " + "UNION ALL " + "SELECT DISTINCT ns.att1, c.att2, sc.att2, c.att0, 2 " + //ns, localName, index, post "FROM METACLASS c, NAMESPACE ns, SUBMETAPROPERTY sc " + "WHERE c.att1 = ns.att0 AND c.att0 = ANY(?) AND sc.att0 = c.att0 "); Array ids = Jdbc.connection().createArrayOf("int", kindsAnalyzer.getMetatypeIds().toArray()); metaclassesById.setArray(1, ids); metaclassesById.setArray(2, ids); ResultSet rs = metaclassesById.executeQuery(); while (rs.next()) { final String ns = rs.getString(1); final String localName = rs.getString(2); final int index = rs.getInt(3); final int post = rs.getInt(4); final RdfType type; switch (rs.getInt(5)) { case 1: type = RdfType.METACLASS; break; case 2: type = RdfType.METAPROPERTY; break; default: throw new AssertionError(); } storedResources.put(new TypedId(type, post), new StoredResource(new Uri(ns, localName), new Interval(index, post), type)); } rs.close(); } return new DbSynchronizer(model, storedResources, storedProperties, kindsAnalyzer.getVirtualIds()); }
From source file:edu.uci.ics.sourcerer.tools.java.component.identifier.internal.ClusterIdentifier.java
public static ClusterCollection identifyClusters(JarCollection jars) { TaskProgressLogger task = TaskProgressLogger.get(); task.start("Identifying core clusters in " + jars.size() + " jar files"); task.report("Compatibility threshold: " + COMPATIBILITY_THRESHOLD.getValue()); Multimap<VersionedFqnNode, Cluster> tempClusterMap = ArrayListMultimap.create(); task.start("Performing post-order traversal of FQN suffix tree", "FQN fragments visited", 100000); // Explore the tree in post-order int clusterCount = 0; for (VersionedFqnNode fragment : jars.getRoot().getPostOrderIterable()) { task.progress("%d FQN fragments visited (" + clusterCount + " clusters) in %s"); // If there are no children, then make it its own single-fqn library if (!fragment.hasChildren()) { Cluster cluster = Cluster.create(fragment); // Store it in the map for processing with the parent tempClusterMap.put(fragment, cluster); clusterCount++;/*from ww w . j a v a 2 s. c om*/ } else { // Start merging children for (VersionedFqnNode child : fragment.getChildren()) { for (Cluster childCluster : tempClusterMap.get(child)) { LinkedList<Cluster> candidates = new LinkedList<>(); // Check to see if it can be merged with any of the // libraries currently associated with the parent for (Cluster merge : tempClusterMap.get(fragment)) { if (areCompatible(merge, childCluster)) { candidates.add(merge); } } if (candidates.size() == 0) { // If nothing was found, promote the library tempClusterMap.put(fragment, childCluster); } else if (candidates.size() == 1) { // If one was found, merge in the child Cluster candidate = candidates.getFirst(); candidate.mergeCore(childCluster); clusterCount--; } else { // This else will never be hit for threshold 1 // TODO Change this for lower thresholds // If more than one was found, promote the library tempClusterMap.put(fragment, childCluster); } } // Clear the entry for this child fragment tempClusterMap.removeAll(child); } } } task.finish(); task.report("Identified " + clusterCount + " core clusters"); task.finish(); return ClusterCollection.create(tempClusterMap.get(jars.getRoot())); }
From source file:com.facebook.presto.execution.scheduler.NodeScheduler.java
public static SplitPlacementResult selectDistributionNodes(NodeMap nodeMap, NodeTaskMap nodeTaskMap, int maxSplitsPerNode, int maxPendingSplitsPerTask, Set<Split> splits, List<RemoteTask> existingTasks, NodePartitionMap partitioning) { Multimap<Node, Split> assignments = HashMultimap.create(); NodeAssignmentStats assignmentStats = new NodeAssignmentStats(nodeTaskMap, nodeMap, existingTasks); Set<Node> blockedNodes = new HashSet<>(); for (Split split : splits) { // node placement is forced by the partitioning Node node = partitioning.getNode(split); // if node is full, don't schedule now, which will push back on the scheduling of splits if (assignmentStats.getTotalSplitCount(node) < maxSplitsPerNode || assignmentStats.getQueuedSplitCountForStage(node) < maxPendingSplitsPerTask) { assignments.put(node, split); assignmentStats.addAssignedSplit(node); } else {/* w w w . j a va2s .c o m*/ blockedNodes.add(node); } } ListenableFuture<?> blocked = toWhenHasSplitQueueSpaceFuture(blockedNodes, existingTasks, calculateLowWatermark(maxPendingSplitsPerTask)); return new SplitPlacementResult(blocked, ImmutableMultimap.copyOf(assignments)); }
From source file:jef.tools.collection.CollectionUtil.java
/** * // ww w. j a va 2 s . c o m * * @param collection ?? * @param function ?Key * @return */ public static <T, A> Multimap<A, T> groupBy(Collection<T> collection, Function<T, A> function) { Multimap<A, T> result = ArrayListMultimap.create(); for (T value : collection) { A attrib = function.apply(value); result.put(attrib, value); } return result; }