Example usage for java.util Collection remove

List of usage examples for java.util Collection remove

Introduction

In this page you can find the example usage for java.util Collection remove.

Prototype

boolean remove(Object o);

Source Link

Document

Removes a single instance of the specified element from this collection, if it is present (optional operation).

Usage

From source file:org.sakaiproject.authz.tool.PermissionsHelperAction.java

/**
 * build the context./*from  w  w w .  jav  a2 s. c  om*/
 * 
 * @return The name of the template to use. <code>null</code> can be returned.
 */
public String buildHelperContext(VelocityPortlet portlet, Context context, RunData rundata,
        SessionState state) {
    // in state is the realm id
    context.put("thelp", rb);
    String realmId = (String) state.getAttribute(STATE_REALM_ID);

    // in state is the realm to use for roles - if not, use realmId
    Collection<String> realmRolesIds = (Collection<String>) state.getAttribute(STATE_REALM_ROLES_IDS);
    context.put("viewRealmIds", realmRolesIds);

    // get the realm locked for editing
    AuthzGroup edit = (AuthzGroup) state.getAttribute(STATE_REALM_EDIT);
    if (edit == null) {
        if (authzGroupService.allowUpdate(realmId)) {
            try {
                edit = authzGroupService.getAuthzGroup(realmId);
                state.setAttribute(STATE_REALM_EDIT, edit);
            } catch (GroupNotDefinedException e) {
                try {
                    // we can create the realm
                    edit = authzGroupService.addAuthzGroup(realmId);
                    state.setAttribute(STATE_REALM_EDIT, edit);
                } catch (GroupIdInvalidException ee) {
                    M_log.warn("PermissionsAction.buildHelperContext: addRealm: " + ee);
                    cleanupState(state);
                    return null;
                } catch (GroupAlreadyDefinedException ee) {
                    M_log.warn("PermissionsAction.buildHelperContext: addRealm: " + ee);
                    cleanupState(state);
                    return null;
                } catch (AuthzPermissionException ee) {
                    M_log.warn("PermissionsAction.buildHelperContext: addRealm: " + ee);
                    cleanupState(state);
                    return null;
                }
            }
        }

        // no permission
        else {
            M_log.warn("PermissionsAction.buildHelperContext: no permission: " + realmId);
            cleanupState(state);
            addAlert(state, rb.getFormattedMessage("alert_permission", new Object[] { realmId }));
            return null;
        }
    }

    AuthzGroup viewEdit = null;
    // check wither the current realm id is of site group type
    if (realmId.indexOf(SiteService.REFERENCE_ROOT) != -1) {
        String siteId = realmId.replaceAll(SiteService.REFERENCE_ROOT + "/", "");
        context.put("siteRef", realmId);

        if (state.getAttribute(STATE_GROUP_AWARE) != null
                && ((Boolean) state.getAttribute(STATE_GROUP_AWARE)).booleanValue()) {
            // only show groups for group-aware tools
            try {
                Site site = siteService.getSite(siteId);
                Collection groups = site.getGroups();
                if (groups != null && !groups.isEmpty()) {
                    Iterator iGroups = groups.iterator();
                    for (; iGroups.hasNext();) {
                        Group group = (Group) iGroups.next();
                        // need to either have realm update permission on the group level or better at the site level
                        if (!authzGroupService.allowUpdate(group.getReference())) {
                            iGroups.remove();
                        }
                    }
                    context.put("groups", groups);
                }

            } catch (Exception siteException) {
                M_log.warn("PermissionsAction.buildHelperContext: getsite of realm id =  " + realmId
                        + siteException);
            }
        }

        // get the realm locked for editing
        viewEdit = (AuthzGroup) state.getAttribute(STATE_VIEW_REALM_EDIT);
        if (viewEdit == null) {
            // I have no idea why this step is performed since we should never edit the template realm, so let's not be too serious about it
            String realmRolesId = realmRolesIds.iterator().next();

            if (authzGroupService.allowUpdate(realmRolesId)
                    || authzGroupService.allowUpdate(siteService.siteReference(siteId))) {
                try {
                    viewEdit = authzGroupService.getAuthzGroup(realmRolesId);
                    state.setAttribute(STATE_VIEW_REALM_EDIT, viewEdit);
                } catch (GroupNotDefinedException e) {
                    M_log.warn("PermissionsAction.buildHelperContext: getRealm with id= " + realmRolesId + " : "
                            + e);
                    cleanupState(state);
                    return null;
                }
            }

            // no permission
            else {
                M_log.warn("PermissionsAction.buildHelperContext: no permission: " + realmId);
                cleanupState(state);
                return null;
            }
        }
    }

    // in state is the prefix for abilities to present
    String prefix = (String) state.getAttribute(STATE_PREFIX);

    // in state is the list of abilities we will present
    List functions = (List) state.getAttribute(STATE_ABILITIES);
    if (functions == null) {
        // get all functions prefixed with our prefix
        functions = functionManager.getRegisteredFunctions(prefix);
    }

    if (functions != null && !functions.isEmpty()) {
        List<String> nFunctions = new Vector<String>();
        if (!realmRolesIds.contains(realmId)) {
            // editing groups within site, need to filter out those permissions only applicable to site level
            for (Iterator iFunctions = functions.iterator(); iFunctions.hasNext();) {
                String function = (String) iFunctions.next();
                if (function.indexOf("all.groups") == -1) {
                    nFunctions.add(function);
                }
            }
        } else {
            nFunctions.addAll(functions);
        }
        state.setAttribute(STATE_ABILITIES, nFunctions);
        context.put("abilities", nFunctions);

        // get function description from passed in HashMap
        // output permission descriptions
        Map<String, String> functionDescriptions = (Map<String, String>) state
                .getAttribute(STATE_PERMISSION_DESCRIPTIONS);
        if (functionDescriptions != null) {
            Set keySet = functionDescriptions.keySet();
            for (Object function : functions) {
                String desc = (String) function;
                String descKey = PREFIX_PERMISSION_DESCRIPTION + function;
                if (keySet.contains(descKey)) {
                    // use function description
                    desc = (String) functionDescriptions.get(descKey);
                }

                functionDescriptions.put((String) function, desc);
            }
            context.put("functionDescriptions", functionDescriptions);
        }
    }

    // in state is the description of the edit
    String description = (String) state.getAttribute(STATE_DESCRIPTION);

    // the list of roles
    List roles = (List) state.getAttribute(STATE_ROLES);
    if (roles == null && realmRolesIds != null) {
        // get the roles from the edit, unless another is specified
        AuthzGroup roleRealm = viewEdit != null ? viewEdit : edit;
        Collection<Role> rolesUnique = new HashSet<Role>();
        for (String realmRoleId : realmRolesIds) {
            if (realmRoleId != null) {
                try {
                    roleRealm = authzGroupService.getAuthzGroup(realmRoleId);
                } catch (Exception e) {
                    M_log.warn("PermissionsHelperAction.buildHelperContext: getRolesRealm: " + realmRoleId
                            + " : " + e);
                }
            }

            rolesUnique.addAll(roleRealm.getRoles());
        }
        roles = new Vector(rolesUnique);
        Collections.sort(roles);
        state.setAttribute(STATE_ROLES, roles);
    }

    // the abilities not including this realm for each role
    Map rolesAbilities = (Map) state.getAttribute(STATE_ROLE_ABILITIES);
    if (rolesAbilities == null) {
        rolesAbilities = new Hashtable();
        state.setAttribute(STATE_ROLE_ABILITIES, rolesAbilities);

        // get this resource's role Realms,those that refine the role definitions, but not it's own
        Reference ref = entityManager.newReference(viewEdit != null ? viewEdit.getId() : edit.getId());
        Collection realms = ref.getAuthzGroups();
        realms.remove(ref.getReference());

        for (Iterator iRoles = roles.iterator(); iRoles.hasNext();) {
            Role role = (Role) iRoles.next();
            Set locks = authzGroupService.getAllowedFunctions(role.getId(), realms);
            rolesAbilities.put(role.getId(), locks);
        }
    }

    PermissionLimiter limiter = getPermissionLimiter();

    context.put("limiter", limiter);

    context.put("roleName", new RoleNameLookup());
    context.put("realm", viewEdit != null ? viewEdit : edit);
    context.put("prefix", prefix);
    context.put("description", description);
    if (roles.size() > 0) {
        context.put("roles", roles);
    }
    context.put("rolesAbilities", rolesAbilities);

    // make sure observers are disabled
    VelocityPortletPaneledAction.disableObservers(state);

    return TEMPLATE_MAIN;
}

