List of usage examples for com.google.common.collect ListMultimap removeAll
@Override List<V> removeAll(@Nullable Object key);
Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.
From source file:org.eurocarbdb.sugar.CustomBasetype.java
public String getName() { if (this.name != null) return this.name; StringBuilder stem_name = new StringBuilder(); StringBuilder substits = new StringBuilder(); for (int i = 0; i < basetypes.length; i++) { if (i != 0) stem_name.append('-'); stem_name.append(stereoConfigs[i]); stem_name.append('-'); stem_name.append(basetypes[i].name()); }//from ww w . j a v a 2s. c o m // substituents Substituent s; ListMultimap<Substituent, Integer> map = ArrayListMultimap.create(); CommonBasetype basetype_with_carbonyl = basetypes[(basetypes.length - 1)]; for (int i = 0; i < functionalGroups.size(); i++) { s = functionalGroups.get(i); if (s == OH) continue; if (s == basetype_with_carbonyl.getFunctionalGroups().get(i)) continue; map.put(s, i + 1); } List<Integer> positions; for (int i = 0; i < functionalGroups.size(); i++) { s = functionalGroups.get(i); positions = map.get(s); if (positions == null || positions.size() == 0) continue; if (substits.length() > 0) substits.append('-'); substits.append(join(",", positions)); substits.append('-'); substits.append(s.getName()); map.removeAll(s); } // superclass, if needed if (substits.length() > 0 || basetypes.length > 1) { stem_name.append('-'); stem_name.append(getSuperclass().getFullName()); } String name = (substits.length() > 0 ? substits.toString() + "-" : "") + stem_name.toString(); this.name = name; return name; }
From source file:org.ambraproject.wombat.controller.BrowseController.java
private List<TypedArticleGroup> buildArticleGroups(Site site, String issueId, List<Map<String, ?>> articles) throws IOException { // Articles grouped by their type. Order within the value lists is significant. ArticleType.Dictionary typeDictionary = ArticleType.getDictionary(site.getTheme()); ListMultimap<ArticleType, Map<String, Object>> groupedArticles = LinkedListMultimap.create(); for (Map<String, ?> article : articles) { if (!article.containsKey("revisionNumber")) continue; // Omit unpublished articles Map<String, Object> populatedArticle = new HashMap<>(article); Map<String, ?> ingestion = (Map<String, ?>) article.get("ingestion"); ArticleType articleType = typeDictionary.lookUp((String) ingestion.get("articleType")); populateRelatedArticles(populatedArticle); populateAuthors(populatedArticle, site); groupedArticles.put(articleType, populatedArticle); }/* w w w . ja v a 2s. com*/ // The article types supported by this site, in the order in which they are supposed to appear. ImmutableList<ArticleType> articleTypes = typeDictionary.getSequence(); // Produce a correctly ordered list of TypedArticleGroup, populated with the article groups. List<TypedArticleGroup> articleGroups = new ArrayList<>(articleTypes.size()); for (ArticleType articleType : articleTypes) { List<Map<String, Object>> articlesOfType = groupedArticles.removeAll(articleType); if (!articlesOfType.isEmpty()) { articleGroups.add(new TypedArticleGroup(articleType, articlesOfType)); } } // If any article groups were not matched, append them to the end. for (Map.Entry<ArticleType, List<Map<String, Object>>> entry : Multimaps.asMap(groupedArticles) .entrySet()) { ArticleType type = entry.getKey(); TypedArticleGroup group = new TypedArticleGroup(type, entry.getValue()); articleGroups.add(group); log.warn(String.format("Issue %s has articles of type \"%s\", which is not configured for %s: %s", issueId, type.getName(), site.getKey(), Lists.transform(group.articles, article -> article.get("doi")))); } return articleGroups; }
From source file:exm.stc.ic.opt.DeadCodeEliminator.java
/** * * @param logger// ww w . ja va 2 s . com * @param f * @param globalVars * @return true if changes made */ private static boolean eliminateIter(Logger logger, Function f, GlobalVars globalVars) { /* All vars defined in function blocks that could possibly be eliminated */ HashSet<Var> removeCandidates = new HashSet<Var>(); /* Set of vars that are definitely required */ HashSet<Var> needed = new HashSet<Var>(); needed.addAll(globalVars.variables()); /* List of vars that were written. Need to ensure that all variables * that are keys in writeEffect are tracked. */ List<Component> modifiedComponents = new ArrayList<Component>(); /* * Graph of dependencies from vars to other vars. If edge exists v1 -> v2 * this means that if v1 is required, then v2 is required */ ListMultimap<Var, Var> dependencyGraph = ArrayListMultimap.create(); /* Track components so that we know if a write from A may flow to B*/ ComponentGraph components = new ComponentGraph(); walkFunction(logger, f, removeCandidates, needed, dependencyGraph, modifiedComponents, components); if (logger.isTraceEnabled()) { logger.trace("Dead code elimination in function " + f.id() + "\n" + "removal candidates: " + removeCandidates + "\n" + "definitely needed: " + needed + "\n" + "dependencies: \n" + printDepGraph(dependencyGraph, 4) + "modifiedComponents: " + modifiedComponents + "\n" + "components: \n" + components); } /* * Add in component info. * Take into account that we might modify value of containing * structure, e.g. array */ for (Component written : modifiedComponents) { Set<Var> potentialAliases = components.findPotentialAliases(written); if (logger.isTraceEnabled()) { logger.trace("Modified var " + written + " potential aliases: " + potentialAliases); } for (Var maybeAffected : potentialAliases) { if (logger.isTraceEnabled()) { logger.trace("Add transitive dep " + maybeAffected + " => " + written); } // Need to keep var that we wrote the affected var through dependencyGraph.put(maybeAffected, written.var); } } if (logger.isTraceEnabled()) logger.trace("dependencies after component updates: \n" + printDepGraph(dependencyGraph, 4)); /* * Expand set of needed based on dependency graph */ StackLite<Var> workStack = new StackLite<Var>(); workStack.addAll(needed); while (!workStack.isEmpty()) { Var neededVar = workStack.pop(); // This loop converges as dependencyGraph is taken apart List<Var> deps = dependencyGraph.removeAll(neededVar); if (deps != null) { needed.addAll(deps); workStack.addAll(deps); } } removeCandidates.removeAll(needed); if (logger.isDebugEnabled()) { logger.debug("Final variables to be eliminated: " + removeCandidates); } if (removeCandidates.isEmpty()) { return false; } else { f.mainBlock().removeVars(removeCandidates); return true; } }
From source file:org.fim.internal.StateComparator.java
private void searchForDifferences() { ListMultimap<FileHash, FileState> notFoundInCurrentFileStateList = buildFileHashList( notFoundInCurrentFileState); Map<FileHash, FileState> foundInPreviousState = new HashMap<>(); List<FileState> samePreviousHashes; for (FileState fileState : addedOrModified) { if ((fileState.getFileLength() > 0) && (context.getHashMode() != dontHash) && ((samePreviousHashes = findFilesWithSameHash(fileState, previousFileStates)).size() > 0)) { FileState originalFileState = samePreviousHashes.get(0); FileHash originalFileHash = originalFileState.getFileHash(); if (notFoundInCurrentFileStateList.containsKey(originalFileHash) || foundInPreviousState.containsKey(originalFileHash)) { result.getRenamed().add(new Difference(originalFileState, fileState)); fileState.setModification(Modification.renamed); } else { if (contentChanged(originalFileState)) { result.getCopied().add(new Difference(originalFileState, fileState)); fileState.setModification(Modification.copied); } else { result.getDuplicated().add(new Difference(originalFileState, fileState)); fileState.setModification(Modification.duplicated); }/*from www .j a va 2 s .co m*/ } List<FileState> removed = notFoundInCurrentFileStateList.removeAll(originalFileHash); if (removed != null && removed.size() > 0) { // Used to check other duplicated files that have been renamed foundInPreviousState.put(originalFileHash, originalFileState); } } else { result.getAdded().add(new Difference(null, fileState)); fileState.setModification(Modification.added); } } addedOrModified.clear(); notFoundInCurrentFileState = new ArrayList<>(notFoundInCurrentFileStateList.values()); }
From source file:com.google.gerrit.server.change.ChangeJson.java
private Map<String, Collection<String>> permittedLabels(ChangeData cd) throws OrmException { ChangeControl ctl = control(cd);//from w w w . jav a2 s . c o m if (ctl == null) { return null; } LabelTypes labelTypes = ctl.getLabelTypes(); ListMultimap<String, String> permitted = LinkedListMultimap.create(); for (SubmitRecord rec : submitRecords(cd)) { if (rec.labels == null) { continue; } for (SubmitRecord.Label r : rec.labels) { LabelType type = labelTypes.byLabel(r.label); if (type == null) { continue; } PermissionRange range = ctl.getRange(Permission.forLabel(r.label)); for (LabelValue v : type.getValues()) { if (range.contains(v.getValue())) { permitted.put(r.label, v.formatValue()); } } } } List<String> toClear = Lists.newArrayListWithCapacity(permitted.keySet().size()); for (Map.Entry<String, Collection<String>> e : permitted.asMap().entrySet()) { if (isOnlyZero(e.getValue())) { toClear.add(e.getKey()); } } for (String label : toClear) { permitted.removeAll(label); } return permitted.asMap(); }
From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.GenericLogicDiscoverer.java
/** * Generic implementation for finding all the Services or Operations that have ALL the given types as inputs or outputs. * * @param entityType the MSM URI of the type of entity we are looking for. Only supports Service and Operation. * @param relationship the MSM URI of the relationship we are looking for. Only supports hasInput and hasOutput. * @param types the input/output types (modelReferences that is) we are looking for * @return a Map mapping operation/services URIs to MatchResults. *///from w ww . j av a 2s .c o m private Map<URI, MatchResult> findAll(URI entityType, URI relationship, Set<URI> types) { // Ensure that we have been given correct parameters if (types == null || types.isEmpty() || (!entityType.toASCIIString().equals(MSM.Service.getURI()) && !entityType.toASCIIString().equals(MSM.Operation.getURI())) || (!relationship.toASCIIString().equals(MSM.hasInput.getURI()) && !entityType.toASCIIString().equals(MSM.hasOutput.getURI()) && !relationship.toASCIIString().equals(SAWSDL.modelReference.getURI()))) { return ImmutableMap.of(); } // Expand the input types to get all that match enough to be consumed // The structure is: <OriginalType, MatchingType, MatchResult> Table<URI, URI, MatchResult> expandedTypes; if (relationship.toASCIIString().equals(SAWSDL.modelReference.getURI())) { expandedTypes = HashBasedTable.create(); for (URI type : types) { expandedTypes.putAll(this.conceptMatcher.listMatchesAtMostOfType(ImmutableSet.of(type), LogicConceptMatchType.Subsume)); expandedTypes.putAll( this.conceptMatcher.listMatchesOfType(ImmutableSet.of(type), LogicConceptMatchType.Exact)); } } else { expandedTypes = this.conceptMatcher.listMatchesAtLeastOfType(types, LogicConceptMatchType.Plugin); } // Track all the results in a multimap to push the details up the stack ListMultimap<URI, MatchResult> result = ArrayListMultimap.create(); // Do the intersection of those operations that can consume each of the inputs separately boolean firstTime = true; Map<URI, MatchResult> intermediateMatches; Map<URI, Map<URI, MatchResult>> rowMap = expandedTypes.rowMap(); // For each original type for (URI inputType : rowMap.keySet()) { // obtain those entities that match any of the expanded matching types intermediateMatches = findSome(entityType, relationship, rowMap.get(inputType).keySet()); if (firstTime) { // Add all entries firstTime = false; for (Map.Entry<URI, MatchResult> entry : intermediateMatches.entrySet()) { result.put(entry.getKey(), entry.getValue()); } } else { // Put all the values from the intersection Set<URI> intersection = Sets.intersection(result.keySet(), intermediateMatches.keySet()); for (URI opUri : intersection) { result.put(opUri, intermediateMatches.get(opUri)); } // Drop all the values from the difference // Use an immutable copy since the views will be changed Set<URI> difference = Sets.difference(result.keySet(), intermediateMatches.keySet()) .immutableCopy(); for (URI opUri : difference) { result.removeAll(opUri); } } } // Merge the results into a single map using Union return Maps.transformValues(result.asMap(), MatchResultsMerger.INTERSECTION); }
From source file:com.zimbra.cs.dav.resource.AddressObject.java
private static void constructContactGroupFromAppleXProps(DavContext ctxt, Account ownerAccount, VCard vcard, Contact existingContact, int folderId) { ListMultimap<String, VCardParamsAndValue> xprops = Contact .decodeUnknownVCardProps(vcard.fields.get(ContactConstants.A_vCardXProps)); String kind = VCardParamsAndValue.getFirstValue(XABSKIND, xprops); if (kind != null && kind.compareTo("group") == 0) { ContactGroup contactGroup;/*from w w w.j av a 2s . co m*/ List<VCardParamsAndValue> xabsmembers = xprops.get(XABSMEMBER); try { if (existingContact == null) { // create contactGroup = ContactGroup.init(); } else { // modify contactGroup = ContactGroup.init(existingContact, true); // remove all the contacts of type CONTACT_REF that belong to the collection same as the group ArrayList<Member> membersToRemove = new ArrayList<Member>(); for (Member member : contactGroup.getMembers()) { if (Member.Type.CONTACT_REF.equals(member.getType())) { ItemId itemId = new ItemId(member.getValue(), existingContact.getAccount().getId()); if (itemId.belongsTo(existingContact.getAccount())) { // make sure member belongs to the same collection as the group. Contact c = getContactByUID(ctxt, itemId.toString(), existingContact.getAccount(), folderId); if (c != null) { membersToRemove.add(member); } } } } for (Member member : membersToRemove) { contactGroup.removeMember(member.getType(), member.getValue()); } } for (VCardParamsAndValue memberProp : xabsmembers) { String member = memberProp.getValue(); if (member.startsWith("urn:uuid:")) { member = member.substring(9); } Contact c = getContactByUID(ctxt, member, ownerAccount, folderId); if (c != null) { // add to the group as a CONTACT_REF ItemId itemId = new ItemId(c); contactGroup.addMember(Member.Type.CONTACT_REF, itemId.toString()); } } vcard.fields.put(ContactConstants.A_type, ContactConstants.TYPE_GROUP); vcard.fields.put(ContactConstants.A_groupMember, contactGroup.encode()); // remove the Apple x-props and preserve the rest. xprops.removeAll(XABSKIND); xprops.removeAll(XABSMEMBER); vcard.fields.put(ContactConstants.A_vCardXProps, Contact.encodeUnknownVCardProps(xprops)); } catch (ServiceException e) { ZimbraLog.dav.debug("can't parse xprop %s", xabsmembers, e); } } }
From source file:org.gradle.api.internal.file.copy.NormalizingCopyActionDecorator.java
public WorkResult execute(final CopyActionProcessingStream stream) { final Set<RelativePath> visitedDirs = new HashSet<RelativePath>(); final ListMultimap<RelativePath, FileCopyDetailsInternal> pendingDirs = ArrayListMultimap.create(); WorkResult result = delegate.execute(new CopyActionProcessingStream() { public void process(final CopyActionProcessingStreamAction action) { stream.process(new CopyActionProcessingStreamAction() { public void processFile(FileCopyDetailsInternal details) { if (details.isDirectory()) { RelativePath path = details.getRelativePath(); if (!visitedDirs.contains(path)) { pendingDirs.put(path, details); }/*www . j a v a 2 s . c om*/ } else { maybeVisit(details.getRelativePath().getParent(), details.isIncludeEmptyDirs(), action); action.processFile(details); } } }); for (RelativePath path : new LinkedHashSet<RelativePath>(pendingDirs.keySet())) { List<FileCopyDetailsInternal> detailsList = new ArrayList<FileCopyDetailsInternal>( pendingDirs.get(path)); for (FileCopyDetailsInternal details : detailsList) { if (details.isIncludeEmptyDirs()) { maybeVisit(path, details.isIncludeEmptyDirs(), action); } } } visitedDirs.clear(); pendingDirs.clear(); } private void maybeVisit(RelativePath path, boolean includeEmptyDirs, CopyActionProcessingStreamAction delegateAction) { if (path == null || path.getParent() == null || !visitedDirs.add(path)) { return; } maybeVisit(path.getParent(), includeEmptyDirs, delegateAction); List<FileCopyDetailsInternal> detailsForPath = pendingDirs.removeAll(path); FileCopyDetailsInternal dir; if (detailsForPath.isEmpty()) { // TODO - this is pretty nasty, look at avoiding using a time bomb stub here dir = new StubbedFileCopyDetails(path, includeEmptyDirs, chmod); } else { dir = detailsForPath.get(0); } delegateAction.processFile(dir); } }); return result; }