Search in sources :

Example 1 with HandleService

use of org.dspace.handle.service.HandleService in project DSpace by DSpace.

the class SWORDMETSIngester method ingest.

/* (non-Javadoc)
     * @see org.dspace.sword.SWORDIngester#ingest(org.dspace.core.Context, org.purl.sword.base.Deposit)
     */
@Override
public DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject dso) throws DSpaceSWORDException, SWORDErrorException {
    try {
        // first, make sure this is the right kind of ingester, and set the collection
        if (!(dso instanceof Collection)) {
            throw new DSpaceSWORDException("Tried to run an ingester on wrong target type");
        }
        Collection collection = (Collection) dso;
        // now set the sword service
        swordService = service;
        // get the things out of the service that we need
        Context context = swordService.getContext();
        // get deposited file as InputStream
        File depositFile = deposit.getFile();
        // load the plugin manager for the required configuration
        String cfg = configurationService.getProperty("sword-server.mets-ingester.package-ingester");
        if (cfg == null || "".equals(cfg)) {
            // default to METS
            cfg = "METS";
        }
        swordService.message("Using package manifest format: " + cfg);
        PackageIngester pi = (PackageIngester) CoreServiceFactory.getInstance().getPluginService().getNamedPlugin(PackageIngester.class, cfg);
        swordService.message("Loaded package ingester: " + pi.getClass().getName());
        // the licence is either in the zip or the mets manifest.  Either way
        // it's none of our business here
        String licence = null;
        // Initialize parameters to packager
        PackageParameters params = new PackageParameters();
        // Force package ingester to respect Collection workflows
        params.setWorkflowEnabled(true);
        // Should restore mode be enabled, i.e. keep existing handle?
        if (configurationService.getBooleanProperty("sword-server.restore-mode.enable", false)) {
            params.setRestoreModeEnabled(true);
        }
        // Whether or not to use the collection template
        params.setUseCollectionTemplate(configurationService.getBooleanProperty("mets.default.ingest.useCollectionTemplate", false));
        // ingest the item from the temp file
        DSpaceObject ingestedObject = pi.ingest(context, collection, depositFile, params, licence);
        if (ingestedObject == null) {
            swordService.message("Failed to ingest the package; throwing exception");
            throw new SWORDErrorException(DSpaceSWORDErrorCodes.UNPACKAGE_FAIL, "METS package ingester failed to unpack package");
        }
        // Verify we have an Item as a result -- SWORD can only ingest Items
        if (!(ingestedObject instanceof Item)) {
            throw new DSpaceSWORDException("DSpace Ingester returned wrong object type -- not an Item result.");
        } else {
            // otherwise, we have an item, and a workflow should have already been started for it.
            swordService.message("Workflow process started");
        }
        // get reference to item so that we can report on it
        Item installedItem = (Item) ingestedObject;
        // update the item metadata to inclue the current time as
        // the updated date
        this.setUpdatedDate(context, installedItem);
        // DSpace ignores the slug value as suggested identifier, but
        // it does store it in the metadata
        this.setSlug(installedItem, deposit.getSlug());
        // in order to write these changes, we need to bypass the
        // authorisation briefly, because although the user may be
        // able to add stuff to the repository, they may not have
        // WRITE permissions on the archive.
        context.turnOffAuthorisationSystem();
        itemService.update(context, installedItem);
        context.restoreAuthSystemState();
        // for some reason, DSpace will not give you the handle automatically,
        // so we have to look it up
        HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
        String handle = handleService.findHandle(context, installedItem);
        swordService.message("Ingest successful");
        swordService.message("Item created with internal identifier: " + installedItem.getID());
        if (handle != null) {
            swordService.message("Item created with external identifier: " + handle);
        } else {
            swordService.message("No external identifier available at this stage (item in workflow)");
        }
        DepositResult dr = new DepositResult();
        dr.setItem(installedItem);
        dr.setHandle(handle);
        dr.setTreatment(this.getTreatment());
        return dr;
    } catch (RuntimeException re) {
        log.error("caught exception: ", re);
        throw re;
    } catch (Exception e) {
        log.error("caught exception: ", e);
        throw new DSpaceSWORDException(e);
    }
}
Also used : Context(org.dspace.core.Context) SWORDErrorException(org.purl.sword.base.SWORDErrorException) SQLException(java.sql.SQLException) Item(org.dspace.content.Item) PackageIngester(org.dspace.content.packager.PackageIngester) DSpaceObject(org.dspace.content.DSpaceObject) Collection(org.dspace.content.Collection) PackageParameters(org.dspace.content.packager.PackageParameters) File(java.io.File) HandleService(org.dspace.handle.service.HandleService) SWORDErrorException(org.purl.sword.base.SWORDErrorException)

