Search in sources :

Example 1 with Context

use of org.dspace.core.Context in project DSpace by DSpace.

the class EPersonCLITool method main.

/**
 * Tool for manipulating user accounts.
 *
 * @param argv the command line arguments given
 * @throws ParseException     Base for Exceptions thrown during parsing of a command-line.
 * @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.
 */
public static void main(String[] argv) throws ParseException, SQLException, AuthorizeException {
    final OptionGroup VERBS = new OptionGroup();
    VERBS.addOption(VERB_ADD);
    VERBS.addOption(VERB_DELETE);
    VERBS.addOption(VERB_LIST);
    VERBS.addOption(VERB_MODIFY);
    final Options globalOptions = new Options();
    globalOptions.addOptionGroup(VERBS);
    globalOptions.addOption("h", "help", false, "explain options");
    CommandLineParser parser = new DefaultParser();
    CommandLine command = parser.parse(globalOptions, argv, true);
    Context context = new Context();
    // Disable authorization since this only runs from the local commandline.
    context.turnOffAuthorisationSystem();
    int status = 0;
    if (command.hasOption(VERB_ADD.getOpt())) {
        status = cmdAdd(context, argv);
    } else if (command.hasOption(VERB_DELETE.getOpt())) {
        status = cmdDelete(context, argv);
    } else if (command.hasOption(VERB_MODIFY.getOpt())) {
        status = cmdModify(context, argv);
    } else if (command.hasOption(VERB_LIST.getOpt())) {
        status = cmdList(context, argv);
    } else if (command.hasOption('h')) {
        new HelpFormatter().printHelp("user [options]", globalOptions);
    } else {
        System.err.println("Unknown operation.");
        new HelpFormatter().printHelp("user [options]", globalOptions);
        context.abort();
        status = 1;
    }
    if (context.isValid()) {
        try {
            context.complete();
        } catch (SQLException ex) {
            System.err.println(ex.getMessage());
        }
    }
    System.exit(status);
}
Also used : Context(org.dspace.core.Context) HelpFormatter(org.apache.commons.cli.HelpFormatter) Options(org.apache.commons.cli.Options) CommandLine(org.apache.commons.cli.CommandLine) OptionGroup(org.apache.commons.cli.OptionGroup) SQLException(java.sql.SQLException) CommandLineParser(org.apache.commons.cli.CommandLineParser) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 2 with Context

use of org.dspace.core.Context in project DSpace by DSpace.

the class SolrServiceImpl method cleanIndex.

/**
 * Iterates over all documents in the Lucene index and verifies they are in
 * database, if not, they are removed.
 *
 * @throws IOException            IO exception
 * @throws SQLException           sql exception
 * @throws SearchServiceException occurs when something went wrong with querying the solr server
 */
@Override
public void cleanIndex() throws IOException, SQLException, SearchServiceException {
    Context context = new Context();
    context.turnOffAuthorisationSystem();
    try {
        if (solrSearchCore.getSolr() == null) {
            return;
        }
        // First, we'll just get a count of the total results
        SolrQuery countQuery = new SolrQuery("*:*");
        // don't actually request any data
        countQuery.setRows(0);
        // Get the total amount of results
        QueryResponse totalResponse = solrSearchCore.getSolr().query(countQuery, solrSearchCore.REQUEST_METHOD);
        long total = totalResponse.getResults().getNumFound();
        int start = 0;
        int batch = 100;
        // Now get actual Solr Documents in batches
        SolrQuery query = new SolrQuery();
        query.setFields(SearchUtils.RESOURCE_UNIQUE_ID, SearchUtils.RESOURCE_ID_FIELD, SearchUtils.RESOURCE_TYPE_FIELD);
        query.addSort(SearchUtils.RESOURCE_UNIQUE_ID, SolrQuery.ORDER.asc);
        query.setQuery("*:*");
        query.setRows(batch);
        // Keep looping until we hit the total number of Solr docs
        while (start < total) {
            query.setStart(start);
            QueryResponse rsp = solrSearchCore.getSolr().query(query, solrSearchCore.REQUEST_METHOD);
            SolrDocumentList docs = rsp.getResults();
            for (SolrDocument doc : docs) {
                String uniqueID = (String) doc.getFieldValue(SearchUtils.RESOURCE_UNIQUE_ID);
                IndexableObject o = findIndexableObject(context, doc);
                if (o == null) {
                    log.info("Deleting: " + uniqueID);
                    /*
                         * Use IndexWriter to delete, its easier to manage
                         * write.lock
                         */
                    unIndexContent(context, uniqueID);
                } else {
                    log.debug("Keeping: " + o.getUniqueIndexID());
                }
            }
            start += batch;
        }
    } catch (IOException | SQLException | SolrServerException e) {
        log.error("Error cleaning discovery index: " + e.getMessage(), e);
    } finally {
        context.abort();
    }
}
Also used : Context(org.dspace.core.Context) SQLException(java.sql.SQLException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) SolrDocumentList(org.apache.solr.common.SolrDocumentList) IOException(java.io.IOException) SolrQuery(org.apache.solr.client.solrj.SolrQuery) SolrDocument(org.apache.solr.common.SolrDocument) QueryResponse(org.apache.solr.client.solrj.response.QueryResponse)

