Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java
### 代码内容：
/**
 * The contents of this file are subject to the license and copyright
 * detailed in the LICENSE and NOTICE files at the root of the source
 * tree and available online at
 *
 * http://www.dspace.org/license/
 */
package org.dspace.content;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.dspace.app.util.AuthorizeUtil;
import org.dspace.authorize.AuthorizeConfiguration;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.authorize.service.ResourcePolicyService;
import org.dspace.content.dao.CollectionDAO;
import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.core.LogHelper;
import org.dspace.core.service.LicenseService;
import org.dspace.discovery.DiscoverQuery;
import org.dspace.discovery.DiscoverResult;
import org.dspace.discovery.IndexableObject;
import org.dspace.discovery.SearchService;
import org.dspace.discovery.SearchServiceException;
import org.dspace.discovery.indexobject.IndexableCollection;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.service.GroupService;
import org.dspace.eperson.service.SubscribeService;
import org.dspace.event.Event;
import org.dspace.harvest.HarvestedCollection;
import org.dspace.harvest.service.HarvestedCollectionService;
import org.dspace.identifier.IdentifierException;
import org.dspace.identifier.service.IdentifierService;
import org.dspace.services.ConfigurationService;
import org.dspace.workflow.factory.WorkflowServiceFactory;
import org.dspace.xmlworkflow.WorkflowConfigurationException;
import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
import org.dspace.xmlworkflow.state.Workflow;
import org.dspace.xmlworkflow.storedcomponents.CollectionRole;
import org.dspace.xmlworkflow.storedcomponents.service.CollectionRoleService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Service implementation for the Collection object.
 * This class is responsible for all business logic calls for the Collection object and is autowired by spring.
 * This class should never be accessed directly.
 *
 * @author kevinvandevelde at atmire.com
 */
public class CollectionServiceImpl extends DSpaceObjectServiceImpl<Collection> implements CollectionService {

    /**
     * log4j category
     */
    private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(CollectionServiceImpl.class);

    @Autowired(required = true)
    protected CollectionDAO collectionDAO;

    @Autowired(required = true)
    protected AuthorizeService authorizeService;
    @Autowired(required = true)
    protected ResourcePolicyService resourcePolicyService;
    @Autowired(required = true)
    protected BitstreamService bitstreamService;
    @Autowired(required = true)
    protected ItemService itemService;
    @Autowired(required = true)
    protected CommunityService communityService;
    @Autowired(required = true)
    protected GroupService groupService;
    @Autowired(required = true)
    protected IdentifierService identifierService;

    @Autowired(required = true)
    protected LicenseService licenseService;
    @Autowired(required = true)
    protected SubscribeService subscribeService;
    @Autowired(required = true)
    protected WorkspaceItemService workspaceItemService;
    @Autowired(required = true)
    protected HarvestedCollectionService harvestedCollectionService;

    @Autowired(required = true)
    protected XmlWorkflowFactory workflowFactory;

    @Autowired(required = true)
    protected CollectionRoleService collectionRoleService;

    @Autowired(required = true)
    protected SearchService searchService;

    @Autowired(required = true)
    protected ConfigurationService configurationService;

    protected CollectionServiceImpl() {
        super();
    }

    @Override
    public Collection create(Context context, Community community) throws SQLException, AuthorizeException {
        return create(context, community, null);
    }

    @Override
    public Collection create(Context context, Community community, String handle)
            throws SQLException, AuthorizeException {
        return create(context, community, handle, null);
    }

    @Override
    public Collection create(Context context, Community community,
                             String handle, UUID uuid) throws SQLException, AuthorizeException {
        if (community == null) {
            throw new IllegalArgumentException("Community cannot be null when creating a new collection.");
        }

        Collection newCollection;
        if (uuid != null) {
            newCollection = collectionDAO.create(context, new Collection(uuid));
        }  else {
            newCollection = collectionDAO.create(context, new Collection());
        }
        //Add our newly created collection to our community, authorization checks occur in THIS method
        communityService.addCollection(context, community, newCollection);

        // create the default authorization policy for collections
        // of 'anonymous' READ
        Group anonymousGroup = groupService.findByName(context, Group.ANONYMOUS);

        authorizeService.createResourcePolicy(context, newCollection, anonymousGroup, null, Constants.READ, null);
        // now create the default policies for submitted items
        authorizeService
                .createResourcePolicy(context, newCollection, anonymousGroup, null, Constants.DEFAULT_ITEM_READ, null);
        authorizeService
                .createResourcePolicy(context, newCollection, anonymousGroup, null,
                        Constants.DEFAULT_BITSTREAM_READ, null);

        collectionDAO.save(context, newCollection);

        //Update our collection so we have a collection identifier
        try {
            if (handle == null) {
                identifierService.register(context, newCollection);
            } else {
                identifierService.register(context, newCollection, handle);
            }
        } catch (IllegalStateException | IdentifierException ex) {
            throw new IllegalStateException(ex);
        }

        context.addEvent(new Event(Event.CREATE, Constants.COLLECTION,
                newCollection.getID(), newCollection.getHandle(),
                getIdentifiers(context, newCollection)));

        log.info(LogHelper.getHeader(context, "create_collection",
                "collection_id=" + newCollection.getID())
                + ",handle=" + newCollection.getHandle());

        return newCollection;
    }

    @Override
    public List<Collection> findAll(Context context) throws SQLException {
        MetadataField nameField = metadataFieldService.findByElement(context, MetadataSchemaEnum.DC.getName(),
                                                                     "title", null);
        if (nameField == null) {
            throw new IllegalArgumentException(
                "Required metadata field '" + MetadataSchemaEnum.DC.getName() + ".title' doesn't exist!");
        }

        return collectionDAO.findAll(context, nameField);
    }

    @Override
    public List<Collection> findAll(Context context, Integer limit, Integer offset) throws SQLException {
        MetadataField nameField = metadataFieldService.findByElement(context, MetadataSchemaEnum.DC.getName(),
                                                                     "title", null);
        if (nameField == null) {
            throw new IllegalArgumentException(
                "Required metadata field '" + MetadataSchemaEnum.DC.getName() + ".title' doesn't exist!");
        }

        return collectionDAO.findAll(context, nameField, limit, offset);
    }

    @Override
    public List<Collection> findAuthorizedOptimized(Context context, int actionID) throws SQLException {
        if (!configurationService
            .getBooleanProperty("org.dspace.content.Collection.findAuthorizedPerformanceOptimize", false)) {
            // Fallback to legacy query if config says so. The rationale could be that a site found a bug.
            return findAuthorized(context, null, actionID);
        }

        List<Collection> myResults = new ArrayList<>();

        if (authorizeService.isAdmin(context)) {
            return findAll(context);
        }

        //Check eperson->policy
        List<Collection> directToCollection = findDirectMapped(context, actionID);
        for (int i = 0; i < directToCollection.size(); i++) {
            if (!myResults.contains(directToCollection.get(i))) {
                myResults.add(directToCollection.get(i));
            }
        }

        //Check eperson->groups->policy
        List<Collection> groupToCollection = findGroupMapped(context, actionID);

        for (Collection aGroupToCollection : groupToCollection) {
            if (!myResults.contains(aGroupToCollection)) {
                myResults.add(aGroupToCollection);
            }
        }

        //Check eperson->groups->groups->policy->collection
        //i.e. Malcolm Litchfield is a member of OSU_Press_Embargo,
        // which is a member of: COLLECTION_24_ADMIN, COLLECTION_24_SUBMIT
        List<Collection> group2GroupToCollection = findGroup2GroupMapped(context, actionID);

        for (Collection aGroup2GroupToCollection : group2GroupToCollection) {
            if (!myResults.contains(aGroup2GroupToCollection)) {
                myResults.add(aGroup2GroupToCollection);
            }
        }

        //TODO Check eperson->groups->groups->policy->community

        //TODO Check eperson->groups->policy->community
        // i.e. Typical Community Admin -- name.# > COMMUNITY_10_ADMIN > Ohio State University Press

        //Check eperson->comm-admin
        List<Collection> group2commCollections = findGroup2CommunityMapped(context);
        for (Collection group2commCollection : group2commCollections) {
            if (!myResults.contains(group2commCollection)) {
                myResults.add(group2commCollection);
            }
        }

        // Return the collections, sorted alphabetically
        Collections.sort(myResults, new CollectionNameComparator());

        return myResults;
    }

    @Override
    public List<Collection> findDirectMapped(Context context, int actionID) throws SQLException {
        return collectionDAO
            .findAuthorized(context, context.getCurrentUser(), Arrays.asList(Constants.ADD, Constants.ADMIN));
    }

    @Override
    public List<Collection> findGroup2CommunityMapped(Context context) throws SQLException {
        List<Community> communities = communityService
            .findAuthorizedGroupMapped(context, Arrays.asList(Constants.ADD, Constants.ADMIN));
        List<Collection> collections = new ArrayList<>();
        for (Community community : communities) {
            collections.addAll(community.getCollections());
        }
        return collections;
    }

    @Override
    public List<Collection> findGroup2GroupMapped(Context context, int actionID) throws SQLException {
        return collectionDAO
            .findAuthorizedByGroup(context, context.getCurrentUser(), Collections.singletonList(actionID));
    }

    @Override
    public List<Collection> findGroupMapped(Context context, int actionID) throws SQLException {
        List<Community> communities = communityService
            .findAuthorized(context, Arrays.asList(Constants.ADD, Constants.ADMIN));
        List<Collection> collections = new ArrayList<>();
        for (Community community : communities) {
            collections.addAll(community.getCollections());
        }
        return collections;
    }