From source file:org.codehaus.groovy.grails.plugins.DefaultGrailsPlugin.java

@SuppressWarnings("unchecked")
private void addExcludeRuleInternal(Map map, Object o) {
    Collection excludes = (Collection) map.get(EXCLUDES);
    if (excludes == null) {
        excludes = new ArrayList();
        map.put(EXCLUDES, excludes);//  w  w w  .j a  va 2  s.  c o m
    }
    Collection includes = (Collection) map.get(INCLUDES);
    if (includes != null)
        includes.remove(o);
    excludes.add(o);
}

From source file:org.kuali.kra.award.awardhierarchy.sync.helpers.AwardSyncSponsorContactHelper.java

@SuppressWarnings("unchecked")
@Override/* www.j  av a  2 s  .c om*/
public void applySyncChange(Award award, AwardSyncChange change)
        throws NoSuchFieldException, IllegalAccessException, InvocationTargetException, ClassNotFoundException,
        NoSuchMethodException, InstantiationException {
    Collection sponsorContacts = award.getSponsorContacts();
    AwardSponsorContact sponsorContact = (AwardSponsorContact) getAwardSyncUtilityService()
            .findMatchingBo(sponsorContacts, change.getXmlExport().getKeys());
    if (StringUtils.equals(change.getSyncType(), AwardSyncType.ADD_SYNC.getSyncValue())) {
        if (sponsorContact != null) {
            this.setValuesOnSyncable(sponsorContact, change.getXmlExport().getValues(), change);
        } else {
            sponsorContact = new AwardSponsorContact();
            setValuesOnSyncable(sponsorContact, change.getXmlExport().getKeys(), change);
            setValuesOnSyncable(sponsorContact, change.getXmlExport().getValues(), change);
            award.add(sponsorContact);
        }
    } else {
        if (sponsorContact != null) {
            sponsorContacts.remove(sponsorContact);
        }
    }
}