Example 2 with HandleService

use of org.dspace.handle.service.HandleService in project DSpace by DSpace.

the class UpdateHandlePrefix method main.

/**
 * When invoked as a command-line tool, updates handle prefix
 *
 * @param args the command-line arguments, none used
 * @throws Exception on generic exception
 */
public static void main(String[] args) throws Exception {
    // There should be two parameters
    if (args.length < 2) {
        System.out.println("\nUsage: update-handle-prefix <old handle> <new handle>\n");
        System.exit(1);
    } else {
        HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
        String oldH = args[0];
        String newH = args[1];
        // Get info about changes
        System.out.println("\nGetting information about handles from database...");
        Context context = new Context();
        long count = handleService.countHandlesByPrefix(context, oldH);
        if (count > 0) {
            // Print info text about changes
            System.out.println("In your repository will be updated " + count + " handle" + ((count > 1) ? "s" : "") + " to new prefix " + newH + " from original " + oldH + "!\n");
            // Confirm with the user that this is what they want to do
            System.out.print("Servlet container (e.g. Apache Tomcat, Jetty, Caucho Resin) must be running.\n" + "If it is necessary, please make a backup of the database.\n" + "Are you ready to continue? [y/n]: ");
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            String choiceString = input.readLine();
            if (choiceString.equalsIgnoreCase("y")) {
                context.turnOffAuthorisationSystem();
                try {
                    log.info("Updating handle prefix from " + oldH + " to " + newH);
                    // Make the changes
                    System.out.print("\nUpdating handle table... ");
                    int updHdl = handleService.updateHandlesWithNewPrefix(context, newH, oldH);
                    System.out.println(updHdl + " item" + ((updHdl > 1) ? "s" : "") + " updated");
                    System.out.print("Updating metadatavalues table... ");
                    MetadataValueService metadataValueService = ContentServiceFactory.getInstance().getMetadataValueService();
                    String handlePrefix = handleService.getCanonicalPrefix();
                    Iterator<MetadataValue> metadataValues = metadataValueService.findByValueLike(context, handlePrefix + oldH);
                    int updMeta = 0;
                    while (metadataValues.hasNext()) {
                        MetadataValue metadataValue = metadataValues.next();
                        metadataValue.setValue(metadataValue.getValue().replace(handlePrefix + oldH, handlePrefix + newH));
                        metadataValueService.update(context, metadataValue, true);
                        context.uncacheEntity(metadataValue);
                        updMeta++;
                    }
                    System.out.println(updMeta + " metadata value" + ((updMeta > 1) ? "s" : "") + " updated");
                    // Commit the changes
                    context.complete();
                    log.info("Done with updating handle prefix. " + "It was changed " + updHdl + " handle" + ((updHdl > 1) ? "s" : "") + " and " + updMeta + " metadata record" + ((updMeta > 1) ? "s" : ""));
                } catch (SQLException sqle) {
                    if ((context != null) && (context.isValid())) {
                        context.abort();
                        context = null;
                    }
                    System.out.println("\nError during SQL operations.");
                    throw sqle;
                }
                System.out.println("Handles successfully updated in database.\n");
                System.out.println("Re-creating browse and search indexes...");
                try {
                    // Reinitialise the search and browse system
                    ScriptLauncher.main(new String[] { "index-discovery", "-b" });
                    System.out.println("Browse and search indexes are ready now.");
                    // All done
                    System.out.println("\nAll done successfully. Please check the DSpace logs!\n");
                } catch (Exception e) {
                    // Not a lot we can do
                    System.out.println("Error during re-indexing.");
                    System.out.println("\n\nAutomatic re-indexing failed. Please perform it manually.\n\n" + "  [dspace]/bin/dspace index-discovery -b\n\n" + "When launching this command, your servlet container must be running.\n");
                    throw e;
                }
                context.restoreAuthSystemState();
            } else {
                System.out.println("No changes have been made to your data.\n");
            }
        } else {
            System.out.println("Nothing to do! All handles are up-to-date.\n");
        }
    }
}
Also used : Context(org.dspace.core.Context) MetadataValue(org.dspace.content.MetadataValue) InputStreamReader(java.io.InputStreamReader) SQLException(java.sql.SQLException) BufferedReader(java.io.BufferedReader) MetadataValueService(org.dspace.content.service.MetadataValueService) HandleService(org.dspace.handle.service.HandleService) SQLException(java.sql.SQLException)

