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:net.sourceforge.fenixedu.domain.Enrolment.java

final public Collection<Enrolment> getBrothers() {
    final Collection<Enrolment> result = new HashSet<Enrolment>();

    result.addAll(getStudentCurricularPlan().getEnrolments(getCurricularCourse()));
    result.remove(this);

    return result;
}

From source file:nl.strohalm.cyclos.services.groups.GroupServiceImpl.java

@SuppressWarnings("unchecked")
private <G extends Group> G save(G group) {
    if (group.isTransient()) {
        group = groupDao.insert(group);/*from   ww  w. ja v  a  2 s . co  m*/
    } else {
        // We must keep the many-to-many relationships, or they would be cleared...
        final Group currentGroup = load(group.getId(), FETCH_TO_KEEP_DATA);

        group.setPermissions(new HashSet<Permission>(currentGroup.getPermissions()));
        group.setTransferTypes(new ArrayList<TransferType>(currentGroup.getTransferTypes()));
        group.setConversionSimulationTTs(
                new ArrayList<TransferType>(currentGroup.getConversionSimulationTTs()));
        group.setGuaranteeTypes(new ArrayList<GuaranteeType>(currentGroup.getGuaranteeTypes()));

        if (group instanceof SystemGroup) {
            final SystemGroup systemGroup = (SystemGroup) group;
            final SystemGroup currentSystemGroup = ((SystemGroup) currentGroup);
            systemGroup.setDocuments(new ArrayList<Document>(currentSystemGroup.getDocuments()));
            systemGroup.setMessageCategories(
                    new ArrayList<MessageCategory>(currentSystemGroup.getMessageCategories()));
            systemGroup.setChargebackTransferTypes(
                    new ArrayList<TransferType>(currentSystemGroup.getChargebackTransferTypes()));
        }

        if (group instanceof AdminGroup) {
            final AdminGroup adminGroup = (AdminGroup) group;
            final AdminGroup currentAdminGroup = ((AdminGroup) currentGroup);
            adminGroup.setTransferTypesAsMember(
                    new ArrayList<TransferType>(currentAdminGroup.getTransferTypesAsMember()));
            adminGroup.setManagesGroups(new ArrayList<MemberGroup>(currentAdminGroup.getManagesGroups()));
            adminGroup.setViewConnectedAdminsOf(
                    new ArrayList<AdminGroup>(currentAdminGroup.getViewConnectedAdminsOf()));
            adminGroup.setViewInformationOf(
                    new ArrayList<SystemAccountType>(currentAdminGroup.getViewInformationOf()));
            adminGroup.setViewAdminRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getViewAdminRecordTypes()));
            adminGroup.setCreateAdminRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getCreateAdminRecordTypes()));
            adminGroup.setModifyAdminRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getModifyAdminRecordTypes()));
            adminGroup.setDeleteAdminRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getDeleteAdminRecordTypes()));
            adminGroup.setViewMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getViewMemberRecordTypes()));
            adminGroup.setCreateMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getCreateMemberRecordTypes()));
            adminGroup.setModifyMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getModifyMemberRecordTypes()));
            adminGroup.setDeleteMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentAdminGroup.getDeleteMemberRecordTypes()));
        }
        if (group instanceof BrokerGroup) {
            final BrokerGroup brokerGroup = (BrokerGroup) group;
            final BrokerGroup currentBrokerGroup = (BrokerGroup) currentGroup;

            final List<Document> brokerDocuments = new ArrayList<Document>();
            if (currentBrokerGroup.getBrokerDocuments() != null) {
                brokerDocuments.addAll(currentBrokerGroup.getBrokerDocuments());
            }
            brokerGroup.setBrokerDocuments(brokerDocuments);

            final List<AccountType> brokerCanViewInformationOf = new ArrayList<AccountType>();
            if (brokerGroup.getBrokerCanViewInformationOf() != null) {
                brokerCanViewInformationOf.addAll(brokerGroup.getBrokerCanViewInformationOf());
            }
            brokerGroup.setBrokerCanViewInformationOf(brokerCanViewInformationOf);

            brokerGroup.setTransferTypesAsMember(
                    new ArrayList<TransferType>(currentBrokerGroup.getTransferTypesAsMember()));
            brokerGroup.setBrokerConversionSimulationTTs(
                    new ArrayList<TransferType>(currentBrokerGroup.getBrokerConversionSimulationTTs()));
            brokerGroup.setBrokerMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentBrokerGroup.getBrokerMemberRecordTypes()));
            brokerGroup.setBrokerCreateMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentBrokerGroup.getBrokerCreateMemberRecordTypes()));
            brokerGroup.setBrokerModifyMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentBrokerGroup.getBrokerModifyMemberRecordTypes()));
            brokerGroup.setBrokerDeleteMemberRecordTypes(
                    new ArrayList<MemberRecordType>(currentBrokerGroup.getBrokerDeleteMemberRecordTypes()));

            // "possibleInitialGroups" is updated at edit group screen, so it doesn't need to be copied
        }
        if (group instanceof MemberGroup) {
            final MemberGroup memberGroup = (MemberGroup) group;
            final MemberGroup currentMemberGroup = (MemberGroup) currentGroup;
            memberGroup.setAccountSettings(currentMemberGroup.getAccountSettings());

            // Ensure that no channel will be set by default if it's not accessible
            memberGroup.getDefaultChannels().retainAll(memberGroup.getChannels());

            // Ensure the removedChannels collection contains the channels which were removed
            final Collection<Channel> removedChannels = new HashSet<Channel>();
            removedChannels.addAll(currentMemberGroup.getChannels());
            removedChannels.removeAll(memberGroup.getChannels());

            final List<MemberGroup> viewProfile = new ArrayList<MemberGroup>();
            if (currentMemberGroup.getCanViewProfileOfGroups() != null) {
                viewProfile.addAll(currentMemberGroup.getCanViewProfileOfGroups());
            }
            memberGroup.setCanViewProfileOfGroups(viewProfile);

            final List<AccountType> canViewInformationOf = new ArrayList<AccountType>();
            if (currentMemberGroup.getCanViewInformationOf() != null) {
                canViewInformationOf.addAll(currentMemberGroup.getCanViewInformationOf());
            }
            memberGroup.setCanViewInformationOf(canViewInformationOf);

            final List<MemberGroup> viewAds = new ArrayList<MemberGroup>();
            if (currentMemberGroup.getCanViewAdsOfGroups() != null) {
                viewAds.addAll(currentMemberGroup.getCanViewAdsOfGroups());
            }
            memberGroup.setCanViewAdsOfGroups(viewAds);

            final List<AdminGroup> managedByGroups = new ArrayList<AdminGroup>();
            if (currentMemberGroup.getManagedByGroups() != null) {
                managedByGroups.addAll(currentMemberGroup.getManagedByGroups());
            }
            memberGroup.setManagedByGroups(managedByGroups);

            // "defaultMailMessages" is updated at edit group screen, so it doesn't need to be copied
            // "smsMessages" is updated at edit group screen, so it doesn't need to be copied
            // "defaultSmsMessages" is updated at edit group screen, so it doesn't need to be copied
            // "channels" is updated at edit group screen, so it doesn't need to be copied
            // "defaultChannels" is updated at edit group screen, so it doesn't need to be copied

            // Add the main web access to default and accessible channels.
            final Channel webChannel = channelService.loadByInternalName(Channel.WEB);
            memberGroup.setChannels(
                    CollectionUtils.union(memberGroup.getChannels(), Collections.singleton(webChannel)));
            memberGroup.setDefaultChannels(
                    CollectionUtils.union(memberGroup.getDefaultChannels(), Collections.singleton(webChannel)));

            final List<Channel> requestPaymentByChannels = new ArrayList<Channel>();
            if (currentMemberGroup.getRequestPaymentByChannels() != null) {
                requestPaymentByChannels.addAll(currentMemberGroup.getRequestPaymentByChannels());
            }
            memberGroup.setRequestPaymentByChannels(requestPaymentByChannels);

            final MemberGroupSettings memberSettings = memberGroup.getMemberSettings();
            memberSettings
                    .setGroupAfterExpiration(fetchService.fetch(memberSettings.getGroupAfterExpiration()));

            // Update the basic settings of operator groups for members in this group
            final GroupQuery operatorQuery = new GroupQuery();
            operatorQuery.setNature(Group.Nature.OPERATOR);
            operatorQuery.fetch(
                    RelationshipHelper.nested(OperatorGroup.Relationships.MEMBER, Element.Relationships.GROUP));
            final List<OperatorGroup> operatorGroups = (List<OperatorGroup>) groupDao.search(operatorQuery);
            for (final OperatorGroup operatorGroup : operatorGroups) {
                if (operatorGroup.getMember().getGroup().equals(memberGroup)) {
                    groupDao.update(operatorGroup);
                }
            }
            final List<MemberGroup> canIssueCertificationToGroups = new ArrayList<MemberGroup>();
            if (currentMemberGroup.getCanIssueCertificationToGroups() != null) {
                canIssueCertificationToGroups.addAll(currentMemberGroup.getCanIssueCertificationToGroups());
            }
            memberGroup.setCanIssueCertificationToGroups(canIssueCertificationToGroups);

            final List<MemberGroup> canBuyWithPaymentObligationsFromGroups = new ArrayList<MemberGroup>();
            if (currentMemberGroup.getCanBuyWithPaymentObligationsFromGroups() != null) {
                canBuyWithPaymentObligationsFromGroups
                        .addAll(currentMemberGroup.getCanBuyWithPaymentObligationsFromGroups());
            }
            memberGroup.setCanBuyWithPaymentObligationsFromGroups(canBuyWithPaymentObligationsFromGroups);

            // Ensure the message notification types are not present on the group for SMS
            final Collection<Message.Type> smsMessages = memberGroup.getSmsMessages();
            if (smsMessages != null) {
                smsMessages.remove(Message.Type.FROM_MEMBER);
                smsMessages.remove(Message.Type.FROM_ADMIN_TO_GROUP);
                smsMessages.remove(Message.Type.FROM_ADMIN_TO_MEMBER);
            }
            final Collection<Type> defaultSmsMessages = memberGroup.getDefaultSmsMessages();
            if (defaultSmsMessages != null) {
                defaultSmsMessages.remove(Message.Type.FROM_MEMBER);
                defaultSmsMessages.remove(Message.Type.FROM_ADMIN_TO_GROUP);
                defaultSmsMessages.remove(Message.Type.FROM_ADMIN_TO_MEMBER);
            }

            // Remove from all members channels which are no longer accessible
            elementDao.removeChannelsFromMembers(memberGroup, removedChannels);

            // ensure activation status
            if (memberGroup.isRemoved()) {
                memberGroup.setActive(false);
            }
        }
        if (group instanceof OperatorGroup) {
            final OperatorGroup operatorGroup = (OperatorGroup) group;
            final OperatorGroup currentOperatorGroup = (OperatorGroup) currentGroup;

            // Check the account types
            final List<AccountType> canViewInformationOf = new ArrayList<AccountType>();
            if (currentOperatorGroup.getCanViewInformationOf() != null) {
                canViewInformationOf.addAll(currentOperatorGroup.getCanViewInformationOf());
            }
            operatorGroup.setCanViewInformationOf(canViewInformationOf);
        }
        group = groupDao.update(group);
    }
    // Ensure the permissions cache for this group is evicted
    permissionService.evictCache(group);
    return group;
}