    @Override
    public Collection find(Context context, UUID id) throws SQLException {
        return collectionDAO.findByID(context, Collection.class, id);
    }

    @Override
    public void setMetadataSingleValue(Context context, Collection collection,
            MetadataFieldName field, String language, String value)
            throws MissingResourceException, SQLException {
        if (field.equals(MD_NAME) && (value == null || value.trim().equals(""))) {
            try {
                value = I18nUtil.getMessage("org.dspace.content.untitled");
            } catch (MissingResourceException e) {
                value = "Untitled";
            }
        }

        /*
         * Set metadata field to null if null
         * and trim strings to eliminate excess
         * whitespace.
         */
        if (value == null) {
            clearMetadata(context, collection, field.schema, field.element, field.qualifier, Item.ANY);
            collection.setMetadataModified();
        } else {
            super.setMetadataSingleValue(context, collection, field, null, value);
        }

        collection.addDetails(field.toString());
    }

    @Override
    public Bitstream setLogo(Context context, Collection collection, InputStream is)
        throws AuthorizeException, IOException, SQLException {
        // Check authorisation
        // authorized to remove the logo when DELETE rights
        // authorized when canEdit
        if (!((is == null) && authorizeService.authorizeActionBoolean(
            context, collection, Constants.DELETE))) {
            canEdit(context, collection, true);
        }

        // First, delete any existing logo
        if (collection.getLogo() != null) {
            bitstreamService.delete(context, collection.getLogo());
        }

        if (is == null) {
            collection.setLogo(null);
            log.info(LogHelper.getHeader(context, "remove_logo",
                                          "collection_id=" + collection.getID()));
        } else {
            Bitstream newLogo = bitstreamService.create(context, is);
            collection.setLogo(newLogo);

            // now create policy for logo bitstream
            // to match our READ policy
            List<ResourcePolicy> policies = authorizeService
                .getPoliciesActionFilter(context, collection, Constants.READ);
            authorizeService.addPolicies(context, policies, newLogo);

            log.info(LogHelper.getHeader(context, "set_logo",
                                          "collection_id=" + collection.getID() + "logo_bitstream_id="
                                              + newLogo.getID()));
        }

        collection.setModified();
        return collection.getLogo();
    }

    @Override
    public Group createWorkflowGroup(Context context, Collection collection, int step)
        throws SQLException, AuthorizeException {
        // Check authorisation - Must be an Admin to create Workflow Group
        AuthorizeUtil.authorizeManageWorkflowsGroup(context, collection);

        if (getWorkflowGroup(context, collection, step) == null) {
            //turn off authorization so that Collection Admins can create Collection Workflow Groups
            context.turnOffAuthorisationSystem();
            Group g = groupService.create(context);
            groupService.setName(g,
                                 "COLLECTION_" + collection.getID() + "_WORKFLOW_STEP_" + step);
            groupService.update(context, g);
            context.restoreAuthSystemState();
            setWorkflowGroup(context, collection, step, g);
        }

        return getWorkflowGroup(context, collection, step);
    }

    @Override
    public void setWorkflowGroup(Context context, Collection collection, int step, Group group)
        throws SQLException {
        Workflow workflow = null;
        try {
            workflow = workflowFactory.getWorkflow(collection);
        } catch (WorkflowConfigurationException e) {
            log.error(LogHelper.getHeader(context, "setWorkflowGroup",
                    "collection_id=" + collection.getID() + " " + e.getMessage()), e);
        }
        if (!StringUtils.equals(workflowFactory.getDefaultWorkflow().getID(), workflow.getID())) {
            throw new IllegalArgumentException(
                    "setWorkflowGroup can be used only on collection with the default basic dspace workflow. "
                    + "Instead, the collection: "
                            + collection.getID() + " has the workflow: " + workflow.getID());
        }
        String roleId;

        switch (step) {
            case 1:
                roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP1_NAME;
                break;
            case 2:
                roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP2_NAME;
                break;
            case 3:
                roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP3_NAME;
                break;
            default:
                throw new IllegalArgumentException("Illegal step count: " + step);
        }

        CollectionRole colRole = collectionRoleService.find(context, collection, roleId);
        if (colRole == null) {
            if (group != null) {
                colRole = collectionRoleService.create(context, collection, roleId, group);
            }
        } else {
            if (group != null) {
                colRole.setGroup(group);
                collectionRoleService.update(context, colRole);
            } else {
                collectionRoleService.delete(context, colRole);
            }
        }
        collection.setModified();
    }

