List of usage examples for java.util List retainAll
boolean retainAll(Collection<?> c);
From source file:org.openecomp.sdc.be.components.impl.ServiceBusinessLogic.java
private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent( String componentUUID, String componentVersion) { // First Query Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao .getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion); if (eitherprevVerAudit.isRight()) { return Either.right(eitherprevVerAudit.right().value()); }//from ww w . ja v a 2s . c o m // Second Query Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao .getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion); if (eitherCurrVerAudit.isRight()) { return Either.right(eitherCurrVerAudit.right().value()); } List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value()); List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value()); List<Map<String, Object>> duplicateElements = new ArrayList<Map<String, Object>>(); duplicateElements.addAll(prevVerAuditList); duplicateElements.retainAll(currVerAuditList); List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<Map<String, Object>>(); joinedNonDuplicatedList.addAll(prevVerAuditList); joinedNonDuplicatedList.removeAll(duplicateElements); joinedNonDuplicatedList.addAll(currVerAuditList); return Either.left(joinedNonDuplicatedList); }
From source file:com.silverpeas.jobDomainPeas.control.JobDomainPeasSessionController.java
public boolean isGroupManagerOnGroup(String groupId) throws JobDomainPeasException { List<String> manageableGroupIds = getUserManageableGroupIds(); if (manageableGroupIds.contains(groupId)) { // Current user is directly manager of group return true; } else {/*w w w.jav a2 s.c o m*/ List<String> groupPath = m_AdminCtrl.getPathToGroup(groupId); groupPath.retainAll(manageableGroupIds); if (groupPath.size() > 0) { // Current user is at least manager of one super group of group return true; } } return false; }
From source file:opennlp.tools.apps.object_dedup.SimilarityAccessorBase.java
public DedupResult areNamesSemanticallyCloseWebMineCommonPart(String name1, String name2, String venue) { // normalize gender name1 = normalizeGenderAndOtherAttributes(name1); name2 = normalizeGenderAndOtherAttributes(name2); Boolean bShortTitlesSimilarInWebSpace = attemptShortTitlesSimilarityInWebSpace(name1, name2); if (bShortTitlesSimilarInWebSpace) return new DedupResult("Accepted as short title by web mining", 2, true); StringBuffer reason = new StringBuffer(); List<String> venueToks = removeVenuePart(TextProcessor.fastTokenize(venue.toLowerCase(), false)); LOG.info("\nComputing similarity between name = '" + name1 + "' and name = '" + name2 + "'"); // convert titles into token lists List<String> name1Tokens = removeVenuePart(TextProcessor.fastTokenize(name1.toLowerCase(), true)); List<String> name2Tokens = removeVenuePart(TextProcessor.fastTokenize(name2.toLowerCase(), true)); // applySubPhraseExtractionRule() Boolean bSameAttrib = verifyEventAttributesPost(name1Tokens, name2Tokens) && verifyEventAttributesPre(name1Tokens, name2Tokens); if (!bSameAttrib) { LOG.info("similar events but different attributes"); return new DedupResult("similar events but different attributes", 0, false); }//from www . ja va2 s. c om boolean bothSodesSuccess = applyBothSidesRuleEvent(name1, name2); if (!bothSodesSuccess) { return new DedupResult("Failed common words test for sports", 0, false); } float dist = (float) LevensteinDistanceFinder.levensteinDistance(name1, name2, 1, 10, 1, 10); if (dist < 5.1) { LOG.info("Found low LevensteinDistance for name1 and name2"); return new DedupResult("Found low LevensteinDistance", 2, true); } int nameMergeScore = getAttemptedNameMerge(name1, name2); if (nameMergeScore > 0) { LOG.info("Found low NameMerge Distance for name1 and name2"); return new DedupResult("Found low NameMerge Distance", 2, true); } // todo take into account order // form common sub-list of tokens name1Tokens.retainAll(name2Tokens); name1Tokens.removeAll(venueToks); name1Tokens.removeAll(commonWordsInEventTitles); name1Tokens.removeAll(Arrays.asList(englishPrepositions)); name1Tokens = removeDollarWordAndNonAlphaFromList(name1Tokens); // todo : to use full string measure // boundary case: too many words => just do counts float commonPortion = (float) name1Tokens.size() / (float) name2Tokens.size(); if (commonPortion > 0.8 || name1Tokens.size() >= 4) { // after typical // title words // are revomed 4 // looks OK LOG.info("Accepted since substantial common part"); return new DedupResult("Accepted since substantial common part", Math.max((int) (commonPortion * 5.0), 2), true); } // boundary case: no overlap if (name1Tokens.size() < 1) { LOG.info("Rejected since nothing in common"); return new DedupResult("Rejected since nothing in common", 0, false); } // get from list of tokens back to words to get search expression String entityExpression = name1Tokens.toString().replace('[', ' ').replace(']', ' ').replace(',', ' ') .replace(" ", " ").trim(); /* * // now try name merge reduced strings String entityExpression1 = name1TokensC.toString().replace('[', * ' ').replace(']', ' ').replace(',', ' ') .replace(" ", " ").trim(); String entityExpression2 = * name2Tokens.toString().replace('[', ' ').replace(']', ' ').replace(',', ' ') .replace(" ", " ").trim(); * * nameMergeScore = getAttemptedNameMerge(entityExpression1, entityExpression2); if (nameMergeScore>0){ * LOG.info("Found low NameMerge Distance for REDUCED name1 and name2"); return new * DedupResult("Found low NameMerge Distance REDUCED", 2, true); * * } */ // Before doing web mining, make sure overlap between titles is NOT a // set of common english words (use the vocabulary) // if all words are common, then NOT an entity if (name1Tokens.size() < 2) { boolean bCommonEnglishWord = false; for (String word : name1Tokens) { // if (stopList.isCommonWord(word) /*&& mostFrequent1000Words.isMostFrequent1000Word(word)*/) // bCommonEnglishWord = true; } if (bCommonEnglishWord) { LOG.info("Rejected common entity: common word = " + entityExpression); return new DedupResult("Rejected since common entity is common English word = " + entityExpression, 0, false); } } // accept common expression LOG.info("Formed common entity = " + entityExpression); reason.append("Formed common entity = " + entityExpression + "\n"); // now go to the web / bing api with this common expression List<HitBase> searchResult = webSearch.runSearch(entityExpression); float entityScore = 0f; if (searchResult != null) { int count = 0; for (HitBase item : searchResult) { String lookup = item.getTitle(); LOG.info("Bing hit title = '" + lookup + "'"); reason.append("Bing hit title = '" + lookup + "'\n"); if (count > 4) break; count++; // if occurrence is not capitalized then rejected, do not take // into account in score if (!isCapitalized(lookup)) { LOG.info("Rejected hit title since not capitalized"); reason.append("Rejected hit title since not capitalized\n"); continue; } /* * if (lookup.indexOf('-')>0 ){ lookup = lookup.split("-")[0]; } */ // now compute overlap between what found on the web for hit's // title and the common expression between events List<String> lookupTokens = tokenizeAndStem(lookup); lookupTokens.retainAll(stemList(name1Tokens)); if (lookupTokens.size() >= name1Tokens.size()) // increment score if found hit title is acceptable entityScore += 1.0; else { LOG.info( "Found hit title " + lookupTokens + " does not cover comonality expr = " + name1Tokens); entityScore += 0.25; } } } return new DedupResult(reason.toString(), (int) entityScore, entityScore > 1.0); }
From source file:edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.CollatedObjectPropertyTemplateModel.java
private void filterSubclasses(List<Map<String, String>> statementData) { String objectVariableName = getObjectKey(); if (objectVariableName == null) { log.error("Cannot remove duplicate statements for property " + getUri() + " because no object found to dedupe."); return;/*from w ww . j a v a 2 s . com*/ } if (log.isDebugEnabled()) { log.debug("Data before subclass filtering"); logData(statementData); } // Compile a list of the statements with most specific subclasses; // others will be removed List<Map<String, String>> filteredList = new ArrayList<Map<String, String>>(); Set<String> processedObjects = new HashSet<String>(); for (Map<String, String> outerMap : statementData) { String objectUri = outerMap.get(objectVariableName); if (processedObjects.contains(objectUri)) { continue; } processedObjects.add(objectUri); List<Map<String, String>> dataForThisObject = new ArrayList<Map<String, String>>(); //Retrieve the statements that are related to this specific object for (Map<String, String> innerMap : statementData) { if (innerMap.get(objectVariableName).equals(objectUri)) { // Subclass should at this point contain the most specific // type already dataForThisObject.add(innerMap); } } if (log.isDebugEnabled()) { log.debug("Object URI " + objectUri + " has number of statements = " + dataForThisObject.size()); } //Subclass variable should already reflect most specifick types but there may be more than one most specific type Collections.sort(dataForThisObject, new DataComparatorBySubclass()); filteredList.add(dataForThisObject.get(0)); } statementData.retainAll(filteredList); if (log.isDebugEnabled()) { log.debug("Data after subclass filtering"); logData(statementData); } }
From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java
@Override public Map<Integer, String> getAuthorizedCertificateProfileIdsToNameMap( AuthenticationToken authenticationToken) { final List<Integer> authorizedCpIds = new ArrayList<>( certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0)); // There is no reason to return a certificate profile if it is not present in one of the authorized EEPs final Collection<Integer> authorizedEepIds = endEntityProfileSession .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY); final Set<Integer> cpIdsInAuthorizedEeps = new HashSet<>(); for (final Integer eepId : authorizedEepIds) { final EndEntityProfile eep = endEntityProfileSession.getEndEntityProfile(eepId); for (final String availableCertificateProfileId : eep.getAvailableCertificateProfileIds()) { cpIdsInAuthorizedEeps.add(Integer.parseInt(availableCertificateProfileId)); }/* w ww. jav a 2 s. com*/ } authorizedCpIds.retainAll(cpIdsInAuthorizedEeps); final Map<Integer, String> idToNameMap = certificateProfileSession.getCertificateProfileIdToNameMap(); final Map<Integer, String> authorizedIdToNameMap = new HashMap<>(); for (final Integer cpId : authorizedCpIds) { authorizedIdToNameMap.put(cpId, idToNameMap.get(cpId)); } return authorizedIdToNameMap; }
From source file:de.innovationgate.utils.WGUtils.java
/** * Updates a list with the state represented by another list, with as less * changes as possible. Elements that are new in newCol will get added to * list. Elements that do not exist in newCol but exist in list will get * removed from list. Elements that both, list and newCol, contain will * remain. This method can be used to update lists that are stored via * hibernate. Just replacing the old list with a new one would result in * hibernate removing all rows from the table and re-insert all values anew. * If lists are updated with this method, hibernate can focus on the real * removements and added elements without touching unmodified values. * WARNING: Only use this when the sorting order of the list is of no * importance!/*from w ww . j av a 2s. c o m*/ * * @param list * @param newCol */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void updateList(List list, Collection newCol) { List newList = new ArrayList(newCol); list.retainAll(newList); newList.removeAll(list); list.addAll(newList); }
From source file:com.stratelia.silverpeas.pdcPeas.servlets.PdcSearchRequestRouter.java
/** * Cette methode retourne uniquement la liste contenant les silvercontent (Recherche PDC pure) * * @param alSilverContentIds - la liste de silvercontentId * @return la liste des silvercontents/*from w w w . jav a2 s . c om*/ */ private List<GlobalSilverContent> pdcSearchOnly(List<Integer> alSilverContentIds, PdcSearchSessionController pdcSC) throws Exception { SilverTrace.info("pdcPeas", "PdcSearchRequestRouter.pdcSearchOnly", "root.MSG_GEN_PARAM_VALUE", "alSilverContentIds = " + alSilverContentIds); List<GlobalSilverContent> alSilverContents = new ArrayList<GlobalSilverContent>(); if (alSilverContentIds == null || alSilverContentIds.isEmpty()) { return alSilverContents; } // la recherche PDC des rsultats. La liste qui contient les silverContentId n'est pas vide // recherche des componentId a partir de silverContentId // attention cette methode ne fonctionne que si l'on classe un document dans son instance. List<String> alInstanceIds = new ArrayList<String>(); // on rcupre la liste de instance contenant tous les documents alInstanceIds = contentManager.getInstanceId(alSilverContentIds); SilverTrace.info("pdcPeas", "PdcSearchRequestRouter.pdcSearchOnly", "root.MSG_GEN_PARAM_VALUE", "alInstanceIds = " + alInstanceIds); // une fois la liste des instanceId dfinie, on parcourt cette liste pour en retirer les // SilverContentIds // propre chaque instanceId. // Pb si entre temps, un utilisateur d-instancie un job'Peas for (int j = 0; j < alInstanceIds.size(); j++) { String instanceId = alInstanceIds.get(j); ContentPeas contentP = contentManager.getContentPeas(instanceId); // On rcupre tous les silverContentId d'un instanceId List<Integer> allSilverContentIds = contentManager.getSilverContentIdByInstanceId(instanceId); SilverTrace.info("pdcPeas", "PdcSearchRequestRouter.pdcSearchOnly", "root.MSG_GEN_PARAM_VALUE", "allSilverContentIds = " + allSilverContentIds + " in instance " + instanceId); // une fois les SilverContentId de l'instanceId rcuprs, on ne garde que ceux qui sont // dans la liste rsultat (alSilverContentIds). allSilverContentIds.retainAll(alSilverContentIds); if (contentP != null) { // we are going to search only SilverContent of this instanceId ContentInterface contentInterface = contentP.getContentInterface(); List<SilverContentInterface> silverContentTempo = contentInterface.getSilverContentById( allSilverContentIds, instanceId, pdcSC.getUserId(), contentP.getUserRoles()); if (silverContentTempo != null) { alSilverContents.addAll( transformSilverContentsToGlobalSilverContents(silverContentTempo, instanceId, pdcSC)); } } } SilverTrace.info("pdcPeas", "PdcSearchRequestRouter.pdcSearchOnly", "root.MSG_GEN_PARAM_VALUE", "silverContent size= " + alSilverContents.size()); SilverTrace.info("pdcPeas", "PdcSearchRequestRouter.pdcSearchOnly", "root.MSG_GEN_PARAM_VALUE", "alSilverContentIds = " + alSilverContentIds.toString()); return alSilverContents; }
From source file:org.silverpeas.web.jobdomain.control.JobDomainPeasSessionController.java
public boolean isGroupManagerOnGroup(String groupId) { List<String> manageableGroupIds = getUserManageableGroupIds(); if (manageableGroupIds.contains(groupId)) { // Current user is directly manager of group return true; } else {/*from w w w .j a v a 2s .com*/ List<String> groupPath = adminCtrl.getPathToGroup(groupId); groupPath.retainAll(manageableGroupIds); if (!groupPath.isEmpty()) { // Current user is at least manager of one super group of group return true; } } return false; }
From source file:org.apache.solr.cloud.OverseerCollectionProcessor.java
private static List<String> getLiveOrLiveAndCreateNodeSetList(final Set<String> liveNodes, final ZkNodeProps message, final Random random) { // TODO: add smarter options that look at the current number of cores per // node?/* www .ja v a2 s . c om*/ // for now we just go random (except when createNodeSet and createNodeSet.shuffle=false are passed in) List<String> nodeList; final String createNodeSetStr = message.getStr(CREATE_NODE_SET); final List<String> createNodeList = (createNodeSetStr == null) ? null : StrUtils.splitSmart((CREATE_NODE_SET_EMPTY.equals(createNodeSetStr) ? "" : createNodeSetStr), ",", true); if (createNodeList != null) { nodeList = new ArrayList<>(createNodeList); nodeList.retainAll(liveNodes); if (message.getBool(CREATE_NODE_SET_SHUFFLE, CREATE_NODE_SET_SHUFFLE_DEFAULT)) { Collections.shuffle(nodeList, random); } } else { nodeList = new ArrayList<>(liveNodes); Collections.shuffle(nodeList, random); } return nodeList; }
From source file:org.apache.ranger.plugin.contextenricher.RangerTagEnricher.java
private List<RangerServiceResourceMatcher> getEvaluators(RangerAccessResource resource, EnrichedServiceTags enrichedServiceTags) { if (LOG.isDebugEnabled()) { LOG.debug("==> RangerTagEnricher.getEvaluators(" + (resource != null ? resource.getAsString() : null) + ")"); }/*ww w. j a v a2s . c o m*/ List<RangerServiceResourceMatcher> ret = null; final List<RangerServiceResourceMatcher> serviceResourceMatchers = enrichedServiceTags .getServiceResourceMatchers(); final Map<String, RangerResourceTrie<RangerServiceResourceMatcher>> serviceResourceTrie = enrichedServiceTags .getServiceResourceTrie(); if (resource == null || resource.getKeys() == null || resource.getKeys().size() == 0 || serviceResourceTrie == null) { ret = serviceResourceMatchers; } else { Set<String> resourceKeys = resource.getKeys(); if (CollectionUtils.isNotEmpty(resourceKeys)) { boolean isRetModifiable = false; for (String resourceName : resourceKeys) { RangerResourceTrie<RangerServiceResourceMatcher> trie = serviceResourceTrie.get(resourceName); if (trie == null) { // if no trie exists for this resource level, ignore and continue to next level continue; } List<RangerServiceResourceMatcher> resourceEvaluators = trie .getEvaluatorsForResource(resource.getValue(resourceName)); if (CollectionUtils.isEmpty(resourceEvaluators)) { // no policies for this resource, bail out ret = null; } else if (ret == null) { // initialize ret with policies found for this resource ret = resourceEvaluators; } else { // remove matchers from ret that are not in resourceEvaluators if (isRetModifiable) { ret.retainAll(resourceEvaluators); } else { final List<RangerServiceResourceMatcher> shorterList; final List<RangerServiceResourceMatcher> longerList; if (ret.size() < resourceEvaluators.size()) { shorterList = ret; longerList = resourceEvaluators; } else { shorterList = resourceEvaluators; longerList = ret; } ret = new ArrayList<>(shorterList); ret.retainAll(longerList); isRetModifiable = true; } } if (CollectionUtils.isEmpty(ret)) { // if no matcher exists, bail out and return empty list ret = null; break; } } } } if (ret == null) { ret = Collections.emptyList(); } if (LOG.isDebugEnabled()) { LOG.debug("<== RangerTagEnricher.getEvaluators(" + (resource != null ? resource.getAsString() : null) + "): evaluatorCount=" + ret.size()); } return ret; }