From source file:eu.medsea.mimeutil.detector.OpendesktopMimeDetector.java

private Collection normalizeWeightedMimeList(Collection weightedMimeTypes) {
    Collection mimeTypes = new LinkedHashSet();

    // Sort the weightedMimeTypes
    Collections.sort((List) weightedMimeTypes, new Comparator() {
        public int compare(Object obj1, Object obj2) {
            return ((WeightedMimeType) obj1).weight - ((WeightedMimeType) obj2).weight;
        }//from  ww  w  .  j  a  v a2s .  c o m
    });

    // Keep only globs with the biggest weight. They are in weight order at
    // this point
    int weight = 0;
    int patternLen = 0;
    for (Iterator it = weightedMimeTypes.iterator(); it.hasNext();) {
        WeightedMimeType mw = (WeightedMimeType) it.next();
        if (weight < mw.weight) {
            weight = mw.weight;
        }
        if (weight >= mw.weight) {
            if (mw.pattern.length() > patternLen) {
                patternLen = mw.pattern.length();
            }
            mimeTypes.add(mw);
        }
    }

    // Now keep only the longest patterns
    for (Iterator it = weightedMimeTypes.iterator(); it.hasNext();) {
        WeightedMimeType mw = (WeightedMimeType) it.next();
        if (mw.pattern.length() < patternLen) {
            mimeTypes.remove(mw);
        }
    }

    // Could possibly have multiple mimeTypes here with the same weight and
    // pattern length. Can even have multiple entries for the same type so
    // lets remove
    // any duplicates by copying entries to a HashSet that can only have a
    // single instance
    // of each type
    Collection _mimeTypes = new HashSet();
    for (Iterator it = mimeTypes.iterator(); it.hasNext();) {
        _mimeTypes.add(((WeightedMimeType) it.next()).toString());
    }
    return _mimeTypes;
}