Example 3 with HandleService

use of org.dspace.handle.service.HandleService in project DSpace by DSpace.

the class ITDSpaceAIP method tearDownClass.

/**
 * This method will be run once at the very end
 */
@AfterClass
public static void tearDownClass() {
    try {
        Context context = new Context();
        CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
        HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
        Community topCommunity = (Community) handleService.resolveToObject(context, topCommunityHandle);
        // Delete top level test community and test hierarchy under it
        if (topCommunity != null) {
            log.info("tearDownClass() - DESTROY TEST HIERARCHY");
            context.turnOffAuthorisationSystem();
            communityService.delete(context, topCommunity);
            context.restoreAuthSystemState();
            context.commit();
        }
        // Delete the Eperson created to submit test items
        EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
        EPerson eperson = ePersonService.findByEmail(context, submitterEmail);
        if (eperson != null) {
            log.info("tearDownClass() - DESTROY TEST EPERSON");
            context.turnOffAuthorisationSystem();
            ePersonService.delete(context, eperson);
            context.restoreAuthSystemState();
            context.commit();
        }
        if (context.isValid()) {
            context.abort();
        }
    } catch (Exception ex) {
        log.error("Error in tearDownClass()", ex);
    }
}
Also used : Context(org.dspace.core.Context) EPersonService(org.dspace.eperson.service.EPersonService) CommunityService(org.dspace.content.service.CommunityService) EPerson(org.dspace.eperson.EPerson) HandleService(org.dspace.handle.service.HandleService) Community(org.dspace.content.Community) SQLException(java.sql.SQLException) WorkflowException(org.dspace.workflow.WorkflowException) AuthorizeException(org.dspace.authorize.AuthorizeException) CrosswalkException(org.dspace.content.crosswalk.CrosswalkException) IOException(java.io.IOException) AfterClass(org.junit.AfterClass)

Example 4 with HandleService

use of org.dspace.handle.service.HandleService in project DSpace by DSpace.

the class TestLogicRunner method main.

/**
 * Main runner method for CLI usage
 * @param argv  array of command-line arguments
 */