    @Override
    public Group getWorkflowGroup(Context context, Collection collection, int step) {
        String roleId;

        switch (step) {
            case 1:
                roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP1_NAME;
                break;
            case 2:
                roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP2_NAME;
                break;
            case 3:
                roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP3_NAME;
                break;
            default:
                throw new IllegalArgumentException("Illegal step count: " + step);
        }

        CollectionRole colRole;
        try {
            colRole = collectionRoleService.find(context, collection, roleId);
            if (colRole != null) {
                return colRole.getGroup();
            }
            return null;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Group createSubmitters(Context context, Collection collection) throws SQLException, AuthorizeException {
        // Check authorisation - Must be an Admin to create Submitters Group
        AuthorizeUtil.authorizeManageSubmittersGroup(context, collection);

        Group submitters = collection.getSubmitters();
        if (submitters == null) {
            //turn off authorization so that Collection Admins can create Collection Submitters
            context.turnOffAuthorisationSystem();
            submitters = groupService.create(context);
            context.restoreAuthSystemState();

            groupService.setName(submitters,
                                 "COLLECTION_" + collection.getID() + "_SUBMIT");
            groupService.update(context, submitters);
        }

        // register this as the submitter group
        collection.setSubmitters(submitters);

        authorizeService.addPolicy(context, collection, Constants.ADD, submitters);

        return submitters;
    }

    @Override
    public void removeSubmitters(Context context, Collection collection) throws SQLException, AuthorizeException {
        // Check authorisation - Must be an Admin to delete Submitters Group
        AuthorizeUtil.authorizeManageSubmittersGroup(context, collection);

        // just return if there is no administrative group.
        if (collection.getSubmitters() == null) {
            return;
        }

        // Remove the link to the collection table.
        collection.setSubmitters(null);
    }

    @Override
    public Group createAdministrators(Context context, Collection collection) throws SQLException, AuthorizeException {
        // Check authorisation - Must be an Admin to create more Admins
        AuthorizeUtil.authorizeManageAdminGroup(context, collection);

        Group admins = collection.getAdministrators();
        if (admins == null) {
            //turn off authorization so that Community Admins can create Collection Admins
            context.turnOffAuthorisationSystem();
            admins = groupService.create(context);
            context.restoreAuthSystemState();

            groupService.setName(admins, "COLLECTION_" + collection.getID() + "_ADMIN");
            groupService.update(context, admins);
        }

        authorizeService.addPolicy(context, collection,
                                   Constants.ADMIN, admins);

        // register this as the admin group
        collection.setAdmins(admins);
        context.addEvent(new Event(Event.MODIFY, Constants.COLLECTION, collection.getID(),
                                              null, getIdentifiers(context, collection)));
        return admins;
    }

    @Override
    public void removeAdministrators(Context context, Collection collection) throws SQLException, AuthorizeException {
        // Check authorisation - Must be an Admin of the parent community to delete Admin Group
        AuthorizeUtil.authorizeRemoveAdminGroup(context, collection);

        Group admins = collection.getAdministrators();
        // just return if there is no administrative group.
        if (admins == null) {
            return;
        }

        // Remove the link to the collection table.
        collection.setAdmins(null);
        context.addEvent(new Event(Event.MODIFY, Constants.COLLECTION, collection.getID(),
                                              null, getIdentifiers(context, collection)));
    }

    @Override
    public String getLicense(Collection collection) {
        String license = getMetadataFirstValue(collection, CollectionService.MD_LICENSE, Item.ANY);

        if (license == null || license.trim().equals("")) {
            // Fallback to site-wide default
            license = licenseService.getDefaultSubmissionLicense();
        }

        return license;
    }

    @Override
    public boolean hasCustomLicense(Collection collection) {
        String license = collection.getLicenseCollection();
        return StringUtils.isNotBlank(license);
    }

    @Override
    public void createTemplateItem(Context context, Collection collection) throws SQLException, AuthorizeException {
        // Check authorisation
        AuthorizeUtil.authorizeManageTemplateItem(context, collection);

        if (collection.getTemplateItem() == null) {
            Item template = itemService.createTemplateItem(context, collection);
            collection.setTemplateItem(template);

            log.info(LogHelper.getHeader(context, "create_template_item",
                                          "collection_id=" + collection.getID() + ",template_item_id="
                                              + template.getID()));
        }
    }

    @Override
    public void removeTemplateItem(Context context, Collection collection)
        throws SQLException, AuthorizeException, IOException {
        // Check authorisation
        AuthorizeUtil.authorizeManageTemplateItem(context, collection);

        Item template = collection.getTemplateItem();

        if (template != null) {
            log.info(LogHelper.getHeader(context, "remove_template_item",
                                          "collection_id=" + collection.getID() + ",template_item_id="
                                              + template.getID()));
            // temporarily turn off auth system, we have already checked the permission on the top of the method
            // check it again will fail because we have already broken the relation between the collection and the item
            context.turnOffAuthorisationSystem();
            collection.setTemplateItem(null);
            itemService.delete(context, template);
            context.restoreAuthSystemState();
        }

        context.addEvent(new Event(Event.MODIFY, Constants.COLLECTION,
                                   collection.getID(), "remove_template_item", getIdentifiers(context, collection)));
    }

    @Override
    public void addItem(Context context, Collection collection, Item item) throws SQLException, AuthorizeException {
        // Check authorisation
        authorizeService.authorizeAction(context, collection, Constants.ADD);

        log.info(LogHelper.getHeader(context, "add_item", "collection_id="
            + collection.getID() + ",item_id=" + item.getID()));

        // Create mapping
        // We do NOT add the item to the collection template since we would have to load in all our items
        // Instead we add the collection to an item which works in the same way.
        if (!item.getCollections().contains(collection)) {
            item.addCollection(collection);
        }

        context.addEvent(new Event(Event.ADD, Constants.COLLECTION, collection.getID(),
                                   Constants.ITEM, item.getID(), item.getHandle(),
                                   getIdentifiers(context, collection)));
    }

    @Override
    public void removeItem(Context context, Collection collection, Item item)
        throws SQLException, AuthorizeException, IOException {
        // Check authorisation
        authorizeService.authorizeAction(context, collection, Constants.REMOVE);

        //Check if we orphaned our poor item
        if (item.getCollections().size() == 1) {
            // Orphan; delete it
            itemService.delete(context, item);
        } else {
            //Remove the item from the collection if we have multiple collections
            item.removeCollection(collection);

        }

        context.addEvent(new Event(Event.REMOVE, Constants.COLLECTION,
                                   collection.getID(), Constants.ITEM, item.getID(), item.getHandle(),
                                   getIdentifiers(context, collection)));
    }

    @Override
    public void update(Context context, Collection collection) throws SQLException, AuthorizeException {
        // Check authorisation
        canEdit(context, collection, true);

        log.info(LogHelper.getHeader(context, "update_collection",
                                      "collection_id=" + collection.getID()));

        super.update(context, collection);
        collectionDAO.save(context, collection);

        if (collection.isModified()) {
            context.addEvent(new Event(Event.MODIFY, Constants.COLLECTION,
                                       collection.getID(), null, getIdentifiers(context, collection)));
            collection.clearModified();
        }
        if (collection.isMetadataModified()) {
            context.addEvent(new Event(Event.MODIFY_METADATA, Constants.COLLECTION, collection.getID(),
                                         collection.getDetails(),getIdentifiers(context, collection)));
            collection.clearModified();
        }
        collection.clearDetails();
    }

    @Override
    public boolean canEditBoolean(Context context, Collection collection) throws SQLException {
        return canEditBoolean(context, collection, true);
    }

    @Override
    public boolean canEditBoolean(Context context, Collection collection, boolean useInheritance) throws SQLException {
        try {
            canEdit(context, collection, useInheritance);

            return true;
        } catch (AuthorizeException e) {
            return false;
        }
    }

    @Override
    public void canEdit(Context context, Collection collection) throws SQLException, AuthorizeException {
        canEdit(context, collection, true);
    }

    @Override
    public void canEdit(Context context, Collection collection, boolean useInheritance)
        throws SQLException, AuthorizeException {
        List<Community> parents = communityService.getAllParents(context, collection);
        for (Community parent : parents) {
            if (authorizeService.authorizeActionBoolean(context, parent,
                                                        Constants.WRITE, useInheritance)) {
                return;
            }

            if (authorizeService.authorizeActionBoolean(context, parent,
                                                        Constants.ADD, useInheritance)) {
                return;
            }
        }
        authorizeService.authorizeAction(context, collection, Constants.WRITE, useInheritance);
    }

    @Override
    public void delete(Context context, Collection collection) throws SQLException, AuthorizeException, IOException {
        log.info(LogHelper.getHeader(context, "delete_collection",
                                      "collection_id=" + collection.getID()));

        // remove harvested collections.
        HarvestedCollection hc = harvestedCollectionService.find(context, collection);
        if (hc != null) {
            harvestedCollectionService.delete(context, hc);
        }

        context.addEvent(new Event(Event.DELETE, Constants.COLLECTION,
                                   collection.getID(), collection.getHandle(), getIdentifiers(context, collection)));

        // remove subscriptions - hmm, should this be in Subscription.java?
        subscribeService.deleteByCollection(context, collection);

        // Remove Template Item
        removeTemplateItem(context, collection);

        // Remove items
        // Remove items
        Iterator<Item> items = itemService.findAllByCollection(context, collection);
        while (items.hasNext()) {
            Item item = items.next();
//            items.remove();
            if (itemService.isOwningCollection(item, collection)) {
                // the collection to be deleted is the owning collection, thus remove
                // the item from all collections it belongs to
                itemService.delete(context, item);
            } else {
                // the item was only mapped to this collection, so just remove it
                removeItem(context, collection, item);
            }
        }

        // Delete bitstream logo
        setLogo(context, collection, null);

        Iterator<WorkspaceItem> workspaceItems = workspaceItemService.findByCollection(context, collection).iterator();
        while (workspaceItems.hasNext()) {
            WorkspaceItem workspaceItem = workspaceItems.next();
            workspaceItems.remove();
            workspaceItemService.deleteAll(context, workspaceItem);
        }

        WorkflowServiceFactory.getInstance().getWorkflowService().deleteCollection(context, collection);
        WorkflowServiceFactory.getInstance().getWorkflowItemService().deleteByCollection(context, collection);

        //  get rid of the content count cache if it exists
        // Remove any Handle
        handleService.unbindHandle(context, collection);

        // Remove any workflow roles
        collectionRoleService.deleteByCollection(context, collection);

        collection.getResourcePolicies().clear();

        // Remove default administrators group
        Group g = collection.getAdministrators();

        if (g != null) {
            collection.setAdmins(null);
            groupService.delete(context, g);
        }

        // Remove default submitters group
        g = collection.getSubmitters();

        if (g != null) {
            collection.setSubmitters(null);
            groupService.delete(context, g);
        }

        Iterator<Community> owningCommunities = collection.getCommunities().iterator();
        while (owningCommunities.hasNext()) {
            Community owningCommunity = owningCommunities.next();
            collection.removeCommunity(owningCommunity);
            owningCommunity.removeCollection(collection);
        }

        collectionDAO.delete(context, collection);
    }

    @Override
    public int getSupportsTypeConstant() {
        return Constants.COLLECTION;
    }

    @Override
    public List<Collection> findAuthorized(Context context, Community community, int actionID) throws SQLException {
        List<Collection> myResults = new ArrayList<>();

        List<Collection> myCollections;

        if (community != null) {
            myCollections = community.getCollections();
        } else {
            myCollections = findAll(context);
        }

        // now build a list of collections you have authorization for
        for (Collection myCollection : myCollections) {
            if (authorizeService.authorizeActionBoolean(context,
                                                        myCollection, actionID)) {
                myResults.add(myCollection);
            }
        }
        return myResults;
    }

    @Override
    public Collection findByGroup(Context context, Group group) throws SQLException {
        return collectionDAO.findByGroup(context, group);
    }

    @Override
    public List<Collection> findCollectionsWithSubscribers(Context context) throws SQLException {
        return collectionDAO.findCollectionsWithSubscribers(context);
    }

    @Override
    public DSpaceObject getAdminObject(Context context, Collection collection, int action) throws SQLException {
        DSpaceObject adminObject = null;
        Community community = null;
        List<Community> communities = collection.getCommunities();
        if (CollectionUtils.isNotEmpty(communities)) {
            community = communities.get(0);
        }

        switch (action) {
            case Constants.REMOVE:
                if (AuthorizeConfiguration.canCollectionAdminPerformItemDeletion()) {
                    adminObject = collection;
                } else if (AuthorizeConfiguration.canCommunityAdminPerformItemDeletion()) {
                    adminObject = community;
                }
                break;

            case Constants.DELETE:
                if (AuthorizeConfiguration.canCommunityAdminPerformSubelementDeletion()) {
                    adminObject = community;
                }
                break;
            default:
                adminObject = collection;
                break;
        }
        return adminObject;
    }

    @Override
    public DSpaceObject getParentObject(Context context, Collection collection) throws SQLException {
        List<Community> communities = collection.getCommunities();
        if (CollectionUtils.isNotEmpty(communities)) {
            return communities.get(0);
        } else {
            return null;
        }
    }

    @Override
    public void updateLastModified(Context context, Collection collection) throws SQLException, AuthorizeException {
        //Also fire a modified event since the collection HAS been modified
        context.addEvent(new Event(Event.MODIFY, Constants.COLLECTION,
                                   collection.getID(), null, getIdentifiers(context, collection)));
    }

    @Override
    public Collection findByIdOrLegacyId(Context context, String id) throws SQLException {
        if (StringUtils.isNumeric(id)) {
            return findByLegacyId(context, Integer.parseInt(id));
        } else {
            return find(context, UUID.fromString(id));
        }
    }

    @Override
    public Collection findByLegacyId(Context context, int id) throws SQLException {
        return collectionDAO.findByLegacyId(context, id, Collection.class);
    }

    @Override
    public int countTotal(Context context) throws SQLException {
        return collectionDAO.countRows(context);
    }

    @Override
    public List<Map.Entry<Collection, Long>> getCollectionsWithBitstreamSizesTotal(Context context)
        throws SQLException {
        return collectionDAO.getCollectionsWithBitstreamSizesTotal(context);
    }

    @Override
    public Group createDefaultReadGroup(Context context, Collection collection, String typeOfGroupString,
                                        int defaultRead)
        throws SQLException, AuthorizeException {
        Group role = groupService.create(context);
        groupService.setName(role, "COLLECTION_" + collection.getID().toString() + "_" + typeOfGroupString +
            "_DEFAULT_READ");

        // Remove existing privileges from the anonymous group.
        authorizeService.removePoliciesActionFilter(context, collection, defaultRead);

        // Grant our new role the default privileges.
        authorizeService.addPolicy(context, collection, defaultRead, role);
        groupService.update(context, role);
        return role;
    }

    @Override
    public List<Collection> findCollectionsWithSubmit(String q, Context context, Community community,
        int offset, int limit) throws SQLException, SearchServiceException {

        List<Collection> collections = new ArrayList<>();
        DiscoverQuery discoverQuery = new DiscoverQuery();
        discoverQuery.setDSpaceObjectFilter(IndexableCollection.TYPE);
        discoverQuery.setStart(offset);
        discoverQuery.setMaxResults(limit);
        DiscoverResult resp = retrieveCollectionsWithSubmit(context, discoverQuery, null, community, q);
        for (IndexableObject solrCollections : resp.getIndexableObjects()) {
            Collection c = ((IndexableCollection) solrCollections).getIndexedObject();
            collections.add(c);
        }
        return collections;
    }

    @Override
    public int countCollectionsWithSubmit(String q, Context context, Community community)
        throws SQLException, SearchServiceException {

        DiscoverQuery discoverQuery = new DiscoverQuery();
        discoverQuery.setMaxResults(0);
        discoverQuery.setDSpaceObjectFilter(IndexableCollection.TYPE);
        DiscoverResult resp = retrieveCollectionsWithSubmit(context, discoverQuery, null, community, q);
        return (int)resp.getTotalSearchResults();
    }

    /**
     * Finds all Indexed Collections where the current user has submit rights. If the user is an Admin,
     * this is all Indexed Collections. Otherwise, it includes those collections where
     * an indexed "submit" policy lists either the eperson or one of the eperson's groups
     *
     * @param context                    DSpace context
     * @param discoverQuery
     * @param entityType                 limit the returned collection to those related to given entity type
     * @param community                  parent community, could be null
     * @param q                          limit the returned collection to those with metadata values matching the query
     *                                   terms. The terms are used to make also a prefix query on SOLR
     *                                   so it can be used to implement an autosuggest feature over the collection name
     * @return                           discovery search result objects
     * @throws SQLException              if something goes wrong
     * @throws SearchServiceException    if search error
     */
    private DiscoverResult retrieveCollectionsWithSubmit(Context context, DiscoverQuery discoverQuery,
        String entityType, Community community, String q)
        throws SQLException, SearchServiceException {

        StringBuilder query = new StringBuilder();
        EPerson currentUser = context.getCurrentUser();
        if (!authorizeService.isAdmin(context)) {
            String userId = "";
            if (currentUser != null) {
                userId = currentUser.getID().toString();
            }
            query.append("submit:(e").append(userId);

            Set<Group> groups = groupService.allMemberGroupsSet(context, currentUser);
            for (Group group : groups) {
                query.append(" OR g").append(group.getID());
            }
            query.append(")");
            discoverQuery.addFilterQueries(query.toString());
        }
        if (Objects.nonNull(community)) {
            discoverQuery.addFilterQueries("location.comm:" + community.getID().toString());
        }
        if (StringUtils.isNotBlank(entityType)) {
            discoverQuery.addFilterQueries("search.entitytype:" + entityType);
        }
        if (StringUtils.isNotBlank(q)) {
            StringBuilder buildQuery = new StringBuilder();
            String escapedQuery = ClientUtils.escapeQueryChars(q);
            buildQuery.append(escapedQuery).append(" OR ").append(escapedQuery).append("*");
            discoverQuery.setQuery(buildQuery.toString());
        }
        DiscoverResult resp = searchService.search(context, discoverQuery);
        return resp;
    }

    @Override
    public List<Collection> findCollectionsWithSubmit(String q, Context context, Community community, String entityType,
            int offset, int limit) throws SQLException, SearchServiceException {
        List<Collection> collections = new ArrayList<>();
        DiscoverQuery discoverQuery = new DiscoverQuery();
        discoverQuery.setDSpaceObjectFilter(IndexableCollection.TYPE);
        discoverQuery.setStart(offset);
        discoverQuery.setMaxResults(limit);
        DiscoverResult resp = retrieveCollectionsWithSubmit(context, discoverQuery,
                entityType, community, q);
        for (IndexableObject solrCollections : resp.getIndexableObjects()) {
            Collection c = ((IndexableCollection) solrCollections).getIndexedObject();
            collections.add(c);
        }
        return collections;
    }

    @Override
    public int countCollectionsWithSubmit(String q, Context context, Community community, String entityType)
            throws SQLException, SearchServiceException {
        DiscoverQuery discoverQuery = new DiscoverQuery();
        discoverQuery.setMaxResults(0);
        discoverQuery.setDSpaceObjectFilter(IndexableCollection.TYPE);
        DiscoverResult resp = retrieveCollectionsWithSubmit(context, discoverQuery, entityType, community, q);
        return (int) resp.getTotalSearchResults();
    }

}

## 内容2
### 文件路径：
dspace-api/src/main/java/org/dspace/content/service/CollectionService.java
### 代码内容：
/**
 * The contents of this file are subject to the license and copyright
 * detailed in the LICENSE and NOTICE files at the root of the source
 * tree and available online at
 *
 * http://www.dspace.org/license/
 */
package org.dspace.content.service;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.discovery.SearchServiceException;
import org.dspace.eperson.Group;

/**
 * Service interface class for the Collection object.
 * The implementation of this class is responsible for all business logic calls
 * for the Collection object and is autowired by Spring.
 *
 * @author kevinvandevelde at atmire.com
 */
public interface CollectionService
        extends DSpaceObjectService<Collection>, DSpaceObjectLegacySupportService<Collection> {

    /**
     * Create a new collection with a new ID.
     * Once created the collection is added to the given community
     *
     * @param context   DSpace context object
     * @param community DSpace Community (parent)
     * @return the newly created collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public Collection create(Context context, Community community) throws SQLException,
        AuthorizeException;

    /**
     * Create a new collection with the supplied handle and with a new ID.
     * Once created the collection is added to the given community
     *
     * @param context   DSpace context object
     * @param community DSpace Community (parent)
     * @param handle    the pre-determined Handle to assign to the new community
     * @return the newly created collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public Collection create(Context context, Community community, String handle) throws SQLException,
        AuthorizeException;

    /**
     * Create a new collection with the supplied handle and ID.
     * Once created the collection is added to the given community
     *
     * @param context DSpace context object
     * @param community DSpace Community (parent)
     * @param handle the pre-determined Handle to assign to the new collection
     * @param uuid the pre-determined UUID to assign to the new collection
     * @return the newly created collection
     * @throws SQLException if database error
     * @throws AuthorizeException if authorization error
     */
    public Collection create(Context context, Community community, String handle, UUID uuid) throws SQLException,
            AuthorizeException;

    /**
     * Get all collections in the system. These are alphabetically sorted by
     * collection name.
     *
     * @param context DSpace context object
     * @return the collections in the system
     * @throws SQLException if database error
     */
    public List<Collection> findAll(Context context) throws SQLException;

    /**
     * Get all collections in the system. Adds support for limit and offset.
     *
     * @param context The relevant DSpace Context.
     * @param limit   paging limit
     * @param offset  paging offset
     * @return List of Collections
     * @throws SQLException if database error
     */
    public List<Collection> findAll(Context context, Integer limit, Integer offset) throws SQLException;

    public List<Collection> findAuthorizedOptimized(Context context, int actionID) throws java.sql.SQLException;

    public List<Collection> findDirectMapped(Context context, int actionID) throws java.sql.SQLException;

    public List<Collection> findGroup2CommunityMapped(Context context) throws SQLException;

    public List<Collection> findGroup2GroupMapped(Context context, int actionID) throws SQLException;

    public List<Collection> findGroupMapped(Context context, int actionID) throws java.sql.SQLException;

    /**
     * Give the collection a logo. Passing in <code>null</code> removes any
     * existing logo. You will need to set the format of the new logo bitstream
     * before it will work, for example to "JPEG". Note that
     * <code>update</code> will need to be called for the change to take
     * effect.  Setting a logo and not calling <code>update</code> later may
     * result in a previous logo lying around as an "orphaned" bitstream.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @param is         the stream to use as the new logo
     * @return the new logo bitstream, or <code>null</code> if there is no
     * logo (<code>null</code> was passed in)
     * @throws AuthorizeException if authorization error
     * @throws IOException        if IO error
     * @throws SQLException       if database error
     */
    public Bitstream setLogo(Context context, Collection collection, InputStream is) throws AuthorizeException,
        IOException, SQLException;

    /**
     * Create a workflow group for the given step if one does not already exist.
     * Returns either the newly created group or the previously existing one.
     * Note that while the new group is created in the database, the association
     * between the group and the collection is not written until
     * <code>update</code> is called.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @param step       the step (1-3) of the workflow to create or get the group for
     * @return the workflow group associated with this collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public Group createWorkflowGroup(Context context, Collection collection, int step) throws SQLException,
        AuthorizeException;

    /**
     * Set the workflow group corresponding to a particular workflow step.
     * <code>null</code> can be passed in if there should be no associated
     * group for that workflow step; any existing group is NOT deleted.
     *
     * @param context    current DSpace session.
     * @param collection Collection
     * @param step       the workflow step (1-3)
     * @param group      the new workflow group, or <code>null</code>
     * @throws SQLException passed through.
     * @throws AuthorizeException passed through.
     */
    public void setWorkflowGroup(Context context, Collection collection, int step, Group group)
        throws SQLException, AuthorizeException;

    /**
     * Get the the workflow group corresponding to a particular workflow step.
     * This returns <code>null</code> if there is no group associated with
     * this collection for the given step.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @param step       the workflow step (1-3)
     * @return the group of reviewers or <code>null</code>
     */
    public Group getWorkflowGroup(Context context, Collection collection, int step);

    /**
     * Create a default submitters group if one does not already exist. Returns
     * either the newly created group or the previously existing one. Note that
     * other groups may also be allowed to submit to this collection by the
     * authorization system.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @return the default group of submitters associated with this collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public Group createSubmitters(Context context, Collection collection) throws SQLException, AuthorizeException;

    /**
     * Remove the submitters group, if no group has already been created
     * then return without error. This will merely dereference the current
     * submitters group from the collection so that it may be deleted
     * without violating database constraints.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public void removeSubmitters(Context context, Collection collection) throws SQLException, AuthorizeException;

    /**
     * Create a default administrators group if one does not already exist.
     * Returns either the newly created group or the previously existing one.
     * Note that other groups may also be administrators.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @return the default group of editors associated with this collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public Group createAdministrators(Context context, Collection collection) throws SQLException, AuthorizeException;

    /**
     * Remove the administrators group, if no group has already been created
     * then return without error. This will merely dereference the current
     * administrators group from the collection so that it may be deleted
     * without violating database constraints.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public void removeAdministrators(Context context, Collection collection) throws SQLException, AuthorizeException;

    /**
     * Get the license that users must grant before submitting to this
     * collection. If the collection does not have a specific license, the
     * site-wide default is returned.
     *
     * @param collection Collection
     * @return the license for this collection
     */
    public String getLicense(Collection collection);

    /**
     * Find out if the collection has a custom license
     *
     * @param collection Collection
     * @return <code>true</code> if the collection has a custom license
     */
    public boolean hasCustomLicense(Collection collection);

    /**
     * Create an empty template item for this collection. If one already exists,
     * no action is taken. Caution: Make sure you call <code>update</code> on
     * the collection after doing this, or the item will have been created but
     * the collection record will not refer to it.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public void createTemplateItem(Context context, Collection collection) throws SQLException, AuthorizeException;

    /**
     * Remove the template item for this collection, if there is one. Note that
     * since this has to remove the old template item ID from the collection
     * record in the database, the collection record will be changed, including
     * any other changes made; in other words, this method does an
     * <code>update</code>.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     * @throws IOException        if IO error
     */
    public void removeTemplateItem(Context context, Collection collection)
        throws SQLException, AuthorizeException, IOException;

    /**
     * Add an item to the collection. This simply adds a relationship between
     * the item and the collection - it does nothing like set an issue date,
     * remove a personal workspace item etc. This has instant effect;
     * <code>update</code> need not be called.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @param item       item to add
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     */
    public void addItem(Context context, Collection collection, Item item) throws SQLException, AuthorizeException;

    /**
     * Remove an item. If the item is then orphaned, it is deleted.
     *
     * @param context    DSpace Context
     * @param collection Collection
     * @param item       item to remove
     * @throws SQLException       if database error
     * @throws AuthorizeException if authorization error
     * @throws IOException        if IO error
     */
    public void removeItem(Context context, Collection collection, Item item) throws SQLException, AuthorizeException,
        IOException;

    public boolean canEditBoolean(Context context, Collection collection) throws SQLException;

    public boolean canEditBoolean(Context context, Collection collection, boolean useInheritance)
        throws java.sql.SQLException;

    public void canEdit(Context context, Collection collection) throws SQLException, AuthorizeException;

    public void canEdit(Context context, Collection collection, boolean useInheritance)
        throws SQLException, AuthorizeException;

    /**
     * return an array of collections that user has a given permission on
     * (useful for trimming 'select to collection' list) or figuring out which
     * collections a person is an editor for.
     *
     * @param context   DSpace Context
     * @param community (optional) restrict search to a community, else null
     * @param actionID  of the action
     * @return Collection [] of collections with matching permissions
     * @throws SQLException if database error
     */
    public List<Collection> findAuthorized(Context context, Community community, int actionID)
        throws java.sql.SQLException;

    /**
     *
     * @param context DSpace Context
     * @param group EPerson Group
     * @return the collection, if any, that has the specified group as administrators or submitters
     * @throws SQLException
     */
    public Collection findByGroup(Context context, Group group) throws SQLException;

    List<Collection> findCollectionsWithSubscribers(Context context) throws SQLException;

    int countTotal(Context context) throws SQLException;

    /**
     * The map entry returned contains a collection as a key and sum of bitstream sizes in bytes as a value
     *
     * @param context DSpace Context
     * @return List of Collections and bitstream sizes map
     * @throws SQLException if database error
     */
    List<Map.Entry<Collection, Long>> getCollectionsWithBitstreamSizesTotal(Context context) throws SQLException;

    /**
     * This method will create a default read group for the given Collection. It'll create either a defaultItemRead or
     * a defaultBitstreamRead group depending on the given parameters
     *
     * @param context           The relevant DSpace context
     * @param collection        The collection for which it'll be created
     * @param typeOfGroupString The type of group to be made, item or bitstream
     * @param defaultRead       The defaultRead int, item or bitstream
     * @return                  The created Group
     * @throws SQLException     If something goes wrong
     * @throws AuthorizeException   If something goes wrong
     */
    Group createDefaultReadGroup(Context context, Collection collection, String typeOfGroupString, int defaultRead)
        throws SQLException, AuthorizeException;

    /**
     * Returns Collections for which the current user has 'submit' privileges.
     * NOTE: for better performance, this method retrieves its results from an
     *       index (cache) and does not query the database directly.
     *       This means that results may be stale or outdated until https://github.com/DSpace/DSpace/issues/2853 is resolved"
     *
     * @param q                limit the returned collection to those with metadata values matching the query terms.
     *                         The terms are used to make also a prefix query on SOLR so it can be used to implement
     *                         an autosuggest feature over the collection name
     * @param context          DSpace Context
     * @param community        parent community
     * @param entityType       limit the returned collection to those related to given entity type
     * @param offset           the position of the first result to return
     * @param limit            paging limit
     * @return                 discovery search result objects
     * @throws SQLException              if something goes wrong
     * @throws SearchServiceException    if search error
     */
    public List<Collection> findCollectionsWithSubmit(String q, Context context, Community community,
            String entityType, int offset, int limit) throws SQLException, SearchServiceException;

    /**
     * Returns Collections for which the current user has 'submit' privileges.
     * NOTE: for better performance, this method retrieves its results from an
     *       index (cache) and does not query the database directly.
     *       This means that results may be stale or outdated until
     *       https://github.com/DSpace/DSpace/issues/2853 is resolved"
     *
     * @param q                limit the returned collection to those with metadata values matching the query terms.
     *                         The terms are used to make also a prefix query on SOLR so it can be used to implement
     *                         an autosuggest feature over the collection name
     * @param context          DSpace Context
     * @param community        parent community
     * @param offset           the position of the first result to return
     * @param limit            paging limit
     * @return                 discovery search result objects
     * @throws SQLException              if something goes wrong
     * @throws SearchServiceException    if search error
     */
    public List<Collection> findCollectionsWithSubmit(String q, Context context, Community community,
        int offset, int limit) throws SQLException, SearchServiceException;

    /**
     * Counts the number of Collection for which the current user has 'submit' privileges.
     * NOTE: for better performance, this method retrieves its results from an index (cache)
     *       and does not query the database directly.
     *       This means that results may be stale or outdated until
     *       https://github.com/DSpace/DSpace/issues/2853 is resolved."
     *
     * @param q                limit the returned collection to those with metadata values matching the query terms.
     *                         The terms are used to make also a prefix query on SOLR so it can be used to implement
     *                         an autosuggest feature over the collection name
     * @param context          DSpace Context
     * @param community        parent community
     * @return                 total collections found
     * @throws SQLException              if something goes wrong
     * @throws SearchServiceException    if search error
     */
    public int countCollectionsWithSubmit(String q, Context context, Community community)
        throws SQLException, SearchServiceException;

    /**
     * Counts the number of Collection for which the current user has 'submit' privileges.
     * NOTE: for better performance, this method retrieves its results from an index (cache)
     *       and does not query the database directly.
     *       This means that results may be stale or outdated until
     *       https://github.com/DSpace/DSpace/issues/2853 is resolved."
     *
     * @param q                limit the returned collection to those with metadata values matching the query terms.
     *                         The terms are used to make also a prefix query on SOLR so it can be used to implement
     *                         an autosuggest feature over the collection name
     * @param context          DSpace Context
     * @param community        parent community
     * @param entityType       limit the returned collection to those related to given entity type
     * @return                 total collections found
     * @throws SQLException              if something goes wrong
     * @throws SearchServiceException    if search error
     */
    public int countCollectionsWithSubmit(String q, Context context, Community community, String entityType)
        throws SQLException, SearchServiceException;

}

## 内容3
### 文件路径：
dspace-api/src/main/java/org/dspace/eperson/GroupServiceImpl.java
### 代码内容：
/**
 * The contents of this file are subject to the license and copyright
 * detailed in the LICENSE and NOTICE files at the root of the source
 * tree and available online at
 *
 * http://www.dspace.org/license/
 */
package org.dspace.eperson;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.dspace.authorize.AuthorizeConfiguration;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.authorize.service.ResourcePolicyService;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.DSpaceObjectServiceImpl;
import org.dspace.content.MetadataField;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogHelper;
import org.dspace.eperson.dao.Group2GroupCacheDAO;
import org.dspace.eperson.dao.GroupDAO;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService;
import org.dspace.eperson.service.GroupService;
import org.dspace.event.Event;
import org.dspace.util.UUIDUtils;
import org.dspace.xmlworkflow.Role;
import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.storedcomponents.ClaimedTask;
import org.dspace.xmlworkflow.storedcomponents.CollectionRole;
import org.dspace.xmlworkflow.storedcomponents.PoolTask;
import org.dspace.xmlworkflow.storedcomponents.service.ClaimedTaskService;
import org.dspace.xmlworkflow.storedcomponents.service.CollectionRoleService;
import org.dspace.xmlworkflow.storedcomponents.service.PoolTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Service implementation for the Group object.
 * This class is responsible for all business logic calls for the Group object and is autowired by spring.
 * This class should never be accessed directly.
 *
 * @author kevinvandevelde at atmire.com
 */
public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements GroupService {
    private static final Logger log = LoggerFactory.getLogger(GroupServiceImpl.class);

    @Autowired(required = true)
    protected GroupDAO groupDAO;

    @Autowired(required = true)
    protected Group2GroupCacheDAO group2GroupCacheDAO;

    @Autowired(required = true)
    protected CollectionService collectionService;

    @Autowired(required = true)
    protected CollectionRoleService collectionRoleService;

    @Autowired(required = true)
    protected EPersonService ePersonService;

    @Autowired(required = true)
    protected CommunityService communityService;

    @Autowired(required = true)
    protected AuthorizeService authorizeService;
    @Autowired(required = true)
    protected ResourcePolicyService resourcePolicyService;

    @Autowired(required = true)
    protected PoolTaskService poolTaskService;
    @Autowired(required = true)
    protected ClaimedTaskService claimedTaskService;
    @Autowired(required = true)
    protected XmlWorkflowFactory workflowFactory;

    protected GroupServiceImpl() {
        super();
    }

    @Override
    public Group create(Context context) throws SQLException, AuthorizeException {
        // FIXME - authorization?
        if (!authorizeService.isAdmin(context)) {
            throw new AuthorizeException(
                "You must be an admin to create an EPerson Group");
        }

        // Create a table row
        Group g = groupDAO.create(context, new Group());

        log.info(LogHelper.getHeader(context, "create_group", "group_id="
            + g.getID()));

        context.addEvent(new Event(Event.CREATE, Constants.GROUP, g.getID(), null, getIdentifiers(context, g)));
        update(context, g);

        return g;
    }

    @Override
    public void setName(Group group, String name) throws SQLException {
        if (group.isPermanent()) {
            log.error("Attempt to rename permanent Group {} to {}.",
                      group.getName(), name);
            throw new SQLException("Attempt to rename a permanent Group");
        } else {
            group.setName(name);
        }
    }

    @Override
    public void addMember(Context context, Group group, EPerson e) {
        if (isDirectMember(group, e)) {
            return;
        }
        group.addMember(e);
        e.getGroups().add(group);
        context.addEvent(
            new Event(Event.ADD, Constants.GROUP, group.getID(), Constants.EPERSON, e.getID(), e.getEmail(),
                      getIdentifiers(context, group)));
    }

    @Override
    public void addMember(Context context, Group groupParent, Group groupChild) throws SQLException {
        // don't add if it's already a member
        // and don't add itself
        if (groupParent.contains(groupChild) || groupParent.getID() == groupChild.getID()) {
            return;
        }

        groupParent.addMember(groupChild);
        groupChild.addParentGroup(groupParent);

        context.addEvent(new Event(Event.ADD, Constants.GROUP, groupParent.getID(), Constants.GROUP, groupChild.getID(),
                                   groupChild.getName(), getIdentifiers(context, groupParent)));
    }

    /**
     * Removes a member of a group.
     * The removal will be refused if the group is linked to a workflow step which has claimed tasks or pool tasks
     * and no other member is present in the group to handle these.
     * @param context DSpace context object
     * @param group   DSpace group
     * @param ePerson eperson
     * @throws SQLException
     */
    @Override
    public void removeMember(Context context, Group group, EPerson ePerson) throws SQLException {
        List<CollectionRole> collectionRoles = collectionRoleService.findByGroup(context, group);
        if (!collectionRoles.isEmpty()) {
            List<PoolTask> poolTasks = poolTaskService.findByGroup(context, group);
            List<ClaimedTask> claimedTasks = claimedTaskService.findByEperson(context, ePerson);
            for (ClaimedTask claimedTask : claimedTasks) {
                Step stepByName = workflowFactory.getStepByName(claimedTask.getStepID());
                Role role = stepByName.getRole();
                for (CollectionRole collectionRole : collectionRoles) {
                    if (StringUtils.equals(collectionRole.getRoleId(), role.getId())
                            && claimedTask.getWorkflowItem().getCollection() == collectionRole.getCollection()) {
                        List<EPerson> ePeople = allMembers(context, group);
                        if (ePeople.size() == 1 && ePeople.contains(ePerson)) {
                            throw new IllegalStateException(
                                    "Refused to remove user " + ePerson
                                            .getID() + " from workflow group because the group " + group
                                            .getID() + " has tasks assigned and no other members");
                        }

                    }
                }
            }
            if (!poolTasks.isEmpty()) {
                List<EPerson> ePeople = allMembers(context, group);
                if (ePeople.size() == 1 && ePeople.contains(ePerson)) {
                    throw new IllegalStateException(
                            "Refused to remove user " + ePerson
                                    .getID() + " from workflow group because the group " + group
                                    .getID() + " has tasks assigned and no other members");
                }
            }
        }
        if (group.remove(ePerson)) {
            context.addEvent(new Event(Event.REMOVE, Constants.GROUP, group.getID(), Constants.EPERSON, ePerson.getID(),
                                       ePerson.getEmail(), getIdentifiers(context, group)));
        }
    }

    @Override
    public void removeMember(Context context, Group groupParent, Group childGroup) throws SQLException {
        List<CollectionRole> collectionRoles = collectionRoleService.findByGroup(context, groupParent);
        if (!collectionRoles.isEmpty()) {
            List<PoolTask> poolTasks = poolTaskService.findByGroup(context, groupParent);
            if (!poolTasks.isEmpty()) {
                List<EPerson> parentPeople = allMembers(context, groupParent);
                List<EPerson> childPeople = allMembers(context, childGroup);
                if (childPeople.containsAll(parentPeople)) {
                    throw new IllegalStateException(
                            "Refused to remove sub group " + childGroup
                                    .getID() + " from workflow group because the group " + groupParent
                                    .getID() + " has tasks assigned and no other members");
                }
            }
        }
        if (groupParent.remove(childGroup)) {
            childGroup.removeParentGroup(groupParent);
            context.addEvent(
                new Event(Event.REMOVE, Constants.GROUP, groupParent.getID(), Constants.GROUP, childGroup.getID(),
                          childGroup.getName(), getIdentifiers(context, groupParent)));
        }
    }

    @Override
    public boolean isDirectMember(Group group, EPerson ePerson) {
        // special, group 0 is anonymous
        return StringUtils.equals(group.getName(), Group.ANONYMOUS) || group.contains(ePerson);
    }

    @Override
    public boolean isMember(Group owningGroup, Group childGroup) {
        return owningGroup.contains(childGroup);
    }

    @Override
    public boolean isParentOf(Context context, Group parentGroup, Group childGroup) throws SQLException {
        return group2GroupCacheDAO.findByParentAndChild(context, parentGroup, childGroup) != null;
    }

    @Override
    public boolean isMember(Context context, Group group) throws SQLException {
        return isMember(context, context.getCurrentUser(), group);
    }

    @Override
    public boolean isMember(Context context, EPerson ePerson, Group group)
        throws SQLException {
        if (group == null) {
            return false;

            // special, everyone is member of group 0 (anonymous)
        } else if (StringUtils.equals(group.getName(), Group.ANONYMOUS) ||
                   isParentOf(context, group, findByName(context, Group.ANONYMOUS))) {
            return true;

        } else {
            Boolean cachedGroupMembership = context.getCachedGroupMembership(group, ePerson);

            if (cachedGroupMembership != null) {
                return cachedGroupMembership;

            } else {
                boolean isMember = false;

                //If we have an ePerson, check we can find membership in the database
                if (ePerson != null) {
                    //lookup eperson in normal groups and subgroups with 1 query
                    isMember = isEPersonInGroup(context, group, ePerson);
                }

                //If we did not find the group membership in the database, check the special groups.
                //If there are special groups we need to check direct membership or check if the
                //special group is a subgroup of the provided group.
                //Note that special groups should only be checked if the current user == the ePerson.
                //This also works for anonymous users (ePerson == null) if IP authentication used
                if (!isMember && CollectionUtils.isNotEmpty(context.getSpecialGroups()) &&
                    isAuthenticatedUser(context, ePerson)) {

                    Iterator<Group> it = context.getSpecialGroups().iterator();

                    while (it.hasNext() && !isMember) {
                        Group specialGroup = it.next();
                        //Check if the special group matches the given group or if it is a subgroup (with 1 query)
                        if (specialGroup.equals(group) || isParentOf(context, group, specialGroup)) {
                            isMember = true;
                        }
                    }
                }

                context.cacheGroupMembership(group, ePerson, isMember);
                return isMember;

            }
        }
    }

    private boolean isAuthenticatedUser(final Context context, final EPerson ePerson) {
        return Objects.equals(context.getCurrentUser(), ePerson);
    }

    @Override
    public boolean isMember(final Context context, final String groupName) throws SQLException {
        return isMember(context, findByName(context, groupName));
    }

    @Override
    public boolean isMember(final Context context, EPerson eperson, final String groupName) throws SQLException {
        return isMember(context, eperson, findByName(context, groupName));
    }

    @Override
    public List<Group> allMemberGroups(Context context, EPerson ePerson) throws SQLException {
        return new ArrayList<>(allMemberGroupsSet(context, ePerson));
    }

    @Override
    public Set<Group> allMemberGroupsSet(Context context, EPerson ePerson) throws SQLException {
        Set<Group> cachedGroupMembership = context.getCachedAllMemberGroupsSet(ePerson);
        if (cachedGroupMembership != null) {
            return cachedGroupMembership;
        }

        Set<Group> groups = new HashSet<>();

        if (ePerson != null) {
            // two queries - first to get groups eperson is a member of
            // second query gets parent groups for groups eperson is a member of
            groups.addAll(groupDAO.findByEPerson(context, ePerson));
        }
        // Also need to get all "Special Groups" user is a member of!
        // Otherwise, you're ignoring the user's membership to these groups!
        // However, we only do this is we are looking up the special groups
        // of the current user, as we cannot look up the special groups
        // of a user who is not logged in.
        if ((context.getCurrentUser() == null) || (context.getCurrentUser().equals(ePerson))) {
            List<Group> specialGroups = context.getSpecialGroups();
            for (Group special : specialGroups) {
                groups.add(special);
            }
        }

        // all the users are members of the anonymous group
        groups.add(findByName(context, Group.ANONYMOUS));

        List<Group2GroupCache> groupCache = group2GroupCacheDAO.findByChildren(context, groups);
        // now we have all owning groups, also grab all parents of owning groups
        // yes, I know this could have been done as one big query and a union,
        // but doing the Oracle port taught me to keep to simple SQL!
        for (Group2GroupCache group2GroupCache : groupCache) {
            groups.add(group2GroupCache.getParent());
        }

        context.cacheAllMemberGroupsSet(ePerson, groups);
        return groups;
    }

    @Override
    public List<EPerson> allMembers(Context c, Group g) throws SQLException {
        // two queries - first to get all groups which are a member of this group
        // second query gets all members of each group in the first query

        // Get all groups which are a member of this group
        List<Group2GroupCache> group2GroupCaches = group2GroupCacheDAO.findByParent(c, g);
        Set<Group> groups = new HashSet<>();
        for (Group2GroupCache group2GroupCache : group2GroupCaches) {
            groups.add(group2GroupCache.getChild());
        }

        Set<EPerson> childGroupChildren = new HashSet<>(ePersonService.findByGroups(c, groups));
        //Don't forget to add our direct children
        childGroupChildren.addAll(g.getMembers());

        return new ArrayList<>(childGroupChildren);
    }

    @Override
    public Group find(Context context, UUID id) throws SQLException {
        if (id == null) {
            return null;
        } else {
            return groupDAO.findByID(context, Group.class, id);
        }
    }

    @Override
    public Group findByName(Context context, String name) throws SQLException {
        if (name == null) {
            return null;
        }

        return groupDAO.findByName(context, name);
    }

    /**
     * DEPRECATED: Please use {@code findAll(Context context, List<MetadataField> metadataSortFields)} instead
     */
    @Override
    @Deprecated
    public List<Group> findAll(Context context, int sortField) throws SQLException {
        if (sortField == GroupService.NAME) {
            return findAll(context, null);
        } else {
            throw new UnsupportedOperationException("You can only find all groups sorted by name with this method");
        }
    }

    @Override
    public List<Group> findAll(Context context, List<MetadataField> metadataSortFields) throws SQLException {
        return findAll(context, metadataSortFields, -1, -1);
    }

    @Override
    public List<Group> findAll(Context context, List<MetadataField> metadataSortFields, int pageSize, int offset)
        throws SQLException {
        if (CollectionUtils.isEmpty(metadataSortFields)) {
            return groupDAO.findAll(context, pageSize, offset);
        } else {
            return groupDAO.findAll(context, metadataSortFields, pageSize, offset);
        }
    }

    @Override
    public List<Group> search(Context context, String groupIdentifier) throws SQLException {
        return search(context, groupIdentifier, -1, -1);
    }

    @Override
    public List<Group> search(Context context, String groupIdentifier, int offset, int limit) throws SQLException {
        List<Group> groups = new ArrayList<>();
        UUID uuid = UUIDUtils.fromString(groupIdentifier);
        if (uuid == null) {
            //Search by group name
            groups = groupDAO.findByNameLike(context, groupIdentifier, offset, limit);
        } else {
            //Search by group id
            Group group = find(context, uuid);
            if (group != null) {
                groups.add(group);
            }
        }

        return groups;
    }

    @Override
    public int searchResultCount(Context context, String groupIdentifier) throws SQLException {
        int result = 0;
        UUID uuid = UUIDUtils.fromString(groupIdentifier);
        if (uuid == null) {
            //Search by group name
            result = groupDAO.countByNameLike(context, groupIdentifier);
        } else {
            //Search by group id
            Group group = find(context, uuid);
            if (group != null) {
                result = 1;
            }
        }

        return result;
    }

    @Override
    public void delete(Context context, Group group) throws SQLException {
        if (group.isPermanent()) {
            log.error("Attempt to delete permanent Group $", group.getName());
            throw new SQLException("Attempt to delete a permanent Group");
        }

        context.addEvent(new Event(Event.DELETE, Constants.GROUP, group.getID(),
                                   group.getName(), getIdentifiers(context, group)));

        //Remove the supervised group from any workspace items linked to us.
        group.getSupervisedItems().clear();

        // Remove any ResourcePolicies that reference this group
        authorizeService.removeGroupPolicies(context, group);

        group.getMemberGroups().clear();
        group.getParentGroups().clear();

        //Remove all eperson references from this group
        Iterator<EPerson> ePeople = group.getMembers().iterator();
        while (ePeople.hasNext()) {
            EPerson ePerson = ePeople.next();
            ePeople.remove();
            ePerson.getGroups().remove(group);
        }

        // empty out group2groupcache table (if we do it after we delete our object we get an issue with references)
        group2GroupCacheDAO.deleteAll(context);
        // Remove ourself
        groupDAO.delete(context, group);
        rethinkGroupCache(context, false);

        log.info(LogHelper.getHeader(context, "delete_group", "group_id="
            + group.getID()));
    }

    @Override
    public int getSupportsTypeConstant() {
        return Constants.GROUP;
    }

    /**
     * Return true if group has no direct or indirect members
     */
    @Override
    public boolean isEmpty(Group group) {
        // the only fast check available is on epeople...
        boolean hasMembers = (!group.getMembers().isEmpty());

        if (hasMembers) {
            return false;
        } else {
            // well, groups is never null...
            for (Group subGroup : group.getMemberGroups()) {
                hasMembers = !isEmpty(subGroup);
                if (hasMembers) {
                    return false;
                }
            }
            return !hasMembers;
        }
    }

    @Override
    public void initDefaultGroupNames(Context context) throws SQLException, AuthorizeException {
        GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
        // Check for Anonymous group. If not found, create it
        Group anonymousGroup = groupService.findByName(context, Group.ANONYMOUS);
        if (anonymousGroup == null) {
            anonymousGroup = groupService.create(context);
            anonymousGroup.setName(Group.ANONYMOUS);
            anonymousGroup.setPermanent(true);
            groupService.update(context, anonymousGroup);
        }

        // Check for Administrator group. If not found, create it
        Group adminGroup = groupService.findByName(context, Group.ADMIN);
        if (adminGroup == null) {
            adminGroup = groupService.create(context);
            adminGroup.setName(Group.ADMIN);
            adminGroup.setPermanent(true);
            groupService.update(context, adminGroup);
        }
    }

    /**
     * Get a list of groups with no members.
     *
     * @param context The relevant DSpace Context.
     * @return list of groups with no members
     * @throws SQLException An exception that provides information on a database access error or other errors.
     */
    @Override
    public List<Group> getEmptyGroups(Context context) throws SQLException {
        return groupDAO.getEmptyGroups(context);
    }

    /**
     * Update the group - writing out group object and EPerson list if necessary
     *
     * @param context The relevant DSpace Context.
     * @param group   Group to update
     * @throws SQLException       An exception that provides information on a database access error or other errors.
     * @throws AuthorizeException Exception indicating the current user of the context does not have permission
     *                            to perform a particular action.
     */
    @Override
    public void update(Context context, Group group) throws SQLException, AuthorizeException {

        super.update(context, group);
        // FIXME: Check authorisation
        groupDAO.save(context, group);

        if (group.isMetadataModified()) {
            context.addEvent(new Event(Event.MODIFY_METADATA, Constants.GROUP, group.getID(), group.getDetails(),
                                       getIdentifiers(context, group)));
            group.clearDetails();
        }

        if (group.isGroupsChanged()) {
            rethinkGroupCache(context, true);
            group.clearGroupsChanged();
        }

        log.info(LogHelper.getHeader(context, "update_group", "group_id="
            + group.getID()));
    }

    protected boolean isEPersonInGroup(Context context, Group group, EPerson ePerson)
        throws SQLException {
        return groupDAO.findByIdAndMembership(context, group.getID(), ePerson) != null;
    }

    /**
     * Regenerate the group cache AKA the group2groupcache table in the database -
     * meant to be called when a group is added or removed from another group
     *
     * @param context      The relevant DSpace Context.
     * @param flushQueries flushQueries Flush all pending queries
     * @throws SQLException An exception that provides information on a database access error or other errors.
     */
    protected void rethinkGroupCache(Context context, boolean flushQueries) throws SQLException {

        Map<UUID, Set<UUID>> parents = new HashMap<>();

        List<Pair<UUID, UUID>> group2groupResults = groupDAO.getGroup2GroupResults(context, flushQueries);
        for (Pair<UUID, UUID> group2groupResult : group2groupResults) {
            UUID parent = group2groupResult.getLeft();
            UUID child = group2groupResult.getRight();

            // if parent doesn't have an entry, create one
            if (!parents.containsKey(parent)) {
                Set<UUID> children = new HashSet<>();

                // add child id to the list
                children.add(child);
                parents.put(parent, children);
            } else {
                // parent has an entry, now add the child to the parent's record
                // of children
                Set<UUID> children = parents.get(parent);
                children.add(child);
            }
        }

        // now parents is a hash of all of the IDs of groups that are parents
        // and each hash entry is a hash of all of the IDs of children of those
        // parent groups
        // so now to establish all parent,child relationships we can iterate
        // through the parents hash
        for (Map.Entry<UUID, Set<UUID>> parent : parents.entrySet()) {
            Set<UUID> myChildren = getChildren(parents, parent.getKey());
            parent.getValue().addAll(myChildren);
        }

        // empty out group2groupcache table
        group2GroupCacheDAO.deleteAll(context);

        // write out new one
        for (Map.Entry<UUID, Set<UUID>> parent : parents.entrySet()) {
            UUID key = parent.getKey();

            for (UUID child : parent.getValue()) {

                Group parentGroup = find(context, key);
                Group childGroup = find(context, child);

                if (parentGroup != null && childGroup != null && group2GroupCacheDAO
                    .find(context, parentGroup, childGroup) == null) {
                    Group2GroupCache group2GroupCache = group2GroupCacheDAO.create(context, new Group2GroupCache());
                    group2GroupCache.setParent(parentGroup);
                    group2GroupCache.setChild(childGroup);
                    group2GroupCacheDAO.save(context, group2GroupCache);
                }
            }
        }
    }

    @Override
    public DSpaceObject getParentObject(Context context, Group group) throws SQLException {
        if (group == null) {
            return null;
        }
        // could a collection/community administrator manage related groups?
        // check before the configuration options could give a performance gain
        // if all group management are disallowed
        if (AuthorizeConfiguration.canCollectionAdminManageAdminGroup()
            || AuthorizeConfiguration.canCollectionAdminManageSubmitters()
            || AuthorizeConfiguration.canCollectionAdminManageWorkflows()
            || AuthorizeConfiguration.canCommunityAdminManageAdminGroup()
            || AuthorizeConfiguration
            .canCommunityAdminManageCollectionAdminGroup()
            || AuthorizeConfiguration
            .canCommunityAdminManageCollectionSubmitters()
            || AuthorizeConfiguration
            .canCommunityAdminManageCollectionWorkflows()) {
            // is this a collection related group?
            org.dspace.content.Collection collection = collectionService.findByGroup(context, group);

            if (collection != null) {
                if (group.equals(collection.getSubmitters())) {
                    if (AuthorizeConfiguration.canCollectionAdminManageSubmitters()) {
                        return collection;
                    } else if (AuthorizeConfiguration.canCommunityAdminManageCollectionSubmitters()) {
                        return collectionService.getParentObject(context, collection);
                    }
                }
                if (group.equals(collection.getAdministrators())) {
                    if (AuthorizeConfiguration.canCollectionAdminManageAdminGroup()) {
                        return collection;
                    } else if (AuthorizeConfiguration.canCommunityAdminManageCollectionAdminGroup()) {
                        return collectionService.getParentObject(context, collection);
                    }
                }
            } else {
                if (AuthorizeConfiguration.canCollectionAdminManageWorkflows()
                        || AuthorizeConfiguration.canCommunityAdminManageCollectionWorkflows()) {
                    // if the group is used for one or more roles on a single collection,
                    // admins can eventually manage it
                    List<CollectionRole> collectionRoles = collectionRoleService.findByGroup(context, group);
                    if (collectionRoles != null && collectionRoles.size() > 0) {
                        Set<Collection> colls = new HashSet<>();
                        for (CollectionRole cr : collectionRoles) {
                            colls.add(cr.getCollection());
                        }
                        if (colls.size() == 1) {
                            collection = colls.iterator().next();
                            if (AuthorizeConfiguration.canCollectionAdminManageWorkflows()) {
                                return collection;
                            } else {
                                return collectionService.getParentObject(context, collection);
                            }
                        }
                    } else {
                        if (AuthorizeConfiguration.canCollectionAdminManagePolicies()
                            || AuthorizeConfiguration.canCommunityAdminManagePolicies()
                            || AuthorizeConfiguration.canCommunityAdminManageCollectionWorkflows()) {
                            List<Group> groups = new ArrayList<>();
                            groups.add(group);
                            List<ResourcePolicy> policies = resourcePolicyService.find(context, null, groups,
                                                            Constants.DEFAULT_ITEM_READ, Constants.COLLECTION);
                            if (policies.size() > 0) {
                                return policies.get(0).getdSpaceObject();
                            }
                            policies = resourcePolicyService.find(context, null, groups,
                                                             Constants.DEFAULT_BITSTREAM_READ, Constants.COLLECTION);
                            if (policies.size() > 0) {
                                return policies.get(0).getdSpaceObject();
                            }
                        }
                    }
                }
                if (AuthorizeConfiguration.canCommunityAdminManageAdminGroup()) {
                    // is the group related to a community and community administrator allowed
                    // to manage it?
                    return communityService.findByAdminGroup(context, group);
                }
            }
        }
        return null;
    }

    @Override
    public void updateLastModified(Context context, Group dso) {
        //Not needed.
    }

    /**
     * Used recursively to generate a map of ALL of the children of the given
     * parent
     *
     * @param parents Map of parent,child relationships
     * @param parent  the parent you're interested in
     * @return Map whose keys are all of the children of a parent
     */
    protected Set<UUID> getChildren(Map<UUID, Set<UUID>> parents, UUID parent) {
        Set<UUID> myChildren = new HashSet<>();

        // degenerate case, this parent has no children
        if (!parents.containsKey(parent)) {
            return myChildren;
        }

        // got this far, so we must have children
        Set<UUID> children = parents.get(parent);

        // now iterate over all of the children

        for (UUID child : children) {
            // add this child's ID to our return set
            myChildren.add(child);

            // and now its children
            myChildren.addAll(getChildren(parents, child));
        }

        return myChildren;
    }

    @Override
    public Group findByIdOrLegacyId(Context context, String id) throws SQLException {
        if (org.apache.commons.lang3.StringUtils.isNumeric(id)) {
            return findByLegacyId(context, Integer.parseInt(id));
        } else {
            return find(context, UUIDUtils.fromString(id));
        }
    }

    @Override
    public Group findByLegacyId(Context context, int id) throws SQLException {
        return groupDAO.findByLegacyId(context, id, Group.class);
    }

    @Override
    public int countTotal(Context context) throws SQLException {
        return groupDAO.countRows(context);
    }

    @Override
    public List<Group> findByMetadataField(final Context context, final String searchValue,
                                           final MetadataField metadataField) throws SQLException {
        return groupDAO.findByMetadataField(context, searchValue, metadataField);
    }
}

Output:
【漏洞类型】硬编码字符串
【严重性】中等
【漏洞摘要】在`CollectionServiceImpl`类的`createDefaultReadGroup`方法中，硬编码了组名的生成字符串模式。这种方式容易导致组名生成的不一致，从而影响系统的安全性和可维护性。
【关键代码模式】在方法中直接拼接字符串以生成组名。
【修复方法说明】将组名的生成逻辑提取到单独的方法中，以确保组名的一致性和可维护性。


Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
.patches/security/advisories.json
### 代码内容：
{
    "cves": [
      {
        "cveID": "CVE-2021-39179",
        "privateForkUrl": "https://github.com/dhis2/dhis2-core-ghsa-cmpc-frjv-rrmw",
        "status": "FIXED",
        "pullRequests": [
          {
            "prNumber": 11,
            "target": "patch/2.34.7"
          },
          {
            "prNumber": 4,
            "target": "patch/2.35.7"
          },
          {
            "prNumber": 15,
            "target": "patch/2.35.8"
          },
          {
            "prNumber": 3,
            "target": "patch/2.36.4"
          }
        ]
      },
      {
        "cveID": "CVE-2021-XXXXX",
        "privateForkUrl": "https://github.com/dhis2/dhis2-core-ghsa-fvm5-gp3j-c7c6",
        "status": "FIXED",
        "pullRequests": [
          {
            "prNumber": 6,
            "target": "patch/2.34.7"
          },
          {
            "prNumber": 3,
            "target": "patch/2.35.8"
          },
          {
            "prNumber": 2,
            "target": "patch/2.36.4"
          }
        ]
      }
    ]
}

Output:
【漏洞类型】数据泄露
【严重性】Medium
【漏洞摘要】这是由于代码中的硬编码URL，可能会导致敏感信息泄露。具体表现为在advisories.json文件中，privateForkUrl字段中包含了指向私有仓库的URL。
【关键代码模式】硬编码URL、敏感信息泄露、privateForkUrl字段
【修复方法说明】通过提交中提到的“build: correct patch PRs (#8771)”修复了此问题，可能通过移除或加密敏感URL来防止信息泄露。