From source file:io.fabric8.tooling.archetype.builder.ArchetypeBuilderTest.java

@Test
public void buildAllExampleArchetypes() throws Exception {
    File srcDir = new File(basedir, "../examples").getCanonicalFile();

    builder.configure();/*from w ww.  j a v a  2  s. c om*/
    try {
        List<String> dirs = new ArrayList<String>();
        builder.generateArchetypes("java", srcDir, new File(basedir, "target/test-archetypes"), true, dirs,
                null);
    } finally {
        LOG.info("Completed the generation. Closing!");
        builder.close();
    }

    Collection<File> files = FileUtils.listFilesAndDirs(
            new File("target/test-archetypes/java-hello-world-archetype"), TrueFileFilter.INSTANCE,
            TrueFileFilter.INSTANCE);
    String[] resources = new String[] { "", "/pom.xml", "/.gitignore", "/src", "/src/main",
            "/src/main/resources", "/src/main/resources/archetype-resources",
            "/src/main/resources/archetype-resources/ReadMe.txt",
            "/src/main/resources/archetype-resources/pom.xml", "/src/main/resources/archetype-resources/src",
            "/src/main/resources/archetype-resources/src/test",
            "/src/main/resources/archetype-resources/src/test/resources",
            "/src/main/resources/archetype-resources/src/test/resources/logback-test.xml",
            "/src/main/resources/archetype-resources/src/test/java",
            "/src/main/resources/archetype-resources/src/test/java/HelloTest.java",
            "/src/main/resources/archetype-resources/src/main",
            "/src/main/resources/archetype-resources/src/main/resources",
            "/src/main/resources/archetype-resources/src/main/resources/application.properties",
            "/src/main/resources/archetype-resources/src/main/java",
            "/src/main/resources/archetype-resources/src/main/java/impl",
            "/src/main/resources/archetype-resources/src/main/java/impl/DefaultHello.java",
            "/src/main/resources/archetype-resources/src/main/java/HelloInterface.java",
            "/src/main/resources-filtered", "/src/main/resources-filtered/META-INF",
            "/src/main/resources-filtered/META-INF/maven",
            "/src/main/resources-filtered/META-INF/maven/archetype-metadata.xml", };
    for (String r : resources) {
        assertTrue(files.remove(new File("target/test-archetypes/java-hello-world-archetype" + r)));
    }
    assertTrue("Failed to create correct Archetype project", files.isEmpty());
}

