List of usage examples for java.util Collection retainAll
boolean retainAll(Collection<?> c);
From source file:org.cgiar.ccafs.marlo.action.projects.ProjectLocationAction.java
@Override public void prepare() throws Exception { loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP); loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId()); projectID = Long// w w w . j av a2 s . co m .parseLong(StringUtils.trim(this.getRequest().getParameter(APConstants.PROJECT_REQUEST_ID))); if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) { transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID)); Project history = (Project) auditLogManager.getHistory(transaction); if (history != null) { project = history; } else { this.transaction = null; this.setTransaction("-1"); } } else { project = projectManager.getProjectById(projectID); } this.locationLevels(); if (project != null) { Path path = this.getAutoSaveFilePath(); if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) { BufferedReader reader = null; reader = new BufferedReader(new FileReader(path.toFile())); Gson gson = new GsonBuilder().create(); JsonObject jReader = gson.fromJson(reader, JsonObject.class); reader.close(); AutoSaveReader autoSaveReader = new AutoSaveReader(); project = (Project) autoSaveReader.readFromJson(jReader); Project projectDb = projectManager.getProjectById(project.getId()); project.getProjectInfo().setProjectEditLeader( projectDb.getProjecInfoPhase(this.getActualPhase()).isProjectEditLeader()); // project.setProjectLocations(projectDb.getProjectLocations()); project.getProjectInfo() .setAdministrative(projectDb.getProjecInfoPhase(this.getActualPhase()).getAdministrative()); if (project.getLocationsData() != null) { for (CountryLocationLevel level : project.getLocationsData()) { LocElementType elementType = locElementTypeManager.getLocElementTypeById(level.getId()); if (elementType.getId() == 2 || elementType.getCrp() != null) { level.setAllElements(elementType.getLocElements().stream().filter(le -> le.isActive()) .collect(Collectors.toList())); } } } if (project.getProjectRegions() != null) { for (ProjectLocation projectLocation : project.getProjectRegions()) { if (projectLocation.getLocElement() != null && projectLocation.getLocElement().getId() != null) { projectLocation.setLocElement( locElementManager.getLocElementById(projectLocation.getLocElement().getId())); projectLocation.setLocElementType(null); } else { projectLocation.setLocElementType(locElementTypeManager .getLocElementTypeById(projectLocation.getLocElementType().getId())); projectLocation.setLocElement(null); } } } List<CountryFundingSources> reCountryFundingSources = new ArrayList<>(); List<CountryFundingSources> coCountryFundingSources = new ArrayList<>(); if (project.getRegionFS() != null) { for (CountryFundingSources co : project.getRegionFS()) { if (co.getLocElement() != null) { co.setLocElement(locElementManager.getLocElementById(co.getLocElement().getId())); List<FundingSource> sources = fundingSourceManager.searchFundingSourcesByLocElement( projectID, co.getLocElement().getId(), this.getCurrentCycleYear(), loggedCrp.getId(), this.getActualPhase().getId()); for (FundingSource fundingSource : sources) { fundingSource.getFundingSourceInfo(this.getActualPhase()); } co.setFundingSources(sources); } else { co.setLocElementType( locElementTypeManager.getLocElementTypeById(co.getLocElementType().getId())); List<FundingSource> sources = fundingSourceManager.searchFundingSourcesByLocElementType( projectID, co.getLocElementType().getId(), this.getCurrentCycleYear(), loggedCrp.getId()); for (FundingSource fundingSource : sources) { fundingSource.getFundingSourceInfo(this.getActualPhase()); } co.setFundingSources(sources); } if (!co.isSelected()) { if (co.getLocElement() != null) { co.setSelected(this.locElementSelected(co.getLocElement().getId())); } else { co.setSelected(this.locElementTypeSelected(co.getLocElementType().getId())); } } if (!co.getFundingSources().stream() .filter(c -> c.isActive() && c.getProjectBudgets().stream() .filter(fp -> fp.isActive() && fp.getProject().isActive() && fp.getProject().getId().longValue() == projectID) .collect(Collectors.toList()).size() > 0) .collect(Collectors.toList()).isEmpty()) { reCountryFundingSources.add(co); } } } project.setRegionFS(reCountryFundingSources); if (project.getCountryFS() != null) { for (CountryFundingSources co : project.getCountryFS()) { if (co.getLocElement() != null) { co.setLocElement(locElementManager.getLocElementById(co.getLocElement().getId())); List<FundingSource> sources = fundingSourceManager.searchFundingSourcesByLocElement( projectID, co.getLocElement().getId(), this.getCurrentCycleYear(), loggedCrp.getId(), this.getActualPhase().getId()); for (FundingSource fundingSource : sources) { fundingSource.getFundingSourceInfo(this.getActualPhase()); } co.setFundingSources(new ArrayList<>(sources)); } else { co.setLocElementType( locElementTypeManager.getLocElementTypeById(co.getLocElementType().getId())); } if (!co.isSelected()) { if (co.getLocElement() != null) { co.setSelected(this.locElementSelected(co.getLocElement().getId())); } else { co.setSelected(this.locElementTypeSelected(co.getLocElementType().getId())); } } if (!co.getFundingSources().stream() .filter(c -> c.isActive() && c.getProjectBudgets().stream() .filter(fp -> fp.isActive() && fp.getProject().isActive() && fp.getProject().getId().longValue() == projectID) .collect(Collectors.toList()).size() > 0) .collect(Collectors.toList()).isEmpty()) { coCountryFundingSources.add(co); } } project.setCountryFS(coCountryFundingSources); } this.prepareFundingList(); this.setDraft(true); } else { this.setDraft(false); this.prepareFundingList(); for (CountryFundingSources locElement : project.getCountryFS()) { locElement.setSelected(this.locElementSelected(locElement.getLocElement().getId())); } for (CountryFundingSources locElement : project.getRegionFS()) { if (locElement.getLocElement() != null) { locElement.setSelected(this.locElementSelected(locElement.getLocElement().getId())); } else { locElement.setSelected(this.locElementTypeSelected(locElement.getLocElementType().getId())); } } project.setLocationsData(this.getProjectLocationsData()); project.setProjectRegions(new ArrayList<ProjectLocation>(this.getDBLocations().stream() .filter(p -> p.isActive() && p.getLocElementType() == null && p.getLocElement() != null && p.getLocElement().getLocElementType().getId().longValue() == 1 && p.getPhase() != null && p.getPhase().equals(this.getActualPhase())) .collect(Collectors.toList()))); project.getProjectRegions() .addAll(this.getDBLocations().stream() .filter(p -> p.isActive() && p.getLocElementType() != null && p.getLocElement() == null && p.getPhase().equals(this.getActualPhase())) .collect(Collectors.toList())); } } this.listScopeRegions(); Collection<LocElement> fsLocs = new ArrayList<>(); if (project.getCountryFS() == null) { project.setCountryFS(new ArrayList<>()); } if (project.getRegionFS() == null) { project.setRegionFS(new ArrayList<>()); } for (CountryFundingSources locElement : project.getCountryFS()) { fsLocs.add(locElement.getLocElement()); } if (project.getLocationsData() == null) { project.setLocationsData(new ArrayList<>()); } // Fix Ull Collection when autosave gets the suggeste country - 10/13/2017 for (CountryLocationLevel countryLocationLevel : project.getLocationsData()) { if (countryLocationLevel.getLocElements() != null) { Collection<LocElement> similar = new HashSet<LocElement>(countryLocationLevel.getLocElements()); Collection<LocElement> different = new HashSet<LocElement>(); different.addAll(countryLocationLevel.getLocElements()); different.addAll(fsLocs); similar.retainAll(fsLocs); different.removeAll(similar); countryLocationLevel.getLocElements().removeAll(similar); } } Collection<LocElement> fsLocsRegions = new ArrayList<>(); for (CountryFundingSources locElement : project.getRegionFS()) { if (locElement.getLocElement() != null) { fsLocsRegions.add(locElement.getLocElement()); } } if (project.getProjectRegions() != null) { for (ProjectLocation projectLocation : project.getProjectRegions().stream() .filter(c -> c.getLocElement() != null).collect(Collectors.toList())) { if (fsLocsRegions.contains(projectLocation.getLocElement())) { project.getProjectRegions().remove(projectLocation); } } } Collection<LocElementType> fsLocsCustomRegions = new ArrayList<>(); for (CountryFundingSources locElement : project.getRegionFS()) { if (locElement.getLocElementType() != null) { fsLocsCustomRegions.add(locElement.getLocElementType()); } } if (project.getProjectRegions() != null) { for (ProjectLocation projectLocation : project.getProjectRegions().stream() .filter(c -> c.getLocElementType() != null).collect(Collectors.toList())) { if (fsLocsCustomRegions.contains(projectLocation.getLocElementType())) { project.getProjectRegions().remove(projectLocation); } } } regionLists = new ArrayList<>(locElementManager.findAll().stream().filter( le -> le.isActive() && le.getLocElementType() != null && le.getLocElementType().getId() == 1) .collect(Collectors.toList())); Collections.sort(regionLists, (r1, r2) -> r1.getName().compareTo(r2.getName())); scopeRegionLists = new ArrayList<>(locElementTypeManager.findAll().stream() .filter(le -> le.isActive() && le.getCrp() != null && le.getCrp().equals(loggedCrp) && le.isScope()) .collect(Collectors.toList())); String params[] = { loggedCrp.getAcronym(), project.getId() + "" }; this.setBasePermission(this.getText(Permission.PROJECT_LOCATION_BASE_PERMISSION, params)); if (!project.getLocationsData().stream().filter(c -> c.getId().longValue() != 2) .collect(Collectors.toList()).isEmpty()) { region = true; } else { region = false; } if (this.isHttpPost()) { if (project.getLocationsData() != null) { project.getLocationsData().clear(); } project.getProjecInfoPhase(this.getActualPhase()).setLocationGlobal(false); if (project.getCountryFS() != null) { project.getCountryFS().clear(); } if (project.getRegionFS() != null) { project.getRegionFS().clear(); } if (project.getRegions() != null) { project.getRegions().clear(); } if (project.getProjectRegions() != null) { project.getProjectRegions().clear(); } } }
From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java
@SuppressWarnings("unchecked") @Override/*from ww w . j a v a 2 s .co m*/ public RaCertificateSearchResponse searchForCertificates(AuthenticationToken authenticationToken, RaCertificateSearchRequest request) { final RaCertificateSearchResponse response = new RaCertificateSearchResponse(); final List<Integer> authorizedLocalCaIds = new ArrayList<>( caSession.getAuthorizedCaIds(authenticationToken)); // Only search a subset of the requested CAs if requested if (!request.getCaIds().isEmpty()) { authorizedLocalCaIds.retainAll(request.getCaIds()); } final List<String> issuerDns = new ArrayList<>(); for (final int caId : authorizedLocalCaIds) { try { final String issuerDn = CertTools .stringToBCDNString(StringTools.strip(caSession.getCAInfoInternal(caId).getSubjectDN())); issuerDns.add(issuerDn); } catch (CADoesntExistsException e) { log.warn("CA went missing during search operation. " + e.getMessage()); } } if (issuerDns.isEmpty()) { // Empty response since there were no authorized CAs if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested CAs and the search request will be dropped."); } return response; } // Check Certificate Profile authorization final List<Integer> authorizedCpIds = new ArrayList<>( certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0)); final boolean accessAnyCpAvailable = authorizedCpIds .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet()); if (!request.getCpIds().isEmpty()) { authorizedCpIds.retainAll(request.getCpIds()); } if (authorizedCpIds.isEmpty()) { // Empty response since there were no authorized Certificate Profiles if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested CPs and the search request will be dropped."); } return response; } // Check End Entity Profile authorization final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY)); final boolean accessAnyEepAvailable = authorizedEepIds .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet()); if (!request.getEepIds().isEmpty()) { authorizedEepIds.retainAll(request.getEepIds()); } if (authorizedEepIds.isEmpty()) { // Empty response since there were no authorized End Entity Profiles if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested EEPs and the search request will be dropped."); } return response; } final String subjectDnSearchString = request.getSubjectDnSearchString(); final String subjectAnSearchString = request.getSubjectAnSearchString(); final String usernameSearchString = request.getUsernameSearchString(); final String serialNumberSearchStringFromDec = request.getSerialNumberSearchStringFromDec(); final String serialNumberSearchStringFromHex = request.getSerialNumberSearchStringFromHex(); final StringBuilder sb = new StringBuilder( "SELECT a.fingerprint FROM CertificateData a WHERE (a.issuerDN IN (:issuerDN))"); if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty() || !usernameSearchString.isEmpty() || !serialNumberSearchStringFromDec.isEmpty() || !serialNumberSearchStringFromHex.isEmpty()) { sb.append(" AND ("); boolean firstAppended = false; if (!subjectDnSearchString.isEmpty()) { sb.append("a.subjectDN LIKE :subjectDN"); firstAppended = true; } if (!subjectAnSearchString.isEmpty()) { if (firstAppended) { sb.append(" OR "); } else { firstAppended = true; } sb.append("a.subjectAltName LIKE :subjectAltName"); } if (!usernameSearchString.isEmpty()) { if (firstAppended) { sb.append(" OR "); } else { firstAppended = true; } sb.append("a.username LIKE :username"); } if (!serialNumberSearchStringFromDec.isEmpty()) { if (firstAppended) { sb.append(" OR "); } else { firstAppended = true; } sb.append("a.serialNumber LIKE :serialNumberDec"); } if (!serialNumberSearchStringFromHex.isEmpty()) { if (firstAppended) { sb.append(" OR "); } sb.append("a.serialNumber LIKE :serialNumberHex"); } sb.append(")"); } // NOTE: notBefore is not indexed.. we might want to disallow such search. if (request.isIssuedAfterUsed()) { sb.append(" AND (a.notBefore > :issuedAfter)"); } if (request.isIssuedBeforeUsed()) { sb.append(" AND (a.notBefore < :issuedBefore)"); } if (request.isExpiresAfterUsed()) { sb.append(" AND (a.expireDate > :expiresAfter)"); } if (request.isExpiresBeforeUsed()) { sb.append(" AND (a.expireDate < :expiresBefore)"); } // NOTE: revocationDate is not indexed.. we might want to disallow such search. if (request.isRevokedAfterUsed()) { sb.append(" AND (a.revocationDate > :revokedAfter)"); } if (request.isRevokedBeforeUsed()) { sb.append(" AND (a.revocationDate < :revokedBefore)"); } if (!request.getStatuses().isEmpty()) { sb.append(" AND (a.status IN (:status))"); if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED) || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED)) && !request.getRevocationReasons().isEmpty()) { sb.append(" AND (a.revocationReason IN (:revocationReason))"); } } // Don't constrain results to certain certificate profiles if root access is available and "any" CP is requested if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))"); } // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))"); } final Query query = entityManager.createQuery(sb.toString()); query.setParameter("issuerDN", issuerDns); if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { query.setParameter("certificateProfileId", authorizedCpIds); } if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { query.setParameter("endEntityProfileId", authorizedEepIds); } if (log.isDebugEnabled()) { log.debug(" issuerDN: " + Arrays.toString(issuerDns.toArray())); if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray())); } else { log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access."); } if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray())); } else { log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access."); } } if (!subjectDnSearchString.isEmpty()) { if (request.isSubjectDnSearchExact()) { query.setParameter("subjectDN", subjectDnSearchString); } else { query.setParameter("subjectDN", "%" + subjectDnSearchString + "%"); } } if (!subjectAnSearchString.isEmpty()) { if (request.isSubjectAnSearchExact()) { query.setParameter("subjectAltName", subjectAnSearchString); } else { query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%"); } } if (!usernameSearchString.isEmpty()) { if (request.isUsernameSearchExact()) { query.setParameter("username", usernameSearchString); } else { query.setParameter("username", "%" + usernameSearchString + "%"); } } if (!serialNumberSearchStringFromDec.isEmpty()) { query.setParameter("serialNumberDec", serialNumberSearchStringFromDec); if (log.isDebugEnabled()) { log.debug(" serialNumberDec: " + serialNumberSearchStringFromDec); } } if (!serialNumberSearchStringFromHex.isEmpty()) { query.setParameter("serialNumberHex", serialNumberSearchStringFromHex); if (log.isDebugEnabled()) { log.debug(" serialNumberHex: " + serialNumberSearchStringFromHex); } } if (request.isIssuedAfterUsed()) { query.setParameter("issuedAfter", request.getIssuedAfter()); } if (request.isIssuedBeforeUsed()) { query.setParameter("issuedBefore", request.getIssuedBefore()); } if (request.isExpiresAfterUsed()) { query.setParameter("expiresAfter", request.getExpiresAfter()); } if (request.isExpiresBeforeUsed()) { query.setParameter("expiresBefore", request.getExpiresBefore()); } if (request.isRevokedAfterUsed()) { query.setParameter("revokedAfter", request.getRevokedAfter()); } if (request.isRevokedBeforeUsed()) { query.setParameter("revokedBefore", request.getRevokedBefore()); } if (!request.getStatuses().isEmpty()) { query.setParameter("status", request.getStatuses()); if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED) || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED)) && !request.getRevocationReasons().isEmpty()) { query.setParameter("revocationReason", request.getRevocationReasons()); } } final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(), request.getMaxResults()); query.setMaxResults(maxResults); /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors: * - The hint is ignored * - A QueryTimeoutException is thrown * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back) */ final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout(); if (queryTimeout > 0L) { query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout)); } final List<String> fingerprints; try { fingerprints = query.getResultList(); for (final String fingerprint : fingerprints) { response.getCdws().add(certificateStoreSession.getCertificateData(fingerprint)); } response.setMightHaveMoreResults(fingerprints.size() == maxResults); if (log.isDebugEnabled()) { log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 " + fingerprints.size() + " results. queryTimeout=" + queryTimeout + "ms"); } } catch (QueryTimeoutException e) { // Query.toString() does not return the SQL query executed just a java object hash. If Hibernate is being used we can get it using: // query.unwrap(org.hibernate.Query.class).getQueryString() // We don't have access to hibernate when building this class though, all querying should be moved to the ejbca-entity package. // See ECA-5341 String queryString = e.getQuery().toString(); // try { // queryString = e.getQuery().unwrap(org.hibernate.Query.class).getQueryString(); // } catch (PersistenceException pe) { // log.debug("Query.unwrap(org.hibernate.Query.class) is not supported by JPA provider"); // } log.info("Requested search query by " + authenticationToken + " took too long. Query was '" + queryString + "'. " + e.getMessage()); response.setMightHaveMoreResults(true); } catch (PersistenceException e) { log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. " + e.getMessage()); response.setMightHaveMoreResults(true); } return response; }
From source file:org.sakaiproject.lessonbuildertool.service.LessonsGradeInfoProvider.java
public Map<String, List<String>> getAllExternalAssignments(String gradebookUid, Collection<String> studentIds) { //System.out.println("isassignmentgrouped lesson-builder:1788 " + isAssignmentGrouped("lesson-builder:1788")); //System.out.println("isassignmentgrouped lesson-builder:comment:7289 " + isAssignmentGrouped("lesson-builder:comment:7289")); //System.out.println("isUserInPath " + isUserInPath("c08d3ac9-c717-472a-ad91-7ce0b434f42f", lessonsAccess.getPagePaths(1788L,false),"60c04ab8-40e5-4eb6-9f8d-7006ed023109")); //System.out.println("isUserInPath " + isUserInPath("c08d3ac9-c717-472a-ad91-7ce0b434f42f", lessonsAccess.getItemPaths(7289L),"60c04ab8-40e5-4eb6-9f8d-7006ed023109")); //HashSet<String> userset = new HashSet<String>(); //userset.add("c08d3ac9-c717-472a-ad91-7ce0b434f42f"); //userset.add("9d1a25ba-4735-48c4-bd5e-ff329f9f7749"); //System.out.println("usersInPath " + usersInPath(userset, lessonsAccess.getPagePaths(1788L,false),"60c04ab8-40e5-4eb6-9f8d-7006ed023109")); //System.out.println("userInPath " + usersInPath(userset, lessonsAccess.getItemPaths(7289L),"60c04ab8-40e5-4eb6-9f8d-7006ed023109")); //System.out.println(isAssignmentVisible("lesson-builder:1788", "c08d3ac9-c717-472a-ad91-7ce0b434f42f")); //System.out.println(isAssignmentVisible("lesson-builder:comment:7289", "c08d3ac9-c717-472a-ad91-7ce0b434f42f")); //System.out.println(getExternalAssignmentsForCurrentUser("60c04ab8-40e5-4eb6-9f8d-7006ed023109")); Map<String, List<String>> allExternals = new HashMap<String, List<String>>(); String ref = "/site/" + gradebookUid; List<User> allowedUsers = securityService.unlockUsers(SimplePage.PERMISSION_LESSONBUILDER_READ, ref); if (allowedUsers.size() < 1) return allExternals; // no users allowed, nothing to do List<String> allowedIds = new ArrayList<String>(); for (User user : allowedUsers) allowedIds.add(user.getId());/* w ww.j a v a2 s.c o m*/ // remove any user without lesson builder read in the site studentIds.retainAll(allowedIds); for (String studentId : studentIds) { allExternals.put(studentId, new ArrayList<String>()); } List<SimplePageItem> externalItems = dao.findGradebookItems(gradebookUid); for (SimplePageItem item : externalItems) { Set<Path> paths = lessonsAccess.getItemPaths(item.getId()); Set<String> users = usersInPath(studentIds, paths, gradebookUid); // add this assignment to all users that are in the groups for (String userId : users) if (allExternals.containsKey(userId)) { if (item.getGradebookId() != null) allExternals.get(userId).add(item.getGradebookId()); if (item.getAltGradebook() != null) allExternals.get(userId).add(item.getAltGradebook()); } } List<SimplePage> externalPages = dao.findGradebookPages(gradebookUid); for (SimplePage page : externalPages) { Set<Path> paths = lessonsAccess.getPagePaths(page.getPageId(), false); Set<String> users = usersInPath(studentIds, paths, gradebookUid); // add this assignment to all users that are in the groups for (String userId : users) if (allExternals.containsKey(userId)) { if (page.getGradebookPoints() != null) allExternals.get(userId).add("lesson-builder:" + page.getPageId()); } } // now handle other tools. If we modified their groups, we need to find the original groups // and return the users that match those groups // find list of items we've modified // map of external ID to list of original groups for that item Map<String, ArrayList<String>> otherTools = getExternalAssigns(gradebookUid); // for each externalId for (Map.Entry<String, ArrayList<String>> entry : otherTools.entrySet()) { String externalId = entry.getKey(); // if no group restriction if (entry.getValue() == null) { // add this item to all students for (String userId : studentIds) if (allExternals.containsKey(userId)) allExternals.get(userId).add(externalId); } else { // otherwise find users that are in the groups Set<String> okUsers = new HashSet<String>( authzGroupService.getAuthzUsersInGroups(new HashSet<String>(entry.getValue()))); okUsers.retainAll(studentIds); // and add this item just to them for (String u : okUsers) if (allExternals.containsKey(u)) { allExternals.get(u).add(externalId); } } } //System.out.println("getAllExternalAssignments " + studentIds + " " + allExternals); return allExternals; }
From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java
@SuppressWarnings("unchecked") private void setProperty(Object proxy, IPropertyDescriptor propertyDescriptor, Object newProperty) { String propertyName = propertyDescriptor.getName(); Object oldProperty;// w w w.j av a2 s . c om try { oldProperty = accessorFactory .createPropertyAccessor(propertyName, componentDescriptor.getComponentContract()) .getValue(proxy); } catch (IllegalAccessException | NoSuchMethodException ex) { throw new ComponentException(ex); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new ComponentException(ex.getCause()); } Object actualNewProperty; if (propertyProcessorsEnabled) { actualNewProperty = propertyDescriptor.interceptSetter(proxy, newProperty); } else { actualNewProperty = newProperty; } if (isInitialized(oldProperty) && isInitialized(actualNewProperty) && ObjectUtils.equals(oldProperty, actualNewProperty)) { return; } if (propertyProcessorsEnabled) { propertyDescriptor.preprocessSetter(proxy, actualNewProperty); } if (propertyDescriptor instanceof IRelationshipEndPropertyDescriptor) { // It's a relation end IRelationshipEndPropertyDescriptor reversePropertyDescriptor = ((IRelationshipEndPropertyDescriptor) propertyDescriptor) .getReverseRelationEnd(); try { if (propertyDescriptor instanceof IReferencePropertyDescriptor) { // It's a 'one' relation end storeReferenceProperty(proxy, (IReferencePropertyDescriptor<?>) propertyDescriptor, oldProperty, actualNewProperty); if (reversePropertyDescriptor != null) { // It is bidirectional, so we are going to update the other end. if (reversePropertyDescriptor instanceof IReferencePropertyDescriptor) { // It's a one-to-one relationship if (proxy instanceof IEntity && oldProperty instanceof IEntity) { entityDetached((IEntity) proxy, (IEntity) oldProperty, ((IRelationshipEndPropertyDescriptor) propertyDescriptor)); } IAccessor reversePropertyAccessor = accessorFactory.createPropertyAccessor( reversePropertyDescriptor.getName(), ((IReferencePropertyDescriptor<?>) propertyDescriptor).getReferencedDescriptor() .getComponentContract()); if (oldProperty != null) { reversePropertyAccessor.setValue(oldProperty, null); } if (actualNewProperty != null) { reversePropertyAccessor.setValue(actualNewProperty, proxy); } } else if (reversePropertyDescriptor instanceof ICollectionPropertyDescriptor) { // It's a one-to-many relationship ICollectionAccessor reversePropertyAccessor = accessorFactory .createCollectionPropertyAccessor(reversePropertyDescriptor.getName(), ((IReferencePropertyDescriptor<?>) propertyDescriptor) .getReferencedDescriptor().getComponentContract(), ((ICollectionPropertyDescriptor<?>) reversePropertyDescriptor) .getCollectionDescriptor().getElementDescriptor() .getComponentContract()); if (reversePropertyAccessor instanceof IModelDescriptorAware) { ((IModelDescriptorAware) reversePropertyAccessor) .setModelDescriptor(reversePropertyDescriptor); } if (oldProperty != null) { reversePropertyAccessor.removeFromValue(oldProperty, proxy); } if (actualNewProperty != null) { reversePropertyAccessor.addToValue(actualNewProperty, proxy); } } } } else if (propertyDescriptor instanceof ICollectionPropertyDescriptor) { Collection<?> oldCollectionSnapshot = CollectionHelper .cloneCollection((Collection<?>) oldProperty); // It's a 'many' relation end Collection<Object> oldPropertyElementsToRemove = new THashSet<>(1); Collection<Object> newPropertyElementsToAdd = new TLinkedHashSet<>(1); Collection<Object> propertyElementsToKeep = new THashSet<>(1); if (oldProperty != null) { oldPropertyElementsToRemove.addAll((Collection<?>) oldProperty); propertyElementsToKeep.addAll((Collection<?>) oldProperty); } if (actualNewProperty != null) { newPropertyElementsToAdd.addAll((Collection<?>) actualNewProperty); } propertyElementsToKeep.retainAll(newPropertyElementsToAdd); oldPropertyElementsToRemove.removeAll(propertyElementsToKeep); newPropertyElementsToAdd.removeAll(propertyElementsToKeep); ICollectionAccessor propertyAccessor = accessorFactory.createCollectionPropertyAccessor( propertyName, componentDescriptor.getComponentContract(), ((ICollectionPropertyDescriptor<?>) propertyDescriptor).getCollectionDescriptor() .getElementDescriptor().getComponentContract()); boolean oldCollectionSortEnabled = collectionSortEnabled; boolean oldPropertyChangeEnabled = propertyChangeEnabled; boolean oldPropertyProcessorsEnabled = propertyProcessorsEnabled; try { // Delay sorting for performance reasons. collectionSortEnabled = false; // Block property changes for performance reasons; propertyChangeEnabled = false; // Block property processors propertyProcessorsEnabled = false; for (Object element : oldPropertyElementsToRemove) { propertyAccessor.removeFromValue(proxy, element); } for (Object element : newPropertyElementsToAdd) { propertyAccessor.addToValue(proxy, element); } inlineComponentFactory.sortCollectionProperty((IComponent) proxy, propertyName); } finally { collectionSortEnabled = oldCollectionSortEnabled; propertyChangeEnabled = oldPropertyChangeEnabled; propertyProcessorsEnabled = oldPropertyProcessorsEnabled; } // if the property is a list we may restore the element order and be // careful not to miss one... if (actualNewProperty instanceof List) { Collection<Object> currentProperty = (Collection<Object>) oldProperty; if (currentProperty instanceof List) { // Just check that only order differs Set<Object> temp = new THashSet<>(currentProperty); temp.removeAll((List<?>) actualNewProperty); if (currentProperty instanceof ICollectionWrapper) { currentProperty = ((ICollectionWrapper) currentProperty).getWrappedCollection(); } currentProperty.clear(); currentProperty.addAll((List<?>) actualNewProperty); currentProperty.addAll(temp); } } oldProperty = oldCollectionSnapshot; } } catch (RuntimeException ex) { rollbackProperty(proxy, propertyDescriptor, oldProperty); throw ex; } catch (InvocationTargetException ex) { rollbackProperty(proxy, propertyDescriptor, oldProperty); if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new ComponentException(ex.getCause()); } catch (IllegalAccessException | NoSuchMethodException ex) { throw new ComponentException(ex); } } else { storeProperty(propertyName, actualNewProperty); } doFirePropertyChange(proxy, propertyName, oldProperty, actualNewProperty); if (propertyProcessorsEnabled) { propertyDescriptor.postprocessSetter(proxy, oldProperty, actualNewProperty); } }
From source file:ubic.gemma.core.search.SearchServiceImpl.java
/** * Search for the Experiment query in ontologies, including items that are associated with children of matching * query terms.//www . j av a2s . co m * That is, 'brain' should return entities tagged as 'hippocampus'. This method will return results only up to * MAX_CHARACTERISTIC_SEARCH_RESULTS. It can handle AND in searches, so Parkinson's AND neuron finds items tagged * with both of those terms. The use of OR is handled by the caller. * * @param classes Classes of characteristic-bound entities. For example, to get matching characteristics of * ExpressionExperiments, pass ExpressionExperiments.class in this collection parameter. * @return SearchResults of CharacteristicObjects. Typically to be useful one needs to retrieve the * 'parents' * (entities which have been 'tagged' with the term) of those Characteristics */ private Collection<SearchResult> characteristicSearchWithChildren(Collection<Class<?>> classes, String query) { StopWatch timer = this.startTiming(); /* * The tricky part here is if the user has entered a boolean query. If they put in Parkinson's disease AND * neuron, * then we want to eventually return entities that are associated with both. We don't expect to find single * characteristics that match both. * * But if they put in Parkinson's disease we don't want to do two queries. */ String[] subparts = query.split(" AND "); // we would have to first deal with the separate queries, and then apply the logic. Collection<SearchResult> allResults = new HashSet<>(); SearchServiceImpl.log .info("Starting characteristic search: " + query + " for type=" + StringUtils.join(classes, ",")); for (String rawTerm : subparts) { String trimmed = StringUtils.strip(rawTerm); if (StringUtils.isBlank(trimmed)) { continue; } Collection<SearchResult> subqueryResults = this.characteristicSearchTerm(classes, trimmed); if (allResults.isEmpty()) { allResults.addAll(subqueryResults); } else { // this is our Intersection operation. allResults.retainAll(subqueryResults); // aggregate the highlighted text. Map<SearchResult, String> highlights = new HashMap<>(); for (SearchResult sqr : subqueryResults) { highlights.put(sqr, sqr.getHighlightedText()); } for (SearchResult ar : allResults) { String k = highlights.get(ar); if (StringUtils.isNotBlank(k)) { String highlightedText = ar.getHighlightedText(); if (StringUtils.isBlank(highlightedText)) { ar.setHighlightedText(k); } else { ar.setHighlightedText(highlightedText + "," + k); } } } } if (timer.getTime() > 1000) { SearchServiceImpl.log.info("Characteristic search for '" + rawTerm + "': " + allResults.size() + " hits retained so far; " + timer.getTime() + "ms"); timer.reset(); timer.start(); } } return allResults; }
From source file:ubic.gemma.search.SearchServiceImpl.java
@Override public Collection<Long> searchExpressionExperiments(String query, Long taxonId) { Taxon taxon = taxonDao.load(taxonId); Collection<Long> eeIds = new HashSet<Long>(); if (StringUtils.isNotBlank(query)) { if (query.length() < MINIMUM_EE_QUERY_LENGTH) return eeIds; // Initial list List<SearchResult> results = this .search(SearchSettingsImpl.expressionExperimentSearch(query), false, false) .get(ExpressionExperiment.class); for (SearchResult result : results) { eeIds.add(result.getId());//from w w w .j a v a2s . c o m } // Filter by taxon if (taxon != null) { Collection<Long> eeIdsToKeep = new HashSet<Long>(); Collection<ExpressionExperiment> ees = expressionExperimentService.findByTaxon(taxon); for (ExpressionExperiment ee : ees) { if (eeIds.contains(ee.getId())) eeIdsToKeep.add(ee.getId()); } eeIds.retainAll(eeIdsToKeep); } } else { Collection<ExpressionExperiment> ees = (taxon != null) ? expressionExperimentService.findByTaxon(taxon) : expressionExperimentService.loadAll(); for (ExpressionExperiment ee : ees) { eeIds.add(ee.getId()); } } return eeIds; }
From source file:org.jsweet.transpiler.typescript.Java2TypeScriptTranslator.java
@Override public void visitLambda(JCLambda lamba) { Map<String, VarSymbol> varAccesses = new HashMap<>(); Util.fillAllVariableAccesses(varAccesses, lamba); Collection<VarSymbol> finalVars = new ArrayList<>(varAccesses.values()); if (!varAccesses.isEmpty()) { Map<String, VarSymbol> varDefs = new HashMap<>(); int parentIndex = getStack().size() - 2; int i = parentIndex; JCStatement statement = null;//from w w w . j a va 2 s . c om while (i > 0 && getStack().get(i).getKind() != Kind.LAMBDA_EXPRESSION && getStack().get(i).getKind() != Kind.METHOD) { if (statement == null && getStack().get(i) instanceof JCStatement) { statement = (JCStatement) getStack().get(i); } i--; } if (i >= 0 && getStack().get(i).getKind() != Kind.LAMBDA_EXPRESSION && statement != null) { Util.fillAllVariablesInScope(varDefs, getStack(), lamba, getStack().get(i)); } finalVars.retainAll(varDefs.values()); } if (!finalVars.isEmpty()) { print("(("); for (VarSymbol var : finalVars) { print(var.name.toString()).print(","); } removeLastChar(); print(") => {").println().startIndent().printIndent().print("return "); } getScope().skipTypeAnnotations = true; print("(").printArgList(lamba.params).print(") => "); getScope().skipTypeAnnotations = false; print(lamba.body); if (!finalVars.isEmpty()) { endIndent().println().printIndent().print("})("); for (VarSymbol var : finalVars) { print(var.name.toString()).print(","); } removeLastChar(); print(")"); } }
From source file:org.jsweet.transpiler.Java2TypeScriptTranslator.java
@Override public void visitLambda(JCLambda lamba) { Map<String, VarSymbol> varAccesses = new HashMap<>(); Util.fillAllVariableAccesses(varAccesses, lamba); Collection<VarSymbol> finalVars = new ArrayList<>(varAccesses.values()); if (!varAccesses.isEmpty()) { Map<String, VarSymbol> varDefs = new HashMap<>(); int parentIndex = getStack().size() - 2; int i = parentIndex; JCStatement statement = null;/*w ww .j a v a 2 s .c om*/ while (i > 0 && getStack().get(i).getKind() != Kind.LAMBDA_EXPRESSION && getStack().get(i).getKind() != Kind.METHOD) { if (statement == null && getStack().get(i) instanceof JCStatement) { statement = (JCStatement) getStack().get(i); } i--; } if (i >= 0 && getStack().get(i).getKind() != Kind.LAMBDA_EXPRESSION && statement != null) { Util.fillAllVariablesInScope(varDefs, getStack(), lamba, getStack().get(i)); } finalVars.retainAll(varDefs.values()); } if (!finalVars.isEmpty()) { print("(("); for (VarSymbol var : finalVars) { print(var.name.toString()).print(","); } removeLastChar(); print(") => {").println().startIndent().printIndent().print("return "); } getScope().skipTypeAnnotations = true; print("(").printArgList(null, lamba.params).print(") => "); getScope().skipTypeAnnotations = false; print(lamba.body); if (!finalVars.isEmpty()) { endIndent().println().printIndent().print("})("); for (VarSymbol var : finalVars) { print(var.name.toString()).print(","); } removeLastChar(); print(")"); } }