From source file:com.graphhopper.jsprit.core.algorithm.acceptor.ExperimentalSchrimpfAcceptance.java

@Override
public boolean acceptSolution(Collection<VehicleRoutingProblemSolution> solutions,
        VehicleRoutingProblemSolution newSolution) {
    boolean solutionAccepted = false;
    if (solutions.size() < solutionMemory) {
        solutions.add(newSolution);//from   w  w  w .j  a  va 2s. com
        solutionAccepted = true;
    } else {
        VehicleRoutingProblemSolution worst = null;
        double threshold = getThreshold(currentIteration);
        for (VehicleRoutingProblemSolution solutionInMemory : solutions) {
            if (worst == null)
                worst = solutionInMemory;
            else if (solutionInMemory.getCost() > worst.getCost())
                worst = solutionInMemory;
        }
        if (newSolution.getRoutes().size() < worst.getRoutes().size()) {
            solutions.remove(worst);
            solutions.add(newSolution);
            solutionAccepted = true;
        } else if (newSolution.getRoutes().size() == worst.getRoutes().size()
                && newSolution.getCost() < worst.getCost() + threshold) {
            solutions.remove(worst);
            solutions.add(newSolution);
            solutionAccepted = true;
        }
    }
    return solutionAccepted;
}

From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteriaTest.java

