List of usage examples for java.util Collection clear
void clear();
From source file:com.evolveum.midpoint.security.impl.SecurityEnforcerImpl.java
private <O extends ObjectType, T extends ObjectType> boolean isAuthorizedInternal( MidPointPrincipal midPointPrincipal, String operationUrl, AuthorizationPhaseType phase, PrismObject<O> object, ObjectDelta<O> delta, PrismObject<T> target, OwnerResolver ownerResolver) throws SchemaException { if (AuthorizationConstants.AUTZ_NO_ACCESS_URL.equals(operationUrl)) { return false; }/*from w w w . ja v a 2 s . c o m*/ if (phase == null) { throw new IllegalArgumentException("No phase"); } boolean allow = false; LOGGER.trace("AUTZ: evaluating authorization principal={}, op={}, phase={}, object={}, delta={}, target={}", new Object[] { midPointPrincipal, operationUrl, phase, object, delta, target }); final Collection<ItemPath> allowedItems = new ArrayList<>(); Collection<Authorization> authorities = midPointPrincipal.getAuthorities(); if (authorities != null) { for (GrantedAuthority authority : authorities) { if (authority instanceof Authorization) { Authorization autz = (Authorization) authority; String autzHumanReadableDesc = autz.getHumanReadableDesc(); LOGGER.trace("Evaluating {}", autzHumanReadableDesc); // First check if the authorization is applicable. // action if (!autz.getAction().contains(operationUrl) && !autz.getAction().contains(AuthorizationConstants.AUTZ_ALL_URL)) { LOGGER.trace(" {} not applicable for operation {}", autzHumanReadableDesc, operationUrl); continue; } // phase if (autz.getPhase() == null) { LOGGER.trace(" {} is applicable for all phases (continuing evaluation)", autzHumanReadableDesc); } else { if (autz.getPhase() != phase) { LOGGER.trace(" {} is not applicable for phases {} (breaking evaluation)", autzHumanReadableDesc, phase); continue; } else { LOGGER.trace(" {} is applicable for phases {} (continuing evaluation)", autzHumanReadableDesc, phase); } } // object if (isApplicable(autz.getObject(), object, midPointPrincipal, ownerResolver, "object", autzHumanReadableDesc)) { LOGGER.trace(" {} applicable for object {} (continuing evaluation)", autzHumanReadableDesc, object); } else { LOGGER.trace( " {} not applicable for object {}, none of the object specifications match (breaking evaluation)", autzHumanReadableDesc, object); continue; } // target if (isApplicable(autz.getTarget(), target, midPointPrincipal, ownerResolver, "target", autzHumanReadableDesc)) { LOGGER.trace(" {} applicable for target {} (continuing evaluation)", autzHumanReadableDesc, object); } else { LOGGER.trace( " {} not applicable for target {}, none of the target specifications match (breaking evaluation)", autzHumanReadableDesc, object); continue; } // authority is applicable to this situation. now we can process the decision. AuthorizationDecisionType decision = autz.getDecision(); if (decision == null || decision == AuthorizationDecisionType.ALLOW) { // if there is more than one role which specify // different authz (e.g one role specify allow for whole // objet, the other role specify allow only for some // attributes. this ended with allow for whole object (MID-2018) Collection<ItemPath> allowed = getItems(autz); if (allow && allowedItems.isEmpty()) { LOGGER.trace(" {}: ALLOW operation {} (but continue evaluation)", autzHumanReadableDesc, operationUrl); } else if (allow && allowed.isEmpty()) { allowedItems.clear(); } else { allowedItems.addAll(allowed); } LOGGER.trace(" {}: ALLOW operation {} (but continue evaluation)", autzHumanReadableDesc, operationUrl); allow = true; // Do NOT break here. Other authorization statements may still deny the operation } else { // item if (isApplicableItem(autz, object, delta)) { LOGGER.trace(" {}: Deny authorization applicable for items (continuing evaluation)", autzHumanReadableDesc); } else { LOGGER.trace(" {} not applicable for items (breaking evaluation)", autzHumanReadableDesc); continue; } LOGGER.trace(" {}: DENY operation {}", autzHumanReadableDesc, operationUrl); allow = false; // Break right here. Deny cannot be overridden by allow. This decision cannot be changed. break; } } else { LOGGER.warn("Unknown authority type {} in user {}", authority.getClass(), midPointPrincipal.getUsername()); } } } if (allow) { // Still check allowedItems. We may still deny the operation. if (allowedItems.isEmpty()) { // This means all items are allowed. No need to check anything LOGGER.trace(" Empty list of allowed items, operation allowed"); } else { // all items in the object and delta must be allowed final MutableBoolean itemDecision = new MutableBoolean(true); if (delta != null) { // If there is delta then consider only the delta. Visitor visitor = new Visitor() { @Override public void visit(Visitable visitable) { ItemPath itemPath = getPath(visitable); if (itemPath != null && !itemPath.isEmpty()) { if (!isInList(itemPath, allowedItems)) { LOGGER.trace(" DENY operation because item {} in the delta is not allowed", itemPath); itemDecision.setValue(false); } } } }; delta.accept(visitor); } else if (object != null) { Visitor visitor = new Visitor() { @Override public void visit(Visitable visitable) { ItemPath itemPath = getPath(visitable); if (itemPath != null && !itemPath.isEmpty()) { if (!isInList(itemPath, allowedItems)) { LOGGER.trace(" DENY operation because item {} in the object is not allowed", itemPath); itemDecision.setValue(false); } } } }; object.accept(visitor); } allow = itemDecision.booleanValue(); } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("AUTZ result: principal={}, operation={}: {}", new Object[] { midPointPrincipal, operationUrl, allow }); } return allow; }
From source file:com.smartitengineering.cms.type.xml.XmlParser.java
public Collection<MutableContentType> parse() { ContentTypeId contentTypeId = null;//from w ww . ja va 2s . c om Collection<FieldDef> fieldDefs = new ArrayList<FieldDef>(); Collection<MutableContentType> contentTypes = new ArrayList<MutableContentType>(); Collection<RepresentationDef> representationDefs = new ArrayList<RepresentationDef>(); Collection<ContentStatus> statuses = new ArrayList<ContentStatus>(); String displayName = null; try { Builder builder = new Builder(false); Document document = builder.build(this.source); Element rootElement = document.getRootElement(); Elements childRootElements = rootElement.getChildElements(); for (int j = 0; j < childRootElements.size(); j++) { final MutableContentType mutableContent = introspector.createMutableContentType(); final Element contentTypeElement = childRootElements.get(j); Elements childElements = contentTypeElement.getChildElements(); String name = parseMandatoryStringElement(contentTypeElement, NAME); //max=1,min=1 String namespace = parseAttribute(contentTypeElement, ATTR_NAMESPACE); if (logger.isDebugEnabled()) { logger.debug(new StringBuilder("Iterating over ").append(j).toString()); logger.debug(new StringBuilder("Namespace ").append(namespace).toString()); logger.debug(new StringBuilder("Name ").append(name).toString()); } contentTypeId = getContentTypeId(workspaceId, namespace, name); mutableContent.setContentTypeID(contentTypeId); displayName = parseOptionalStringElement(contentTypeElement, DISPLAY_NAME); //min=0,max=1 mutableContent .setParameterizedDisplayNames(parseParams(contentTypeElement, PARAMETERIZED_DISPLAY_NAMES)); for (int child = 0; child < childElements.size(); child++) {//fields min=1,max=unbounted if (StringUtils.equalsIgnoreCase(childElements.get(child).getLocalName(), FIELDS)) { fieldDefs.addAll(parseFieldDefs(childElements.get(child), null)); } } statuses = parseContentStatuses(contentTypeElement, STATUS); representationDefs = parseRepresentations(contentTypeElement, REPRESENTATIONS); Map<ContentType.ContentProcessingPhase, List<MutableContentCoProcessorDef>> ccpDefs = parseContentCoProcessorDefs( contentTypeElement, CONTENT_CO_PROCESSOR_DEFS); for (Entry<ContentProcessingPhase, List<MutableContentCoProcessorDef>> entry : ccpDefs.entrySet()) { for (MutableContentCoProcessorDef def : entry.getValue()) { def.setPhase(entry.getKey()); if (logger.isDebugEnabled()) { logger.debug("^^^^^^^^^^^^^^ Adding content co processor to " + contentTypeId); } mutableContent.addContentCoProcessorDef(def); } } contentTypeId = parseContentTypeId(contentTypeElement, PARENT, workspaceId); String primaryFieldName = parseOptionalStringElement(contentTypeElement, PRIMARY_FIELD); if (logger.isDebugEnabled()) { logger.debug("Primary field parsed: " + primaryFieldName); } if (StringUtils.isNotBlank(primaryFieldName)) { mutableContent.setPrimaryFieldName(primaryFieldName); } String defType = parseOptionalStringElement(contentTypeElement, DEF_TYPE); if (logger.isDebugEnabled()) { logger.debug("Def type parsed: " + defType); } if (StringUtils.isNotBlank(defType)) { mutableContent.setDefinitionType(ContentType.DefinitionType.valueOf(defType)); } mutableContent.setDisplayName(displayName); mutableContent.setParent(contentTypeId); mutableContent.getMutableFieldDefs().addAll(fieldDefs); if (representationDefs != null) { mutableContent.getMutableRepresentationDefs().addAll(representationDefs); } mutableContent.getMutableStatuses().addAll(statuses); contentTypes.add(mutableContent); introspector.processMutableContentType(mutableContent, contentTypeElement); fieldDefs.clear(); } } catch (Exception e) { logger.warn(e.getMessage(), e); } return contentTypes; }
From source file:org.regenstrief.util.Util.java
/** * Clears a Collection/* ww w. ja va2 s .c om*/ * * @param c the Collection **/ public final static void clear(final Collection<?> c) { if (c != null) { c.clear(); } }
From source file:org.silverpeas.components.kmelia.service.DefaultKmeliaService.java
@Override public List<KmeliaPublication> getLatestPublications(String instanceId, int nbPublisOnRoot, boolean isRightsOnTopicsUsed, String userId) { PublicationPK pubPK = new PublicationPK(UNKNOWN, instanceId); Collection<PublicationDetail> pubDetails = publicationService .getDetailsByBeginDateDescAndStatusAndNotLinkedToFatherId(pubPK, PublicationDetail.VALID_STATUS, nbPublisOnRoot, NodePK.BIN_NODE_ID); if (isRightsOnTopicsUsed) {// The list of publications must be filtered List<PublicationDetail> filteredList = new ArrayList<>(); KmeliaAuthorization security = new KmeliaAuthorization(); for (PublicationDetail pubDetail : pubDetails) { if (security.isObjectAvailable(instanceId, userId, pubDetail.getPK().getId(), PUBLICATION)) { filteredList.add(pubDetail); }/*from ww w . jav a2 s . c o m*/ } pubDetails.clear(); pubDetails.addAll(filteredList); } return pubDetails2userPubs(pubDetails); }
From source file:net.droidsolutions.droidcharts.core.plot.XYPlot.java
/** * Clears the (foreground and background) range markers for a particular * renderer./* w ww . ja va2 s. co m*/ * * @param index * the renderer index. */ public void clearRangeMarkers(int index) { Integer key = new Integer(index); if (this.backgroundRangeMarkers != null) { Collection markers = (Collection) this.backgroundRangeMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); // m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection markers = (Collection) this.foregroundRangeMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); // m.removeChangeListener(this); } markers.clear(); } } // fireChangeEvent(); }
From source file:net.droidsolutions.droidcharts.core.plot.XYPlot.java
/** * Clears the (foreground and background) domain markers for a particular * renderer./*from ww w .ja v a2 s . co m*/ * * @param index * the renderer index. * * @see #clearRangeMarkers(int) */ public void clearDomainMarkers(int index) { Integer key = new Integer(index); if (this.backgroundDomainMarkers != null) { Collection markers = (Collection) this.backgroundDomainMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); // m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection markers = (Collection) this.foregroundDomainMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); // m.removeChangeListener(this); } markers.clear(); } } // fireChangeEvent(); }
From source file:com.stratelia.webactiv.kmelia.control.ejb.KmeliaBmEJB.java
@Override public List<KmeliaPublication> getLatestPublications(String instanceId, int nbPublisOnRoot, boolean isRightsOnTopicsUsed, String userId) { PublicationPK pubPK = new PublicationPK("unknown", instanceId); Collection<PublicationDetail> pubDetails = publicationBm .getDetailsByBeginDateDescAndStatusAndNotLinkedToFatherId(pubPK, PublicationDetail.VALID, nbPublisOnRoot, NodePK.BIN_NODE_ID); if (isRightsOnTopicsUsed) {// The list of publications must be filtered List<PublicationDetail> filteredList = new ArrayList<PublicationDetail>(); KmeliaSecurity security = new KmeliaSecurity(); for (PublicationDetail pubDetail : pubDetails) { if (security.isObjectAvailable(instanceId, userId, pubDetail.getPK().getId(), "Publication")) { filteredList.add(pubDetail); }/*from w w w . j a v a 2 s . c om*/ } pubDetails.clear(); pubDetails.addAll(filteredList); } return pubDetails2userPubs(pubDetails); }
From source file:org.openmrs.module.patientaccesscontrol.web.dwr.DWRModulePatientService.java
/** * Returns a map of results with the values as count of matches and a partial list of the matching patients * (depending on values of start and length parameters) while the keys are are 'count' and 'objectList' * respectively, if the length parameter is not specified, then all matches will be returned from the start index if * specified./* www.j a v a 2 s. c o m*/ * * @param searchValue * patient name or identifier * @param start * the beginning index * @param length * the number of matching patients to return * @param getMatchCount * Specifies if the count of matches should be included in the returned map * @return a map of results * @throws APIException * @since 1.8 * @should signal for a new search if the new search value has matches and is a first call * @should not signal for a new search if it is not the first ajax call * @should not signal for a new search if the new search value has no matches * @should match patient with identifiers that contain no digit */ public Map<String, Object> listCountAndPatients(String searchValue, List<Integer> conceptIds, Integer start, Integer length, boolean getMatchCount) throws APIException { // Map to return Map<String, Object> resultsMap = new HashMap<String, Object>(); Collection<Object> objectList = new Vector<Object>(); try { PatientAccessControlService ps = Context.getService(PatientAccessControlService.class); int patientCount = 0; // if this is the first call if (getMatchCount) { patientCount += ps.getCountOfPatientPrograms(searchValue); // if there are no results found and a number was not in the // search and this is the first call, then do a decapitated search: // trim each word down to the first three characters and search again if (patientCount == 0 && start == 0 && !searchValue.matches(".*\\d+.*")) { String[] names = searchValue.split(" "); String newSearch = ""; for (String name : names) { if (name.length() > 3) { name = name.substring(0, 3); } newSearch += " " + name; } newSearch = newSearch.trim(); if (!newSearch.equals(searchValue)) { newSearch = newSearch.trim(); int newPatientCount = ps.getCountOfPatients(newSearch); if (newPatientCount > 0) { // Send a signal to the core search widget to search again against newSearch resultsMap.put("searchAgain", newSearch); resultsMap.put("notification", Context.getMessageSourceService().getMessage("searchWidget.noResultsFoundFor", new Object[] { searchValue, newSearch }, Context.getLocale())); } } } // no results found and a number was in the search -- // should check whether the check digit is correct. else if (patientCount == 0 && searchValue.matches(".*\\d+.*")) { // Looks through all the patient identifier validators to see if this type of identifier // is supported for any of them. If it isn't, then no need to warn about a bad check // digit. If it does match, then if any of the validators validates the check digit // successfully, then the user is notified that the identifier has been entered correctly. // Otherwise, the user is notified that the identifier was entered incorrectly. Collection<IdentifierValidator> pivs = Context.getPatientService().getAllIdentifierValidators(); boolean shouldWarnUser = true; boolean validCheckDigit = false; boolean identifierMatchesValidationScheme = false; for (IdentifierValidator piv : pivs) { try { if (piv.isValid(searchValue)) { shouldWarnUser = false; validCheckDigit = true; } identifierMatchesValidationScheme = true; } catch (UnallowedIdentifierException e) { } } if (identifierMatchesValidationScheme) { if (shouldWarnUser) { resultsMap.put("notification", "<b>" + Context.getMessageSourceService() .getMessage("Patient.warning.inValidIdentifier") + "<b/>"); } else if (validCheckDigit) { resultsMap.put("notification", "<b style=\"color:green;\">" + Context.getMessageSourceService() .getMessage("Patient.message.validIdentifier") + "<b/>"); } } } else { // ensure that count never exceeds this value because the API's service layer would never // return more than it since it is limited in the DAO layer if (maximumResults == null) { maximumResults = getMaximumSearchResults(); } if (length != null && length > maximumResults) { length = maximumResults; } if (patientCount > maximumResults) { patientCount = maximumResults; if (log.isDebugEnabled()) { log.debug("Limitng the size of matching patients to " + maximumResults); } } } } // if we have any matches or this isn't the first ajax call when the caller // requests for the count if (patientCount > 0 || !getMatchCount) { objectList = listBatchOfPatients(searchValue, conceptIds, false, start, length); } resultsMap.put("count", patientCount); resultsMap.put("objectList", objectList); } catch (Exception e) { log.error("Error while searching for patients", e); objectList.clear(); objectList.add( Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage()); resultsMap.put("count", 0); resultsMap.put("objectList", objectList); } return resultsMap; }
From source file:edu.amc.sakai.user.JLDAPDirectoryProvider.java
/** * Similar to iterating over <code>users</code> passing * each element to {@link #getUser(UserEdit)}, removing the * {@link org.sakaiproject.user.api.UserEdit} if that method * returns <code>false</code>. * // ww w. j av a2 s . c o m * <p>Adds search retry capability if any one lookup fails * with a directory error. Empties <code>users</code> and * returns if a retry exits exceptionally * <p> */ public void getUsers(Collection<UserEdit> users) { if (M_log.isDebugEnabled()) { M_log.debug("getUsers(): [Collection size = " + users.size() + "]"); } LDAPConnection conn = null; boolean abortiveSearch = false; int maxQuerySize = getMaxObjectsToQueryFor(); UserEdit userEdit = null; HashMap<String, UserEdit> usersToSearchInLDAP = new HashMap<String, UserEdit>(); List<UserEdit> usersToRemove = new ArrayList<UserEdit>(); try { int cnt = 0; for (Iterator<UserEdit> userEdits = users.iterator(); userEdits.hasNext();) { userEdit = (UserEdit) userEdits.next(); String eid = userEdit.getEid(); if (!(isSearchableEid(eid))) { userEdits.remove(); //proceed ahead with this (perhaps the final) iteration //usersToSearchInLDAP needs to be processed unless empty } else { usersToSearchInLDAP.put(eid, userEdit); cnt++; } // We need to make sure this query isn't larger than maxQuerySize if ((!userEdits.hasNext() || cnt == maxQuerySize) && !usersToSearchInLDAP.isEmpty()) { if (conn == null) { conn = ldapConnectionManager.getConnection(); } String filter = ldapAttributeMapper.getManyUsersInOneSearch(usersToSearchInLDAP.keySet()); List<LdapUserData> ldapUsers = searchDirectory(filter, null, null, null, null, maxQuerySize); for (LdapUserData ldapUserData : ldapUsers) { String ldapEid = ldapUserData.getEid(); if (StringUtils.isEmpty(ldapEid)) { continue; } ldapEid = ldapEid.toLowerCase(); UserEdit ue = usersToSearchInLDAP.get(ldapEid); mapUserDataOntoUserEdit(ldapUserData, ue); usersToSearchInLDAP.remove(ldapEid); } // see if there are any users that we could not find in the LDAP query for (Map.Entry<String, UserEdit> entry : usersToSearchInLDAP.entrySet()) { usersToRemove.add(entry.getValue()); } // clear the HashMap and reset the counter usersToSearchInLDAP.clear(); cnt = 0; } } // Finally clean up the original collection and remove and users we could not find for (UserEdit userRemove : usersToRemove) { if (M_log.isDebugEnabled()) { M_log.debug("JLDAP getUsers could not find user: " + userRemove.getEid()); } users.remove(userRemove); } } catch (LDAPException e) { abortiveSearch = true; throw new RuntimeException("getUsers(): LDAPException during search [eid = " + (userEdit == null ? null : userEdit.getEid()) + "][result code = " + e.resultCodeToString() + "][error message = " + e.getLDAPErrorMessage() + "]", e); } catch (Exception e) { abortiveSearch = true; throw new RuntimeException("getUsers(): RuntimeException during search eid = " + (userEdit == null ? null : userEdit.getEid()) + "]", e); } finally { if (conn != null) { if (M_log.isDebugEnabled()) { M_log.debug("getUsers(): returning connection to connection manager"); } ldapConnectionManager.returnConnection(conn); } // no sense in returning a partially complete search result if (abortiveSearch) { if (M_log.isDebugEnabled()) { M_log.debug("getUsers(): abortive search, clearing received users collection"); } users.clear(); } } }
From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java
/** * @param collsubformctl//from ww w.ja v a 2s .co m * @precondition collsubformctl != null */ private static void closeSubFormControllers(Collection<? extends SubFormController> collsubformctl) { for (SubFormController subformctl : collsubformctl) { subformctl.close(); } collsubformctl.clear(); }