List of usage examples for java.util Set retainAll
boolean retainAll(Collection<?> c);
From source file:org.alfresco.module.org_alfresco_module_rm.action.impl.DestroyAction.java
/** * Clear all the content properties//from ww w. java 2s . c om * * @param nodeRef */ private void clearAllContent(NodeRef nodeRef) { Set<QName> props = this.getNodeService().getProperties(nodeRef).keySet(); props.retainAll(this.getDictionaryService().getAllProperties(DataTypeDefinition.CONTENT)); for (QName prop : props) { // Clear the content clearContent(nodeRef, prop); // Remove the property this.getNodeService().removeProperty(nodeRef, prop); } }
From source file:com.redhat.rhn.frontend.action.rhnpackage.PackageDetailsAction.java
/** {@inheritDoc} */ public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) {/* w w w. j a v a 2 s . co m*/ RequestContext requestContext = new RequestContext(request); User user = requestContext.getCurrentUser(); //If this is an easy one and we have the pid if (request.getParameter("pid") != null) { long pid = requestContext.getRequiredParam("pid"); Package pkg = PackageFactory.lookupByIdAndUser(pid, user); // show permission error if pid is invalid like we did before if (pkg == null) { throw new PermissionException("Invalid pid"); } request.setAttribute("type", "rpm"); request.setAttribute(PACKAGE_NAME, pkg.getFilename()); if (!pkg.getPackageKeys().isEmpty()) { request.setAttribute(PACKAGE_KEY, pkg.getPackageKeys().iterator().next().getKey()); } boolean isDebug = pkg.getPackageName().getName().contains("debuginfo"); request.setAttribute("isDebuginfo", isDebug); if (!isDebug) { Package debugPkg = PackageManager.findDebugInfo(user, pkg); String ftpUrl = PackageManager.generateFtpDebugPath(pkg); if (debugPkg != null) { request.setAttribute("debugUrl", DownloadManager.getPackageDownloadPath(debugPkg, user)); } else if (ftpUrl != null) { request.setAttribute("debugUrl", ftpUrl); request.setAttribute("debugFtp", true); } } if (DownloadManager.isFileAvailable(pkg.getPath())) { request.setAttribute("url", DownloadManager.getPackageDownloadPath(pkg, user)); } List<PackageSource> src = PackageFactory.lookupPackageSources(pkg); if (!src.isEmpty() && DownloadManager.isFileAvailable(src.get(0).getPath())) { request.setAttribute("srpm_url", DownloadManager.getPackageSourceDownloadPath(pkg, src.get(0), user)); request.setAttribute("srpm_path", src.get(0).getFile()); } // remove references to channels we can't see Set<Channel> channels = new HashSet<Channel>(pkg.getChannels()); channels.retainAll(ChannelFactory.getAccessibleChannelsByOrg(user.getOrg().getId())); request.setAttribute("channels", channels); request.setAttribute("pack", pkg); // description can be null. if (pkg.getDescription() != null) { String description = StringEscapeUtils.escapeHtml(pkg.getDescription()); request.setAttribute("description", description.replace("\n", "<BR>\n")); } else { request.setAttribute("description", pkg.getDescription()); } request.setAttribute("packArches", PackageFactory.findPackagesWithDifferentArch(pkg)); request.setAttribute("pid", pid); request.setAttribute("erratumEmpty", pkg.getPublishedErrata().isEmpty()); request.setAttribute("erratum", pkg.getPublishedErrata()); return mapping.findForward(RhnHelper.DEFAULT_FORWARD); } PackageListItem item = PackageListItem.parse(request.getParameter("id_combo")); Package pkg; long nameId = item.getIdOne(); long evrId = item.getIdTwo(); long archId = 0; if (item.getIdThree() != null) { archId = item.getIdThree(); } Long cid = requestContext.getParamAsLong("cid"); Long sid = requestContext.getParamAsLong("sid"); if (cid != null) { pkg = PackageManager.guestimatePackageByChannel(cid, nameId, evrId, user.getOrg()); } else if (sid != null) { pkg = PackageManager.guestimatePackageBySystem(sid, nameId, evrId, archId, user.getOrg()); } else { throw new BadParameterException("pid, cid, or sid"); } // show permission error if pid is invalid like we did before if (pkg == null) { throw new PermissionException("Invalid id_combo and cid/sid"); } Map<String, Object> params = new HashMap<String, Object>(); params.put("pid", pkg.getId()); return getStrutsDelegate().forwardParams(mapping.findForward("package"), params); }
From source file:org.openmrs.module.amrsreports.reporting.data.evaluator.RegimenHistoryDataEvaluator.java
private List<Regimen> findPotentialRegimens(DrugSnapshot ds, String ageRange) { List<Regimen> results = new ArrayList<Regimen>(); for (Regimen r : getAllRegimens()) { if (OpenmrsUtil.nullSafeEquals(r.getAge(), ageRange)) { // if the drugs in the regimen are all contained in the incoming parameter ... Set<Concept> s = new HashSet<Concept>(r.getDrugs()); if (!s.retainAll(ds.getConcepts())) { // we have a match! results.add(r);/*from ww w . j ava2 s.c om*/ } } } return results; }
From source file:com.haulmont.cuba.web.widgets.CubaDateField.java
@Override protected void updateInternal(String newDateString, Map<String, Integer> resolutions) { // CAUTION: copied from AbstractDateField Set<String> resolutionNames = getResolutions().map(Enum::name).collect(Collectors.toSet()); resolutionNames.retainAll(resolutions.keySet()); if (!isReadOnly() && (!resolutionNames.isEmpty() || newDateString != null)) { // Old and new dates final LocalDate oldDate = getValue(); LocalDate newDate;//from w w w.j a v a 2 s . c o m String mask = StringUtils.replaceChars(getState(false).dateMask, "#U", "__"); if ("".equals(newDateString) || mask.equals(newDateString)) { newDate = null; } else { newDate = reconstructDateFromFields(resolutions, oldDate); } boolean hasChanges = !Objects.equals(dateString, newDateString) || !Objects.equals(oldDate, newDate); if (hasChanges) { dateString = newDateString; currentParseErrorMessage = null; if (newDateString == null || newDateString.isEmpty() || mask.equals(newDateString)) { setValue(newDate, true); } else { // invalid date string if (resolutions.isEmpty()) { Result<LocalDate> parsedDate = handleUnparsableDateString(dateString); parsedDate.ifOk(v -> setValue(v, true)); if (parsedDate.isError()) { dateString = null; currentParseErrorMessage = parsedDate.getMessage().orElse("Parsing error"); if (!isDifferentValue(null)) { doSetValue(null); } else { setValue(null, true); } } } else { setValue(newDate, true); } } } } }
From source file:dk.statsbiblioteket.doms.licensemodule.validation.LicenseValidator.java
public static CheckAccessForIdsOutputDTO checkAccessForIds(CheckAccessForIdsInputDTO input) throws Exception { if (input.getIds() == null || input.getIds().size() == 0) { throw new IllegalArgumentException("No ID's in input"); }/* ww w .jav a 2 s. c o m*/ //Get the query. This also validates the input GetUserQueryInputDTO inputQuery = new GetUserQueryInputDTO(); inputQuery.setAttributes(input.getAttributes()); inputQuery.setPresentationType(input.getPresentationType()); GetUserQueryOutputDTO query = getUserQuery(inputQuery); CheckAccessForIdsOutputDTO output = new CheckAccessForIdsOutputDTO(); output.setPresentationType(input.getPresentationType()); output.setQuery(query.getQuery()); ArrayList<SolrServerClient> servers = LicenseModulePropertiesLoader.SOLR_SERVERS; // merge (union) results. Set<String> filteredIdsSet = new HashSet<String>(); //Next step: use Future's to make multithreaded when we get more servers. //But currently these requests are less 10 ms for (SolrServerClient server : servers) { ArrayList<String> filteredIds = server.filterIds(input.getIds(), query.getQuery()); log.info("#filtered id for server (" + input.getPresentationType() + ") " + server.getSolrServer().getBaseURL() + " : " + filteredIds.size()); filteredIdsSet.addAll(filteredIds); } //Now we have to remove remove ID's not asked for that are here because of multivalue field. (set intersection) filteredIdsSet.retainAll(input.getIds()); output.setAccessIds(new ArrayList<String>(filteredIdsSet)); //Sanity check! if (output.getAccessIds().size() > input.getIds().size()) { throw new IllegalArgumentException( "Security problem: More Id's in output than input. Check for query injection."); } log.debug( "#query IDs=" + input.getIds().size() + " returned #filtered IDs=" + output.getAccessIds().size()); return output; }
From source file:edu.wustl.common.querysuite.queryobject.impl.QueryEntity.java
/** * TO check whether the given query entity is having matching Entity. This * is used to identify Pseudo-AND condition. Returns true if the two * entities belongs to the same class heirarchy. i.e. class heirarchy having * TABLE_PER_HEIRARCHY as inheritance strategy. * //from w w w. j a v a 2s. c o m * @param queryEntity The QueryEntity to check. * @return true if the two entities can be pseudoAnded. */ public boolean isPseudoAndedEntity(IQueryEntity queryEntity) { EntityInterface theEntityInterface = queryEntity.getDynamicExtensionsEntity(); if (entityInterface.equals(theEntityInterface)) { return true; } // check for the Parent class heirarchy. // It will check whether two entities belongs to the same Class // heirarchy having TABLE_PER_HEIRARCHY as inheritance strategy. EntityInterface parentEntity = entityInterface.getParentEntity(); EntityInterface theParentEntity = theEntityInterface.getParentEntity(); if (parentEntity != null && theParentEntity != null) { Set<EntityInterface> parentHeirarchy = getParentHeirarchy(entityInterface); // retaining common parent entities parentHeirarchy.retainAll(getParentHeirarchy(theEntityInterface)); if (!parentHeirarchy.isEmpty()) { return true; } } return false; }
From source file:com.act.reachables.CladeTraversal.java
/** * This function finds all reactions that explain the given combination of src and dst chemicals. * * @param src - The src node id./*from w w w . java 2 s.c om*/ * @param dst - The dst node id. * @return Returns a set of rxn ids where src in the substrates and dst in the products. */ public Set<Long> rxnIdsForEdge(Long src, Long dst) { Set<Long> rxnsThatProduceChem = GlobalParams.USE_RXN_CLASSES ? ActData.instance().rxnClassesThatProduceChem.get(dst) : ActData.instance().rxnsThatProduceChem.get(dst); Set<Long> rxnsThatConsumeChem = GlobalParams.USE_RXN_CLASSES ? ActData.instance().rxnClassesThatConsumeChem.get(src) : ActData.instance().rxnsThatConsumeChem.get(src); Set<Long> intersection = new HashSet<>(rxnsThatProduceChem); intersection.retainAll(rxnsThatConsumeChem); return intersection; }
From source file:dk.netarkivet.harvester.harvesting.report.BnfHarvestReport.java
/** * Post-processing happens on the scheduler side when ARC files * have been uploaded.// w ww.j a v a2 s. c o m * @param job the actual job. */ @Override public void postProcess(Job job) { ArgumentNotValid.checkNotNull(job, "job"); if (LOG.isInfoEnabled()) { LOG.info("Starting post-processing of harvest report for job " + job.getJobID()); } long startTime = System.currentTimeMillis(); long harvestObjectLimit = -1L; long harvestByteLimit = -1L; // First find if it's a full harvest job, // and if so get actual byte and object limits. if (job.isSnapshot()) { HarvestDefinitionDAO dao = HarvestDefinitionDAO.getInstance(); String harvestName = dao.getHarvestName(job.getOrigHarvestDefinitionID()); SparseFullHarvest harvest = dao.getSparseFullHarvest(harvestName); harvestObjectLimit = harvest.getMaxCountObjects(); harvestByteLimit = harvest.getMaxBytes(); } DomainDAO domDao = DomainDAO.getInstance(); Map<String, String> domConfMap = job.getDomainConfigurationMap(); // Process only domains from the harvest definition. final Set<String> harvestDomainNames = new HashSet<String>(); harvestDomainNames.addAll(getDomainNames()); harvestDomainNames.retainAll(domConfMap.keySet()); for (String domainName : harvestDomainNames) { Domain domain = domDao.read(domainName); String confName = domConfMap.get(domainName); DomainConfiguration conf = domain.getConfiguration(confName); long confByteLimit = conf.getMaxBytes(); long confObjectLimit = conf.getMaxObjects(); DomainStats ds = getOrCreateDomainStats(domainName); long actualByteCount = ds.getByteCount(); long actualObjectCount = ds.getObjectCount(); StopReason finalStopReason = ds.getStopReason(); if (harvestByteLimit > 0 && (actualByteCount >= harvestByteLimit)) { finalStopReason = StopReason.SIZE_LIMIT; } else if (harvestObjectLimit > 0 && (actualObjectCount >= harvestObjectLimit)) { finalStopReason = StopReason.OBJECT_LIMIT; } else if (confByteLimit > 0 && (actualByteCount >= confByteLimit)) { finalStopReason = StopReason.CONFIG_SIZE_LIMIT; } else if (confObjectLimit > 0 && (actualObjectCount >= confObjectLimit)) { finalStopReason = StopReason.CONFIG_OBJECT_LIMIT; } ds.setStopReason(finalStopReason); // Create the HarvestInfo object HarvestInfo hi = new HarvestInfo(job.getOrigHarvestDefinitionID(), job.getJobID(), domainName, confName, new Date(), actualByteCount, actualObjectCount, finalStopReason); // Add HarvestInfo to Domain and make data persistent // by updating DAO domain.getHistory().addHarvestInfo(hi); domDao.update(domain); } if (LOG.isInfoEnabled()) { long time = System.currentTimeMillis() - startTime; LOG.info("Finished post-processing of harvest report for job " + job.getJobID() + ", operation took " + StringUtils.formatDuration(time / TimeUtils.SECOND_IN_MILLIS)); } }
From source file:com.ggvaidya.scinames.summary.HigherStabilityView.java
private double calculateSimilarity(Set<Name> from, Set<Name> to) { // Similarity = intersection(from, to)/union(from, to) Set<Name> union = new HashSet<>(from); union.addAll(to);/*from www . j a v a 2 s .c om*/ Set<Name> intersection = new HashSet<>(from); intersection.retainAll(to); return ((double) intersection.size() / union.size()); }
From source file:org.owasp.jbrofuzz.graph.canvas.JaccardIndexChart.java
private double calculateValue(final File inputFile) { final HashSet<Character> secondSet = new HashSet<Character>(); BufferedReader inBuffReader = null; try {/*from www .j a v a2s . co m*/ inBuffReader = new BufferedReader(new FileReader(inputFile)); int counter = 0; int check = 0; int c; while (((c = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) { // If we are passed "--jbrofuzz-->\n" in the file if (check == END_SIGNATURE.length()) { secondSet.add((char) c); } // Else find "--jbrofuzz-->\n" using a counter else { // Increment the counter for each success if (c == END_SIGNATURE.charAt(check)) { check++; } else { check = 0; } } counter++; } inBuffReader.close(); } catch (final IOException e1) { System.out.println("An IOExcepiton occurred."); } finally { IOUtils.closeQuietly(inBuffReader); } // Calculate the Jaccard Index, between the 2 sets of chars final Set<Character> intersectionSet = new HashSet<Character>(firstSet); intersectionSet.retainAll(secondSet); final Set<Character> unionSet = new HashSet<Character>(firstSet); unionSet.addAll(secondSet); // The index is the ratio return ((double) intersectionSet.size() / (double) unionSet.size()); }