@SuppressWarnings("unchecked")
@Test//from  www.  jav a  2s  . c  om
public void publicAbstractMethodStartingWithAdd() {
    memberCriteria.membersOfType(Method.class);
    memberCriteria.withModifiers(Modifier.ABSTRACT);
    memberCriteria.named(Pattern.compile("add.*"));
    memberCriteria.setMemberIterateOrder(ReflectFacade.getMemberNameComparator());
    Collection<Class<?>> iteratedTypes = new ArrayList<Class<?>>(Arrays.asList(List.class, Collection.class));
    ClassCriteria classCriteria = new ClassCriteria();
    Iterable<Class<?>> classIterable = classCriteria.getIterable(ArrayList.class);
    Iterable<Member> memberIterable = memberCriteria.getIterable(classIterable);
    assertTrue(memberIterable.iterator().hasNext());
    for (Member member : memberIterable) {
        assertTrue("member must be a method", member instanceof Method);
        iteratedTypes.remove(member.getDeclaringClass());
        String name = member.getName();
        assertTrue(name.startsWith("add"));
        int modifiers = member.getModifiers();
        assertTrue(Modifier.isAbstract(modifiers));
    }
    assertTrue("Some types have not been iterated. " + iteratedTypes, iteratedTypes.isEmpty());
}

From source file:ubic.gemma.core.security.authorization.SecurityServiceTest.java

@Test
public void testRemoveMultipleAcesFromPrivateExpressionExperiment() {
    // make private experiment
    ExpressionExperiment ee = super.getTestPersistentBasicExpressionExperiment();
    this.securityService.makePrivate(ee);

    // add user and add the user to a group
    String username = "salmonid";
    String groupName = "fish" + this.randomName();
    this.makeUser(username);
    this.securityService.makeOwnedByUser(ee, username);
    assertTrue(this.securityService.isEditableByUser(ee, username));
    this.runAsUser(username);
    this.securityService.createGroup(groupName);

    // get the basic acls
    MutableAcl acl = aclTestUtils.getAcl(ee);
    int numberOfAces = acl.getEntries().size();

    // make readable by group add first ACE read for group and check added
    this.securityService.makeReadableByGroup(ee, groupName);
    MutableAcl aclAfterReadableAdded = aclTestUtils.getAcl(ee);
    assertEquals(numberOfAces + 1, aclAfterReadableAdded.getEntries().size());

    // force the addition of duplicate ACE read, fish group on the same experiment. Note that in the current
    // implementation this only adds one - we already avoid duplicates.
    List<GrantedAuthority> groupAuthorities = this.userManager.findGroupAuthorities(groupName);
    GrantedAuthority ga = groupAuthorities.get(0);
    aclAfterReadableAdded.insertAce(aclAfterReadableAdded.getEntries().size(), BasePermission.READ,
            new AclGrantedAuthoritySid(this.userManager.getRolePrefix() + ga), true);
    this.aclTestUtils.update(aclAfterReadableAdded);
    MutableAcl aclAfterReadableAddedDuplicate = aclTestUtils.getAcl(ee);
    assertEquals(numberOfAces + 1, aclAfterReadableAddedDuplicate.getEntries().size());

    // remove the ace now and check removed permission completely.
    this.securityService.makeUnreadableByGroup(ee, groupName);
    MutableAcl aclAfterReadableAddedDuplicateRemoval = aclTestUtils.getAcl(ee);
    assertEquals(numberOfAces, aclAfterReadableAddedDuplicateRemoval.getEntries().size());
    List<AccessControlEntry> entriesAfterDelete = aclAfterReadableAddedDuplicateRemoval.getEntries();
    assertEquals(numberOfAces, entriesAfterDelete.size());

    // also check that the right ACE check the principals
    Collection<String> principals = new ArrayList<>();
    principals.add("AclGrantedAuthoritySid[GROUP_ADMIN]");
    principals.add("AclGrantedAuthoritySid[GROUP_AGENT]");
    principals.add("AclPrincipalSid[salmonid]");
    principals.add("AclPrincipalSid[salmonid]");

    for (AccessControlEntry accessControl : entriesAfterDelete) {
        Sid sid = accessControl.getSid();
        assertTrue(principals.contains(sid.toString()));
        // remove it once in case found in case of duplicates
        principals.remove(sid.toString());
    }//from   ww w.j a va2  s  .  co  m
    // clean up the groups
    this.userManager.deleteGroup(groupName);
    // userManager.deleteUser( username );
}