Example 3 with Context

use of org.dspace.core.Context in project DSpace by DSpace.

the class Groomer method aging.

/**
 * Find and optionally delete accounts not logged in recently.
 *
 * @param command a parsed command line.
 * @throws SQLException from callees.
 */
private static void aging(CommandLine command) throws SQLException {
    if (!command.hasOption('b')) {
        System.err.println("A last login date is required.");
        System.exit(1);
    }
    Date before = null;
    try {
        before = dateFormat.get().parse(command.getOptionValue('b'));
    } catch (java.text.ParseException ex) {
        System.err.println(ex.getMessage());
        System.exit(1);
    }
    boolean delete = command.hasOption('d');
    Context myContext = new Context();
    List<EPerson> epeople = ePersonService.findNotActiveSince(myContext, before);
    myContext.turnOffAuthorisationSystem();
    for (EPerson account : epeople) {
        System.out.print(account.getID());
        System.out.print('\t');
        System.out.print(account.getLastActive());
        System.out.print('\t');
        System.out.print(account.getEmail());
        System.out.print('\t');
        System.out.print(account.getNetid());
        System.out.print('\t');
        System.out.print(account.getFullName());
        System.out.println();
        if (delete) {
            List<String> whyNot = ePersonService.getDeleteConstraints(myContext, account);
            if (!whyNot.isEmpty()) {
                System.out.print("\tCannot be deleted; referenced in");
                for (String table : whyNot) {
                    System.out.print(' ');
                    System.out.print(table);
                }
                System.out.println();
            } else {
                try {
                    ePersonService.delete(myContext, account);
                } catch (AuthorizeException | IOException ex) {
                    System.err.println(ex.getMessage());
                }
            }
        }
    }
    myContext.restoreAuthSystemState();
    myContext.complete();
}
Also used : Context(org.dspace.core.Context) AuthorizeException(org.dspace.authorize.AuthorizeException) Context(org.dspace.core.Context) IOException(java.io.IOException) Date(java.util.Date)

Example 4 with Context

use of org.dspace.core.Context in project DSpace by DSpace.

the class Groomer method findUnsalted.

/**
 * List accounts having no password salt.
 *
 * @throws SQLException if database error
 */
private static void findUnsalted() throws SQLException {
    Context myContext = new Context();
    List<EPerson> ePersons = ePersonService.findUnsalted(myContext);
    for (EPerson ePerson : ePersons) {
        System.out.println(ePerson.getEmail());
    }
    // No changes to commit
    myContext.abort();
}
Also used : Context(org.dspace.core.Context)

Example 5 with Context

use of org.dspace.core.Context in project DSpace by DSpace.

the class GroupServiceImpl method getParentObject.