From source file:org.apache.flex.compiler.internal.projects.LibraryPathManager.java

/**
 * Compute the set of libraries to add and remove.<br>
 * Remove all the existing libraries that are in the new library path.<br>
 * Add all the new library path that are not in the existing library path.
 * //  ww  w  .  java2 s.  c om
 * @param swcFilePaths Set of swcs to load. The iterator will iterate over
 * the swcs in priority order.
 * @param swcFilesToAdd SWC files to be added
 * @param swcFilesToRemove SWD files to be removed
 */
private void computeAddRemoveSet(final Set<String> swcFilePaths, final Collection<String> swcFilesToAdd,
        final Collection<String> swcFilesToRemove) {
    // only add a SWC to the swcFilesToAdd if it exists in on disk. swcFilePaths
    // can have files which don't exist yet, as a library project we depend on
    // may not have been compiled yet.
    for (String swcPath : swcFilePaths) {
        File f = new File(swcPath);
        if (f.exists())
            swcFilesToAdd.add(swcPath);
    }

    Iterator<String> swcFilePathsIter = swcFilePaths.iterator();
    boolean swcOrderDiffers = false;

    // if an existing swc is not in the newPath, it needs to be removed.
    for (final String existingSWCFilePath : libraryFilePaths.keySet()) {
        /*
         * If the order of the SWCs is different then add and remove all 
         * SWCs in the list after and including that SWC.
         */
        String newSWCFilePath = null;

        if (!swcOrderDiffers) {
            if (!swcFilePathsIter.hasNext()) {
                // we can run past the swcFilePaths when removing the last
                // element from the library path
                swcOrderDiffers = true;
            } else {
                newSWCFilePath = swcFilePathsIter.next();

                if (existingSWCFilePath.equals(newSWCFilePath)) {
                    swcFilesToAdd.remove(existingSWCFilePath);
                    continue;
                } else {
                    swcOrderDiffers = true;
                }
            }
        }

        /*
         * If the SWC order is detected as being different, then
         * always remove existing SWCs. Remove SWCs from the "add"
         * list that are no longer needed.
         */
        if (swcOrderDiffers) {
            swcFilesToRemove.add(existingSWCFilePath);

            if (!swcFilesToAdd.contains(existingSWCFilePath))
                swcFilesToAdd.remove(existingSWCFilePath);
        }
    }
}