From source file:uk.ac.ebi.intact.editor.services.curate.interaction.InteractionEditorService.java

private void initialiseVariableParameters(Collection<VariableParameterValueSet> parameters) {
    Collection<VariableParameterValueSet> originalSet = new ArrayList<VariableParameterValueSet>(parameters);
    for (VariableParameterValueSet set : originalSet) {
        if (set instanceof IntactVariableParameterValueSet && !isVariableParameterValueSetInitialised(set)) {
            VariableParameterValueSet reloaded = initialiseVariableParameterValueSet(set);
            if (reloaded != set) {
                parameters.remove(set);
                parameters.add(reloaded);
            }/*from  w  w  w  .j  a v  a 2 s  .  c  om*/
        }
    }
}

From source file:com.twinsoft.convertigo.beans.core.RequestableStep.java

private void removeOrderedVariable(Long value) {
    Collection<Long> ordered = orderedVariables.get(0);
    ordered.remove(value);
    hasChanged = true;/*from  ww  w . ja v a 2s . c o  m*/
}

From source file:org.impalaframework.module.definition.DependencyManager.java

/**
 * Returns the vertices contained in <code>sortable</code> according to the topological
 * sort order of vertices known to this {@link DependencyManager} instance.
 *///  w w  w.  j  av  a 2 s. c om
private List<Vertex> populatedOrderedVertices(Collection<Vertex> sortable) {

    Assert.notNull(sortable, "sortable cannot be null");

    Collection<Vertex> copy = new HashSet<Vertex>(sortable);
    List<Vertex> ordered = new ArrayList<Vertex>();

    //get the ordered to remove list
    List<Vertex> sorted = this.sorted;
    for (Vertex vertex : sorted) {
        if (copy.contains(vertex)) {
            ordered.add(vertex);
            copy.remove(vertex);
        }
    }

    if (!copy.isEmpty()) {
        //should not be possible, as all of the modules have already been converted into vertexes. Hence
        //would be the sign of an non-obvious programming error
        throw new InvalidStateException(
                "Sortable list contains modules not known by the current instance of dependency registry: "
                        + GraphHelper.getModuleNamesFromCollection(copy));
    }

    return ordered;
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.registry.VersionRegisterableScriptClasspathScanner.java

/**
 * Matches and processes a folder level defining a version a script is provided in.
 *
 * @param resourcePattern//w  w w  . j av  a  2 s .c  o  m
 *            the resource pattern for the current level
 * @param patternStack
 *            the stack of patterns evaluated thus far
 * @param versionDataContainer
 *            the container for collection version information
 * @param subRegistry
 *            the sub-registry to register the script in or {@code null} if no sub-registry is to be used
 * @param fileName
 *            the name of the file currently evaluated
 * @throws IOException
 *             if any exception occurs handling the resource
 */
protected void matchVersion(final String resourcePattern, final Collection<String> patternStack,
        final VersionRegisterableScriptAdapter<Script> versionDataContainer, final String subRegistry,
        final String fileName) throws IOException {
    final String versionStr = fileName;

    LOGGER.debug("Matched version {} fragment", versionStr);

    versionDataContainer.setVersion(versionStr);
    patternStack.add(VERSION_PATTERN);
    try {
        this.scanNextLevel(resourcePattern + "/" + fileName, patternStack, versionDataContainer, subRegistry);
    } finally {
        versionDataContainer.setVersion((VersionNumber) null);
        patternStack.remove(VERSION_PATTERN);
    }
}