public static void main(String[] argv) {
    System.out.println("Starting impl of main() test spring logic item filter");
    // initialize options
    Options options = new Options();
    options.addOption("h", "help", false, "Help");
    options.addOption("l", "list", false, "List filters");
    options.addOption("f", "filter", true, "Use filter <filter>");
    options.addOption("i", "item", true, "Run filter over item <handle>");
    options.addOption("a", "all", false, "Run filter over all items");
    // initialize parser
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    HelpFormatter helpformater = new HelpFormatter();
    try {
        line = parser.parse(options, argv);
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
    }
    if (line.hasOption("help")) {
        helpformater.printHelp("\nTest the DSpace logical item filters\n", options);
        System.exit(0);
    }
    // Create a context
    Context c = new Context(Context.Mode.READ_ONLY);
    // c.turnOffAuthorisationSystem();
    ServiceManager manager = DSpaceServicesFactory.getInstance().getServiceManager();
    if (line.hasOption("list")) {
        // Lit filters and exit
        List<Filter> filters = manager.getServicesByType(Filter.class);
        for (Filter filter : filters) {
            System.out.println(filter.getClass().toString());
        }
        System.out.println("See item-filters.xml spring config for filter names");
        System.exit(0);
    }
    Filter filter;
    if (line.hasOption("filter")) {
        String filterName = line.getOptionValue("filter");
        filter = manager.getServiceByName(filterName, Filter.class);
        if (filter == null) {
            System.out.println("Error loading filter: " + filterName);
            System.exit(1);
        }
        if (line.hasOption("item")) {
            String handle = line.getOptionValue("item");
            HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
            try {
                DSpaceObject dso = handleService.resolveToObject(c, handle);
                if (Constants.typeText[dso.getType()].equals("ITEM")) {
                    Item item = (Item) dso;
                    System.out.println(filter.getResult(c, item));
                } else {
                    System.out.println(handle + " is not an ITEM");
                }
            } catch (SQLException | LogicalStatementException e) {
                System.out.println("Error encountered processing item " + handle + ": " + e.getMessage());
            }
        } else if (line.hasOption("all")) {
            ItemService itemService = ContentServiceFactory.getInstance().getItemService();
            try {
                Iterator<Item> itemIterator = itemService.findAll(c);
                while (itemIterator.hasNext()) {
                    Item i = itemIterator.next();
                    System.out.println("Testing '" + filter + "' on item " + i.getHandle() + " ('" + i.getName() + "')");
                    System.out.println(filter.getResult(c, i));
                }
            } catch (SQLException | LogicalStatementException e) {
                System.out.println("Error encountered processing items: " + e.getMessage());
            }
        } else {
            helpformater.printHelp("\nTest the DSpace logical item filters\n", options);
        }
    }
}
Also used : Context(org.dspace.core.Context) Options(org.apache.commons.cli.Options) SQLException(java.sql.SQLException) PosixParser(org.apache.commons.cli.PosixParser) HelpFormatter(org.apache.commons.cli.HelpFormatter) Item(org.dspace.content.Item) CommandLine(org.apache.commons.cli.CommandLine) DSpaceObject(org.dspace.content.DSpaceObject) ServiceManager(org.dspace.kernel.ServiceManager) ItemService(org.dspace.content.service.ItemService) Iterator(java.util.Iterator) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) HandleService(org.dspace.handle.service.HandleService)

Example 5 with HandleService

use of org.dspace.handle.service.HandleService in project DSpace by DSpace.

the class V7_0_2020_10_31__CollectionCommunity_Metadata_Handle method migrate.

@Override
public void migrate(Context context) throws Exception {
    HandleService handleService = DSpaceServicesFactory.getInstance().getServiceManager().getServicesByType(HandleService.class).get(0);
    String dbtype = DatabaseUtils.getDbType(context.getConnection());
    String sqlMigrationPath = "org/dspace/storage/rdbms/sqlmigration/metadata/" + dbtype + "/";
    String dataMigrateSQL = MigrationUtils.getResourceAsString(sqlMigrationPath + "V7.0_2020.10.31__CollectionCommunity_Metadata_Handle.sql");
    // Replace ${handle.canonical.prefix} variable in SQL script with value from Configuration
    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("handle.canonical.prefix", handleService.getCanonicalPrefix());
    StringSubstitutor sub = new StringSubstitutor(valuesMap);
    dataMigrateSQL = sub.replace(dataMigrateSQL);
    DatabaseUtils.executeSql(context.getConnection(), dataMigrateSQL);
    migration_file_size = dataMigrateSQL.length();
}
Also used : HashMap(java.util.HashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor) HandleService(org.dspace.handle.service.HandleService)

Aggregations

HandleService (org.dspace.handle.service.HandleService)7 SQLException (java.sql.SQLException)6 Context (org.dspace.core.Context)5 DSpaceObject (org.dspace.content.DSpaceObject)3 File (java.io.File)2 AuthorizeException (org.dspace.authorize.AuthorizeException)2 Community (org.dspace.content.Community)2 Item (org.dspace.content.Item)2 CommunityService (org.dspace.content.service.CommunityService)2 AfterClass (org.junit.AfterClass)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 CommandLine (org.apache.commons.cli.CommandLine)1 CommandLineParser (org.apache.commons.cli.CommandLineParser)1 HelpFormatter (org.apache.commons.cli.HelpFormatter)1 Options (org.apache.commons.cli.Options)1 ParseException (org.apache.commons.cli.ParseException)1