From source file:com.amalto.core.storage.hibernate.FullTextQueryHandler.java

@Override
public StorageResults visit(Select select) {
    // TMDM-4654: Checks if entity has a composite PK.
    Set<ComplexTypeMetadata> compositeKeyTypes = new HashSet<ComplexTypeMetadata>();
    // TMDM-7496: Search should include references to reused types
    Collection<ComplexTypeMetadata> types = new HashSet<ComplexTypeMetadata>(
            select.accept(new SearchTransitiveClosure(storage)));
    for (ComplexTypeMetadata type : types) {
        if (type.getKeyFields().size() > 1) {
            compositeKeyTypes.add(type);
        }//from  w ww  . j a v  a  2 s.  c  om
    }
    if (!compositeKeyTypes.isEmpty()) {
        StringBuilder message = new StringBuilder();
        Iterator it = compositeKeyTypes.iterator();
        while (it.hasNext()) {
            ComplexTypeMetadata compositeKeyType = (ComplexTypeMetadata) it.next();
            message.append(compositeKeyType.getName());
            if (it.hasNext()) {
                message.append(',');
            }
        }
        throw new FullTextQueryCompositeKeyException(message.toString());
    }
    // Removes Joins and joined fields.
    List<Join> joins = select.getJoins();
    if (!joins.isEmpty()) {
        Set<ComplexTypeMetadata> joinedTypes = new HashSet<ComplexTypeMetadata>();
        for (Join join : joins) {
            joinedTypes.add(join.getRightField().getFieldMetadata().getContainingType());
        }
        for (ComplexTypeMetadata joinedType : joinedTypes) {
            types.remove(joinedType);
        }
        List<TypedExpression> filteredFields = new LinkedList<TypedExpression>();
        for (TypedExpression expression : select.getSelectedFields()) {
            if (expression instanceof Field) {
                FieldMetadata fieldMetadata = ((Field) expression).getFieldMetadata();
                if (joinedTypes.contains(fieldMetadata.getContainingType())) {
                    TypeMapping mapping = mappings.getMappingFromDatabase(fieldMetadata.getContainingType());
                    filteredFields.add(new Alias(new StringConstant(StringUtils.EMPTY),
                            mapping.getUser(fieldMetadata).getName()));
                } else {
                    filteredFields.add(expression);
                }
            } else {
                filteredFields.add(expression);
            }
        }
        selectedFields.clear();
        selectedFields.addAll(filteredFields);
    }
    // Handle condition
    Condition condition = select.getCondition();
    if (condition == null) {
        throw new IllegalArgumentException("Expected a condition in select clause but got 0.");
    }
    // Create Lucene query (concatenates all sub queries together).
    FullTextSession fullTextSession = Search.getFullTextSession(session);
    Query parsedQuery = select.getCondition().accept(new LuceneQueryGenerator(types));
    // Create Hibernate Search query
    Set<Class> classes = new HashSet<Class>();
    for (ComplexTypeMetadata type : types) {
        String className = ClassCreator.getClassName(type.getName());
        try {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            classes.add(contextClassLoader.loadClass(className));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not find class '" + className + "'.", e);
        }
    }
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(parsedQuery,
            classes.toArray(new Class<?>[classes.size()]));
    // Very important to leave this null (would disable ability to search across different types)
    fullTextQuery.setCriteriaQuery(null);
    fullTextQuery.setSort(Sort.RELEVANCE); // Default sort (if no order by specified).
    query = EntityFinder.wrap(fullTextQuery, (HibernateStorage) storage, session, select.getTypes()); // ensures only MDM entity objects are returned.
    // Order by
    for (OrderBy current : select.getOrderBy()) {
        current.accept(this);
    }
    // Paging
    Paging paging = select.getPaging();
    paging.accept(this);
    pageSize = paging.getLimit();
    boolean hasPaging = pageSize < Integer.MAX_VALUE;
    if (!hasPaging) {
        return createResults(query.scroll(ScrollMode.FORWARD_ONLY));
    } else {
        return createResults(query.list());
    }
}