@Override
public DSpaceObject getParentObject(Context context, Group group) throws SQLException {
    if (group == null) {
        return null;
    }
    // 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);
                        Optional<ResourcePolicy> defaultPolicy = policies.stream().filter(p -> StringUtils.equals(collectionService.getDefaultReadGroupName((Collection) p.getdSpaceObject(), "ITEM"), group.getName())).findFirst();
                        if (defaultPolicy.isPresent()) {
                            return defaultPolicy.get().getdSpaceObject();
                        }
                        policies = resourcePolicyService.find(context, null, groups, Constants.DEFAULT_BITSTREAM_READ, Constants.COLLECTION);
                        defaultPolicy = policies.stream().filter(p -> StringUtils.equals(collectionService.getDefaultReadGroupName((Collection) p.getdSpaceObject(), "BITSTREAM"), group.getName())).findFirst();
                        if (defaultPolicy.isPresent()) {
                            return defaultPolicy.get().getdSpaceObject();
                        }
                    }
                }
            }
            if (AuthorizeConfiguration.canCommunityAdminManageAdminGroup()) {
                // to manage it?
                return communityService.findByAdminGroup(context, group);
            }
        }
    }
    return null;
}
Also used : Group2GroupCacheDAO(org.dspace.eperson.dao.Group2GroupCacheDAO) CollectionRoleService(org.dspace.xmlworkflow.storedcomponents.service.CollectionRoleService) Event(org.dspace.event.Event) Role(org.dspace.xmlworkflow.Role) LoggerFactory(org.slf4j.LoggerFactory) GroupService(org.dspace.eperson.service.GroupService) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) GroupDAO(org.dspace.eperson.dao.GroupDAO) StringUtils(org.apache.commons.lang3.StringUtils) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) XmlWorkflowFactory(org.dspace.xmlworkflow.factory.XmlWorkflowFactory) HashSet(java.util.HashSet) Constants(org.dspace.core.Constants) SQLException(java.sql.SQLException) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) AuthorizeConfiguration(org.dspace.authorize.AuthorizeConfiguration) AuthorizeService(org.dspace.authorize.service.AuthorizeService) Collection(org.dspace.content.Collection) PoolTaskService(org.dspace.xmlworkflow.storedcomponents.service.PoolTaskService) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) MetadataField(org.dspace.content.MetadataField) DSpaceObjectServiceImpl(org.dspace.content.DSpaceObjectServiceImpl) Step(org.dspace.xmlworkflow.state.Step) AuthorizeException(org.dspace.authorize.AuthorizeException) Set(java.util.Set) UUIDUtils(org.dspace.util.UUIDUtils) UUID(java.util.UUID) EPersonService(org.dspace.eperson.service.EPersonService) ResourcePolicy(org.dspace.authorize.ResourcePolicy) ClaimedTaskService(org.dspace.xmlworkflow.storedcomponents.service.ClaimedTaskService) Objects(java.util.Objects) DSpaceObject(org.dspace.content.DSpaceObject) List(java.util.List) EPersonServiceFactory(org.dspace.eperson.factory.EPersonServiceFactory) Context(org.dspace.core.Context) PoolTask(org.dspace.xmlworkflow.storedcomponents.PoolTask) Optional(java.util.Optional) CommunityService(org.dspace.content.service.CommunityService) LogHelper(org.dspace.core.LogHelper) CollectionRole(org.dspace.xmlworkflow.storedcomponents.CollectionRole) CollectionService(org.dspace.content.service.CollectionService) ClaimedTask(org.dspace.xmlworkflow.storedcomponents.ClaimedTask) ResourcePolicyService(org.dspace.authorize.service.ResourcePolicyService) ArrayList(java.util.ArrayList) Collection(org.dspace.content.Collection) ResourcePolicy(org.dspace.authorize.ResourcePolicy) CollectionRole(org.dspace.xmlworkflow.storedcomponents.CollectionRole) Collection(org.dspace.content.Collection) HashSet(java.util.HashSet)

Aggregations

Context (org.dspace.core.Context)438 SQLException (java.sql.SQLException)193 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)101 ResourceNotFoundException (org.springframework.data.rest.webmvc.ResourceNotFoundException)82 AuthorizeException (org.dspace.authorize.AuthorizeException)73 IOException (java.io.IOException)64 Collection (org.dspace.content.Collection)63 Item (org.dspace.content.Item)62 EPerson (org.dspace.eperson.EPerson)53 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)42 SearchRestMethod (org.dspace.app.rest.SearchRestMethod)39 UnprocessableEntityException (org.dspace.app.rest.exception.UnprocessableEntityException)35 DSpaceObject (org.dspace.content.DSpaceObject)35 Test (org.junit.Test)33 Group (org.dspace.eperson.Group)31 ArrayList (java.util.ArrayList)30 Date (java.util.Date)29 Bitstream (org.dspace.content.Bitstream)29 Community (org.dspace.content.Community)29 File (java.io.File)27