From source file:org.opengroupware.logic.authz.OGoProjectPermissionHandler.java

@SuppressWarnings("unchecked")
public Map<EOKeyGlobalID, Object> fetchInfosForGlobalIDs(OGoAuthzFetchContext _ac, OGoDatabase _db,
        Collection<EOKeyGlobalID> _gids) {
    if (_gids == null || _gids.size() == 0)
        return null;
    boolean debugOn = log.isDebugEnabled();

    // TBD: why do we need to return all the data? We could evaluate the perms
    //      inline?!

    /* find entities and fetch-specs */

    EOEntity projectsEntity = _db.entityNamed("Projects");
    EOEntity aclEntity = _db.entityNamed("ProjectsToCompany");

    EOFetchSpecification pFS = projectsEntity.fetchSpecificationNamed("authzFetch");
    EOFetchSpecification aFS = aclEntity.fetchSpecificationNamed("authzFetch");

    /* prepare result set */

    Map<EOKeyGlobalID, Object> infos = new HashMap<EOKeyGlobalID, Object>(_gids.size());

    /* Extract primary key values from global-ids.
     * Also: we set the minimum access-level for each gid in the map, so that
     * we can be sure that entries w/o ACEs do get the no-access permission. 
     *//*from   ww w . j av  a 2s .  com*/
    Map<Number, EOKeyGlobalID> pkeyToGlobalID = new HashMap<Number, EOKeyGlobalID>(_gids.size());
    for (EOKeyGlobalID gid : _gids) /* extract key */
        pkeyToGlobalID.put(gid.toNumber(), gid);

    Collection<Number> pkeys = pkeyToGlobalID.keySet();
    if (debugOn)
        log.debug("fetch project-infos: #" + pkeys.size());

    /* qualify fetch-specs */

    pFS = pFS.fetchSpecificationWithQualifierBindings("ids", pkeys, "authIds", _ac.authIds);

    /* prepare channel and fetch */

    EOAdaptorChannel channel = _db.adaptor().openChannelFromPool();
    try {
        /* Note: the query already filters all projects, so we need to check
         *       the requested pkeys and if they are not in the resultset,
         *       we have no access.
         * Note: this returns EORecordMap's! (cannot be enhanced)
         */
        List<Map<String, Object>> projects = channel.selectAttributes(null, pFS, false, projectsEntity);
        Collection<Number> aclKeys = null;

        for (Map<String, Object> project : projects) {
            Number pkey = (Number) project.get("project_id");
            EOKeyGlobalID pgid = pkeyToGlobalID.get(pkey);

            /* Check owner inline, if we have the owner, we don't need to check
             * anything else, he has always full access
             */
            Number ownerId = (Number) project.get("owner_id");
            if (_ac.contextHasPrincipalId(ownerId)) {
                if (debugOn)
                    log.debug("  detected ownership: " + pkey);
                _ac.recordPermissionsForGlobalID(ownerPermissions, pgid);
                pkeys.remove(pkey); /* optimization to avoid rechecks below */
                continue;
            }

            /* we need a copy, so that we can modify it */
            project = new HashMap<String, Object>(project);

            /* attach empty-default-ACL */
            project.put("aclPermissions", OGoAuthzFetchContext.noPermission);

            if (aclKeys == null)
                aclKeys = new ArrayList<Number>(pkeys.size());
            aclKeys.add(pkey);

            infos.put(pgid, project);
        }

        /* Loop over requested pkeys and check whether they are in the result
         * set (otherwise we have no access).
         */
        if (aclKeys == null || aclKeys.size() == 0) {
            /* no other keys in result set*/
            // TBD: does this conflict with teamId => readonly?
            if (debugOn)
                log.debug("  no acl keys found, all forbidden: " + pkeys);
            for (Number pkey : pkeys) {
                EOKeyGlobalID pgid = pkeyToGlobalID.get(pkey);
                _ac.recordPermissionsForGlobalID(OGoAuthzFetchContext.noPermission, pgid);
            }
        } else {
            for (Number pkey : pkeys) {
                if (!aclKeys.contains(pkey)) {
                    /* the requested pkey is not in our resultset */
                    if (debugOn)
                        log.debug("  acl key not found, forbidden: " + pkey);
                    EOKeyGlobalID pgid = pkeyToGlobalID.get(pkey);
                    _ac.recordPermissionsForGlobalID(OGoAuthzFetchContext.noPermission, pgid);
                }
            }
        }

        /* fetch ACLs */

        if (aclKeys != null && aclKeys.size() > 0) {
            if (debugOn)
                log.debug("  check ACLs: " + aclKeys);
            aFS = aFS.fetchSpecificationWithQualifierBindings("ids", aclKeys, "authIds", _ac.authIds);

            List<Map<String, Object>> acls = channel.selectAttributes(null, aFS, false, aclEntity);
            for (Map<String, Object> ace : acls) {
                if (!UObject.boolValue(ace.get("has_access"))) {
                    if (debugOn)
                        log.debug("  skip non-ACE ...");
                    continue; /* an attached record, not an ACE (should not happen) */
                }

                if (!_ac.contextHasPrincipalId((Number) ace.get("company_id"))) {
                    if (debugOn)
                        log.debug("  ACE not covered: " + ace);
                    continue; /* should be covered by the fetch, but who knows */
                }

                EOKeyGlobalID pgid = pkeyToGlobalID.get(ace.get("project_id"));
                Map<String, Object> info = (Map<String, Object>) infos.get(pgid);
                if (info == null) {
                    log.warn("no info fetched for project: " + pgid);
                    info = new HashMap<String, Object>(2);
                    infos.put(pgid, info);
                }

                /* combine permissions */

                String perm = (String) info.get("aclPermissions");
                if (perm == null) {
                    log.warn("info has no acl permissions: " + info);
                    perm = OGoAuthzFetchContext.noPermission;
                }
                if (debugOn)
                    log.debug("  join  ACE: " + pgid + " => base '" + perm + "'");

                perm = UString.unionCharacterSets(perm, (String) ace.get("access_right")); // raw
                info.put("aclPermissions", perm);

                if (debugOn)
                    log.debug("  found ACE: " + pgid + " => '" + perm + "'");
            }

        }

        // TBD: evaluate infos inline. Hm. Would this give us anything? Its done
        //      by the next auth-iteration anyways
        // System.err.println("I: " + infos);
    } finally {
        if (channel != null)
            _db.adaptor().releaseChannel(channel);
    }

    return infos;
}

From source file:org.fao.geonet.api.users.UsersApi.java

private void setUserGroups(final User user, List<GroupElem> userGroups) throws Exception {

    final GroupRepository groupRepository = ApplicationContextHolder.get().getBean(GroupRepository.class);
    final UserGroupRepository userGroupRepository = ApplicationContextHolder.get()
            .getBean(UserGroupRepository.class);

    Collection<UserGroup> all = userGroupRepository.findAll(UserGroupSpecs.hasUserId(user.getId()));

    // Have a quick reference of existing groups and profiles for this user
    Set<String> listOfAddedProfiles = new HashSet<String>();
    for (UserGroup ug : all) {
        String key = ug.getProfile().name() + ug.getGroup().getId();
        if (!listOfAddedProfiles.contains(key)) {
            listOfAddedProfiles.add(key);
        }//from w  ww  .jav  a  2 s .  c  om
    }

    // We start removing all old usergroup objects. We will remove the
    // explicitly defined for this call
    Collection<UserGroup> toRemove = new ArrayList<UserGroup>();
    toRemove.addAll(all);

    // New pairs of group-profile we need to add
    Collection<UserGroup> toAdd = new ArrayList<UserGroup>();

    // For each of the parameters on the request, make sure the group is
    // updated.
    for (GroupElem element : userGroups) {
        Integer groupId = element.getId();
        Group group = groupRepository.findOne(groupId);
        String profile = element.getProfile();
        // The user has a new group and profile

        // Combine all groups editor and reviewer groups
        if (profile.equals(Profile.Reviewer.name())) {
            final UserGroup userGroup = new UserGroup().setGroup(group).setProfile(Profile.Editor)
                    .setUser(user);
            String key = Profile.Editor.toString() + group.getId();
            if (!listOfAddedProfiles.contains(key)) {
                toAdd.add(userGroup);
                listOfAddedProfiles.add(key);
            }

            // If the user is already part of this group with this profile,
            // leave it alone:
            for (UserGroup g : all) {
                if (g.getGroup().getId() == groupId && g.getProfile().equals(Profile.Editor)) {
                    toRemove.remove(g);
                }
            }
        }

        final UserGroup userGroup = new UserGroup().setGroup(group)
                .setProfile(Profile.findProfileIgnoreCase(profile)).setUser(user);
        String key = profile + group.getId();
        if (!listOfAddedProfiles.contains(key)) {
            toAdd.add(userGroup);
            listOfAddedProfiles.add(key);

        }

        // If the user is already part of this group with this profile,
        // leave it alone:
        for (UserGroup g : all) {
            if (g.getGroup().getId() == groupId && g.getProfile().name().equalsIgnoreCase(profile)) {
                toRemove.remove(g);
            }
        }
    }

    // Remove deprecated usergroups (if any)
    userGroupRepository.delete(toRemove);

    // Add only new usergroups (if any)
    userGroupRepository.save(toAdd);

}

From source file:org.cesecore.certificates.ca.X509CA.java

/**
 * Method to upgrade new (or existing external caservices) This method needs to be called outside the regular upgrade since the CA isn't
 * instantiated in the regular upgrade.// ww w  .  j av  a 2 s.  c om
 */
@SuppressWarnings({ "rawtypes", "deprecation" })
public boolean upgradeExtendedCAServices() {
    boolean retval = false;
    // call upgrade, if needed, on installed CA services
    Collection<Integer> externalServiceTypes = getExternalCAServiceTypes();
    if (!CesecoreConfiguration.getCaKeepOcspExtendedService()
            && externalServiceTypes.contains(ExtendedCAServiceTypes.TYPE_OCSPEXTENDEDSERVICE)) {
        //This type has been removed, so remove it from any CAs it's been added to as well.
        externalServiceTypes.remove(ExtendedCAServiceTypes.TYPE_OCSPEXTENDEDSERVICE);
        data.put(EXTENDEDCASERVICES, externalServiceTypes);
        retval = true;
    }

    for (Integer type : externalServiceTypes) {
        ExtendedCAService service = getExtendedCAService(type);
        if (service != null) {
            if (Float.compare(service.getLatestVersion(), service.getVersion()) != 0) {
                retval = true;
                service.upgrade();
                setExtendedCAServiceData(service.getExtendedCAServiceInfo().getType(),
                        (HashMap) service.saveData());
            } else if (service.isUpgraded()) {
                // Also return true if the service was automatically upgraded by a UpgradeableDataHashMap.load, which calls upgrade automagically. 
                retval = true;
                setExtendedCAServiceData(service.getExtendedCAServiceInfo().getType(),
                        (HashMap) service.saveData());
            }
        } else {
            log.error("Extended service is null, can not upgrade service of type: " + type);
        }
    }
    return retval;
}

From source file:uk.nhs.cfh.dsp.snomed.normaliser.impl.NormalFormGeneratorImpl.java

/**
 * Gets the strict non redundant merged role groups.
 *
 * @param parentRoleGroupExpressions the parent role group expressions
 * @param conceptRoleGroupExpressions the concept role group expressions
 * @return the strict non redundant merged role groups
 *///w w  w. ja v a  2 s  . c  o  m
private Collection<SnomedRoleGroupExpression> getStrictNonRedundantMergedRoleGroups(
        Collection<SnomedRoleGroupExpression> parentRoleGroupExpressions,
        Collection<SnomedRoleGroupExpression> conceptRoleGroupExpressions) {
    if (parentRoleGroupExpressions.size() == 0) {
        return conceptRoleGroupExpressions;
    } else if (conceptRoleGroupExpressions.size() == 0) {
        return parentRoleGroupExpressions;
    } else {
        Collection<SnomedRoleGroupExpression> groupExpressionsCopy = new ArrayList<SnomedRoleGroupExpression>(
                conceptRoleGroupExpressions);
        for (SnomedRoleGroupExpression parentRoleGroupExpression : parentRoleGroupExpressions) {
            for (SnomedRoleGroupExpression conceptRoleGroupExpression : groupExpressionsCopy) {
                ExpressionComparator.Subsumption_Relation relation = expressionComparator
                        .getSubsumptionRelation(parentRoleGroupExpression, conceptRoleGroupExpression);
                if (ExpressionComparator.Subsumption_Relation.SAME == relation) {
                    conceptRoleGroupExpressions.remove(conceptRoleGroupExpression);
                }
            }
        }

        return conceptRoleGroupExpressions;
    }
}