/** * Authenticate the given service document request. This extracts the appropriate information from * the request and forwards to the appropriate authentication method * * @param auth * @return * @throws DSpaceSwordException * @throws SwordError * @throws SwordAuthException */ public SwordContext authenticate(AuthCredentials auth) throws DSpaceSwordException, SwordError, SwordAuthException { Context context = this.constructContext(); SwordContext sc = null; try { sc = this.authenticate(context, auth); } catch (DSpaceSwordException e) { if (context != null && context.isValid()) { context.abort(); } throw e; } catch (SwordError e) { if (context != null && context.isValid()) { context.abort(); } throw e; } catch (SwordAuthException e) { if (context != null && context.isValid()) { context.abort(); } throw e; } catch (RuntimeException e) { if (context != null && context.isValid()) { context.abort(); } throw e; } return sc; }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // we expect a path in the form /resource/<prefix>/<suffix>. String pathInfo = request.getPathInfo(); log.debug("Pathinfo: " + pathInfo); if (StringUtils.isEmpty(pathInfo) || StringUtils.countMatches(pathInfo, "/") < 2) { log.debug("Path does not contain the expected number of slashes."); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // remove trailing slash of the path info and split it. String[] path = request.getPathInfo().substring(1).split("/"); String handle = path[0] + "/" + path[1]; String dspaceURL = (new DSpace()).getConfigurationService().getProperty("dspace.url"); // Prepare content negotiation int requestedMimeType = Negotiator.negotiate(request.getHeader(ACCEPT_HEADER_NAME)); Context context = null; DSpaceObject dso = null; try { context = new Context(Context.READ_ONLY); dso = handleService.resolveToObject(context, handle); } catch (SQLException ex) { log.error("SQLException: " + ex.getMessage(), ex); context.abort(); // probably a problem with the db connection => send Service Unavailable response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } catch (IllegalStateException ex) { log.error( "Cannot resolve handle " + handle + ". IllegalStateException:" + ex.getMessage(), ex); context.abort(); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (dso == null) { log.info("Cannot resolve handle '" + handle + "' to dso. => 404"); context.abort(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // close the context and send forward. context.abort(); Negotiator.sendRedirect(response, handle, "", requestedMimeType, true); }
/** * Method to check current status of the service and logged in user. * * <p>okay: true | false authenticated: true | false epersonEMAIL: [email protected] epersonNAME: * John Doe * * @param headers Request header which contains the header named "rest-dspace-token" containing * the token as value. * @return status the Status object with information about REST API * @throws UnsupportedEncodingException The Character Encoding is not supported. */ @GET @Path("/status") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Status status(@Context HttpHeaders headers) throws UnsupportedEncodingException { org.dspace.core.Context context = null; try { context = Resource.createContext(); EPerson ePerson = context.getCurrentUser(); if (ePerson != null) { // DB EPerson needed since token won't have full info, need context EPerson dbEPerson = epersonService.findByEmail(context, ePerson.getEmail()); Status status = new Status(dbEPerson.getEmail(), dbEPerson.getFullName()); return status; } } catch (ContextException e) { Resource.processException("Status context error: " + e.getMessage(), context); } catch (SQLException e) { Resource.processException("Status eperson db lookup error: " + e.getMessage(), context); } finally { context.abort(); } // fallback status, unauth return new Status(); }
/** * Delete the specified handle. It is assumed that the user has already confirmed this selection. * * @param context The current DSpace context. * @param handleID ID of handle to be removed. * @return A results object. */ public static FlowResult processDeleteHandle(Context context, int handleID) throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_handle_deletion_failed); try { Handle handleDeleted = Handle.find(context, handleID); HandleManager.changeHandle(context, handleDeleted.getHandle(), null, false); handleDeleted.delete(); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_handle_successfully_deleted); } catch (Exception e) { log.error(e.getMessage()); context.abort(); } return result; }
@GET @Path("/login-shibboleth") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response shibbolethLoginEndPoint() { org.dspace.core.Context context = null; try { context = Resource.createContext(); AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); Iterator<AuthenticationMethod> authenticationMethodIterator = authenticationService.authenticationMethodIterator(); while (authenticationMethodIterator.hasNext()) { AuthenticationMethod authenticationMethod = authenticationMethodIterator.next(); if (authenticationMethod instanceof ShibAuthentication) { // TODO: Perhaps look for a better way of handling this ? org.dspace.services.model.Request currentRequest = new DSpace().getRequestService().getCurrentRequest(); String loginPageURL = authenticationMethod.loginPageURL( context, currentRequest.getHttpServletRequest(), currentRequest.getHttpServletResponse()); if (StringUtils.isNotBlank(loginPageURL)) { currentRequest.getHttpServletResponse().sendRedirect(loginPageURL); } } } context.abort(); } catch (ContextException | SQLException | IOException e) { Resource.processException("Shibboleth endpoint error: " + e.getMessage(), context); } finally { if (context != null && context.isValid()) { context.abort(); } } return Response.ok().build(); }
/** * Find collection from DSpace database. It is encapsulation of method * org.dspace.content.Collection.find with checking if item exist and if user logged into context * has permission to do passed action. * * @param context Context of actual logged user. * @param id Id of collection in DSpace. * @param action Constant from org.dspace.core.Constants. * @return It returns DSpace collection. * @throws WebApplicationException Is thrown when item with passed id is not exists and if user * has no permission to do passed action. */ private org.dspace.content.Collection findCollection( org.dspace.core.Context context, int id, int action) throws WebApplicationException { org.dspace.content.Collection collection = null; try { collection = org.dspace.content.Collection.find(context, id); if (collection == null) { context.abort(); log.warn("Collection(id=" + id + ") was not found!"); throw new WebApplicationException(Response.Status.NOT_FOUND); } else if (!AuthorizeManager.authorizeActionBoolean(context, collection, action)) { context.abort(); if (context.getCurrentUser() != null) { log.error( "User(" + context.getCurrentUser().getEmail() + ") has not permission to " + getActionString(action) + " collection!"); } else { log.error( "User(anonymous) has not permission to " + getActionString(action) + " collection!"); } throw new WebApplicationException(Response.Status.UNAUTHORIZED); } } catch (SQLException e) { processException( "Something get wrong while finding collection(id=" + id + "). SQLException, Message: " + e, context); } return collection; }
public static void main(String[] args) { // get a context from an anonymous user. // don't switch off authorization system! We'll export the converted // data into a triple store that provides a public sparql endpoint. // all exported rdf data can be read by anonymous users. // We won't change the database => read_only context will assure this. Context context = new Context(Context.READ_ONLY); RDFizer myself = null; myself = new RDFizer(); myself.overrideContext(context); myself.runCLI(args); // we don't change anything in the database, so abort the context. context.abort(); }
/** * Save a registry to a filepath * * @param file filepath * @param schema schema definition to save * @throws SQLException if database error * @throws IOException if IO error * @throws SAXException if XML error * @throws RegistryExportException if export error */ public static void saveRegistry(String file, String schema) throws SQLException, IOException, SAXException, RegistryExportException { // create a context Context context = new Context(); context.setIgnoreAuthorization(true); OutputFormat xmlFormat = new OutputFormat(Method.XML, "UTF-8", true); xmlFormat.setLineWidth(120); xmlFormat.setIndent(4); XMLSerializer xmlSerializer = new XMLSerializer(new BufferedWriter(new FileWriter(file)), xmlFormat); // XMLSerializer xmlSerializer = new XMLSerializer(System.out, xmlFormat); xmlSerializer.startDocument(); xmlSerializer.startElement("dspace-dc-types", null); // Save the schema definition(s) saveSchema(context, xmlSerializer, schema); List<MetadataField> mdFields = null; // If a single schema has been specified if (schema != null && !"".equals(schema)) { // Get the id of that schema MetadataSchema mdSchema = metadataSchemaService.find(context, schema); if (mdSchema == null) { throw new RegistryExportException("no schema to export"); } // Get the metadata fields only for the specified schema mdFields = metadataFieldService.findAllInSchema(context, mdSchema); } else { // Get the metadata fields for all the schemas mdFields = metadataFieldService.findAll(context); } // Output the metadata fields for (MetadataField mdField : mdFields) { saveType(context, xmlSerializer, mdField); } xmlSerializer.endElement("dspace-dc-types"); xmlSerializer.endDocument(); // abort the context, as we shouldn't have changed it!! context.abort(); }
/** Return the list of running applications. */ public static List<AbstractDSpaceWebapp> getApps() { ArrayList<AbstractDSpaceWebapp> apps = new ArrayList<AbstractDSpaceWebapp>(); TableRowIterator tri; Context context = null; HttpMethod request = null; try { context = new Context(); tri = DatabaseManager.queryTable(context, "Webapp", "SELECT * FROM Webapp"); for (TableRow row : tri.toList()) { DSpaceWebapp app = new DSpaceWebapp(); app.kind = row.getStringColumn("AppName"); app.url = row.getStringColumn("URL"); app.started = row.getDateColumn("Started"); app.uiQ = row.getBooleanColumn("isUI"); HttpClient client = new HttpClient(); request = new HeadMethod(app.url); int status = client.executeMethod(request); request.getResponseBody(); if (status != HttpStatus.SC_OK) { DatabaseManager.delete(context, row); context.commit(); continue; } apps.add(app); } } catch (SQLException e) { log.error("Unable to list running applications", e); } catch (HttpException e) { log.error("Failure checking for a running webapp", e); } catch (IOException e) { log.error("Failure checking for a running webapp", e); } finally { if (null != request) { request.releaseConnection(); } if (null != context) { context.abort(); } } return apps; }
/** * Change handle prefix. It is assumed that the user has already confirmed this selection. * * @param context The current DSpace context. * @param oldPrefix The prefix to be replace. * @param newPrefix The prefix to be used. * @param archiveOldHandles Should the former handles be archived? * @return A results object. */ public static FlowResult changeHandlePrefix( Context context, String oldPrefix, String newPrefix, boolean archiveOldHandles) throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); result.setContinue(false); result.setOutcome(false); // If we have errors, the form needs to be resubmitted to fix those problems if (StringUtils.isEmpty(oldPrefix)) { result.addError("old_prefix_empty"); } if (StringUtils.isEmpty(newPrefix)) { result.addError("new_prefix_empty"); } if (result.getErrors() == null && oldPrefix.equals(newPrefix)) { result.addError("old_prefix_equals_new_prefix"); } if (result.getErrors() == null) { try { // change prefixes HandleManager.changePrefix(context, oldPrefix, newPrefix, archiveOldHandles); context.commit(); // reindex IndexBrowse.main(new String[] {"-i"}); result.setContinue(true); result.setOutcome(true); result.setMessage(T_prefix_successfully_changed); } catch (Exception e) { result.setMessage(T_prefix_change_failed); log.error(e.getMessage()); context.abort(); } } return result; }
/** @param argv */ public static void main(String[] argv) { // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); // processing basis for determining items // item-specific changes with metadata in source directory with dublin_core.xml files options.addOption("s", "source", true, "root directory of source dspace archive "); // actions on items options.addOption( "a", "addmetadata", true, "add metadata specified for each item; multiples separated by semicolon ';'"); options.addOption("d", "deletemetadata", true, "delete metadata specified for each item"); options.addOption("A", "addbitstreams", false, "add bitstreams as specified for each item"); // extra work to get optional argument Option delBitstreamOption = new Option("D", "deletebitstreams", true, "delete bitstreams as specified for each item"); delBitstreamOption.setOptionalArg(true); delBitstreamOption.setArgName("BitstreamFilter"); options.addOption(delBitstreamOption); // other params options.addOption("e", "eperson", true, "email of eperson doing the update"); options.addOption( "i", "itemfield", true, "optional metadata field that containing item identifier; default is dc.identifier.uri"); options.addOption( "F", "filter-properties", true, "filter class name; only for deleting bitstream"); options.addOption("v", "verbose", false, "verbose logging"); // special run states options.addOption("t", "test", false, "test run - do not actually import items"); options.addOption( "P", "provenance", false, "suppress altering provenance field for bitstream changes"); options.addOption("h", "help", false, "help"); int status = 0; boolean isTest = false; boolean alterProvenance = true; String itemField = null; String metadataIndexName = null; Context context = null; ItemUpdate iu = new ItemUpdate(); try { CommandLine line = parser.parse(options, argv); if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("ItemUpdate", options); pr(""); pr("Examples:"); pr( " adding metadata: ItemUpdate -e [email protected] -s sourcedir -a dc.contributor -a dc.subject "); pr( " deleting metadata: ItemUpdate -e [email protected] -s sourcedir -d dc.description.other"); pr(" adding bitstreams: ItemUpdate -e [email protected] -s sourcedir -A -i dc.identifier"); pr(" deleting bitstreams: ItemUpdate -e [email protected] -s sourcedir -D ORIGINAL "); pr(""); System.exit(0); } if (line.hasOption('v')) { verbose = true; } if (line.hasOption('P')) { alterProvenance = false; pr("Suppressing changes to Provenance field option"); } iu.eperson = line.getOptionValue('e'); // db ID or email if (!line.hasOption('s')) // item specific changes from archive dir { pr("Missing source archive option"); System.exit(1); } String sourcedir = line.getOptionValue('s'); if (line.hasOption('t')) // test { isTest = true; pr("**Test Run** - not actually updating items."); } if (line.hasOption('i')) { itemField = line.getOptionValue('i'); } if (line.hasOption('d')) { String[] targetFields = line.getOptionValues('d'); DeleteMetadataAction delMetadataAction = (DeleteMetadataAction) iu.actionMgr.getUpdateAction(DeleteMetadataAction.class); delMetadataAction.addTargetFields(targetFields); // undo is an add for (String field : targetFields) { iu.undoActionList.add(" -a " + field + " "); } pr("Delete metadata for fields: "); for (String s : targetFields) { pr(" " + s); } } if (line.hasOption('a')) { String[] targetFields = line.getOptionValues('a'); AddMetadataAction addMetadataAction = (AddMetadataAction) iu.actionMgr.getUpdateAction(AddMetadataAction.class); addMetadataAction.addTargetFields(targetFields); // undo is a delete followed by an add of a replace record for target fields for (String field : targetFields) { iu.undoActionList.add(" -d " + field + " "); } for (String field : targetFields) { iu.undoActionList.add(" -a " + field + " "); } pr("Add metadata for fields: "); for (String s : targetFields) { pr(" " + s); } } if (line.hasOption('D')) // undo not supported { pr("Delete bitstreams "); String[] filterNames = line.getOptionValues('D'); if ((filterNames != null) && (filterNames.length > 1)) { pr("Error: Only one filter can be a used at a time."); System.exit(1); } String filterName = line.getOptionValue('D'); pr("Filter argument: " + filterName); if (filterName == null) // indicates using delete_contents files { DeleteBitstreamsAction delAction = (DeleteBitstreamsAction) iu.actionMgr.getUpdateAction(DeleteBitstreamsAction.class); delAction.setAlterProvenance(alterProvenance); } else { // check if param is on ALIAS list String filterClassname = filterAliases.get(filterName); if (filterClassname == null) { filterClassname = filterName; } BitstreamFilter filter = null; try { Class<?> cfilter = Class.forName(filterClassname); pr("BitstreamFilter class to instantiate: " + cfilter.toString()); filter = (BitstreamFilter) cfilter.newInstance(); // unfortunate cast, an erasure consequence } catch (Exception e) { pr("Error: Failure instantiating bitstream filter class: " + filterClassname); System.exit(1); } String filterPropertiesName = line.getOptionValue('F'); if (filterPropertiesName != null) // not always required { try { // TODO try multiple relative locations, e.g. source dir if (!filterPropertiesName.startsWith("/")) { filterPropertiesName = sourcedir + File.separator + filterPropertiesName; } filter.initProperties(filterPropertiesName); } catch (Exception e) { pr( "Error: Failure finding properties file for bitstream filter class: " + filterPropertiesName); System.exit(1); } } DeleteBitstreamsByFilterAction delAction = (DeleteBitstreamsByFilterAction) iu.actionMgr.getUpdateAction(DeleteBitstreamsByFilterAction.class); delAction.setAlterProvenance(alterProvenance); delAction.setBitstreamFilter(filter); // undo not supported } } if (line.hasOption('A')) { pr("Add bitstreams "); AddBitstreamsAction addAction = (AddBitstreamsAction) iu.actionMgr.getUpdateAction(AddBitstreamsAction.class); addAction.setAlterProvenance(alterProvenance); iu.undoActionList.add(" -D "); // delete_contents file will be written, no arg required } if (!iu.actionMgr.hasActions()) { pr("Error - an action must be specified"); System.exit(1); } else { pr("Actions to be performed: "); for (UpdateAction ua : iu.actionMgr) { pr(" " + ua.getClass().getName()); } } pr("ItemUpdate - initializing run on " + (new Date()).toString()); context = new Context(); iu.setEPerson(context, iu.eperson); context.setIgnoreAuthorization(true); HANDLE_PREFIX = ConfigurationManager.getProperty("handle.canonical.prefix"); if (HANDLE_PREFIX == null || HANDLE_PREFIX.length() == 0) { HANDLE_PREFIX = "http://hdl.handle.net/"; } iu.processArchive(context, sourcedir, itemField, metadataIndexName, alterProvenance, isTest); context.complete(); // complete all transactions context.setIgnoreAuthorization(false); } catch (Exception e) { if (context != null && context.isValid()) { context.abort(); context.setIgnoreAuthorization(false); } e.printStackTrace(); pr(e.toString()); status = 1; } if (isTest) { pr("***End of Test Run***"); } else { pr("End."); } System.exit(status); }
public static void main(String[] argv) throws Exception { Options options = new Options(); options.addOption("c", "collection", true, "destination collection(s) Handle (repeatable)"); options.addOption("e", "eperson", true, "email address of eperson doing importing"); options.addOption( "w", "install", false, "disable workflow; install immediately without going through collection's workflow"); options.addOption("t", "type", true, "package type or MIMEtype"); options.addOption( "o", "option", true, "Packager option to pass to plugin, \"name=value\" (repeatable)"); options.addOption( "d", "disseminate", false, "Disseminate package (output); default is to submit."); options.addOption("i", "item", true, "Handle of item to disseminate."); options.addOption("h", "help", false, "help"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, argv); String sourceFile = null; String eperson = null; String[] collections = null; boolean useWorkflow = true; String packageType = null; boolean submit = true; String itemHandle = null; PackageParameters pkgParams = new PackageParameters(); if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("Packager [options] package-file|-\n", options); System.out.println("\nAvailable Submission Package (SIP) types:"); String pn[] = PluginManager.getAllPluginNames(PackageIngester.class); for (int i = 0; i < pn.length; ++i) System.out.println(" " + pn[i]); System.out.println("\nAvailable Dissemination Package (DIP) types:"); pn = PluginManager.getAllPluginNames(PackageDisseminator.class); for (int i = 0; i < pn.length; ++i) System.out.println(" " + pn[i]); System.exit(0); } if (line.hasOption('w')) useWorkflow = false; if (line.hasOption('e')) eperson = line.getOptionValue('e'); if (line.hasOption('c')) collections = line.getOptionValues('c'); if (line.hasOption('t')) packageType = line.getOptionValue('t'); if (line.hasOption('i')) itemHandle = line.getOptionValue('i'); String files[] = line.getArgs(); if (files.length > 0) sourceFile = files[0]; if (line.hasOption('d')) submit = false; if (line.hasOption('o')) { String popt[] = line.getOptionValues('o'); for (int i = 0; i < popt.length; ++i) { String pair[] = popt[i].split("\\=", 2); if (pair.length == 2) pkgParams.addProperty(pair[0].trim(), pair[1].trim()); else if (pair.length == 1) pkgParams.addProperty(pair[0].trim(), ""); else System.err.println("Warning: Illegal package option format: \"" + popt[i] + "\""); } } // Sanity checks on arg list: required args if (sourceFile == null || eperson == null || packageType == null || (submit && collections == null)) { System.err.println("Error - missing a REQUIRED argument or option.\n"); HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("PackageManager [options] package-file|-\n", options); System.exit(0); } // find the EPerson, assign to context Context context = new Context(); EPerson myEPerson = null; myEPerson = EPerson.findByEmail(context, eperson); if (myEPerson == null) usageError("Error, eperson cannot be found: " + eperson); context.setCurrentUser(myEPerson); if (submit) { // make sure we have an input file // GWaller 11/1/10 Disable piping of input in - we need to archive the package so it is // simpler to assume a file stream // rather than save the System.in bytes and re-read. if (sourceFile.equals("-")) { usageError( "Error, input piping not allowed. Specify a file name of a physical file to read"); } InputStream source = new FileInputStream(sourceFile); PackageIngester sip = (PackageIngester) PluginManager.getNamedPlugin(PackageIngester.class, packageType); if (sip == null) usageError("Error, Unknown package type: " + packageType); // find collections Collection[] mycollections = null; System.out.println("Destination collections:"); // validate each collection arg to see if it's a real collection mycollections = new Collection[collections.length]; for (int i = 0; i < collections.length; i++) { // sanity check: did handle resolve, and to a collection? DSpaceObject dso = HandleManager.resolveToObject(context, collections[i]); if (dso == null) throw new IllegalArgumentException( "Bad collection list -- " + "Cannot resolve collection handle \"" + collections[i] + "\""); else if (dso.getType() != Constants.COLLECTION) throw new IllegalArgumentException( "Bad collection list -- " + "Object at handle \"" + collections[i] + "\" is not a collection!"); mycollections[i] = (Collection) dso; System.out.println( (i == 0 ? " Owning " : " ") + " Collection: " + mycollections[i].getMetadata("name")); } try { // GWaller 26/08/09 Support array of collections WorkspaceItem wi = sip.ingest(context, mycollections, source, pkgParams, null); // GWaller 11/1/10 IssueID #157 Archive the package InputStream sourceCopy = new FileInputStream(sourceFile); Bundle archivedBundle = BundleUtils.getBundleByName(wi.getItem(), Constants.ARCHIVED_CONTENT_PACKAGE_BUNDLE); Bitstream bs = archivedBundle.createBitstream(sourceCopy); bs.setName(new File(sourceFile).getName()); bs.update(); archivedBundle.update(); if (useWorkflow) { String handle = null; // Check if workflow completes immediately, and // return Handle if so. WorkflowItem wfi = WorkflowManager.startWithoutNotify(context, wi); if (wfi.getState() == WorkflowManager.WFSTATE_ARCHIVE) { Item ni = wfi.getItem(); handle = HandleManager.findHandle(context, ni); } if (handle == null) System.out.println("Created Workflow item, ID=" + String.valueOf(wfi.getID())); else System.out.println("Created and installed item, handle=" + handle); } else { InstallItem.installItem(context, wi); System.out.println( "Created and installed item, handle=" + HandleManager.findHandle(context, wi.getItem())); } context.complete(); System.exit(0); } catch (Exception e) { // abort all operations context.abort(); e.printStackTrace(); System.out.println(e); System.exit(1); } } else { OutputStream dest = (sourceFile.equals("-")) ? (OutputStream) System.out : (OutputStream) (new FileOutputStream(sourceFile)); PackageDisseminator dip = (PackageDisseminator) PluginManager.getNamedPlugin(PackageDisseminator.class, packageType); if (dip == null) usageError("Error, Unknown package type: " + packageType); DSpaceObject dso = HandleManager.resolveToObject(context, itemHandle); if (dso == null) throw new IllegalArgumentException( "Bad Item handle -- " + "Cannot resolve handle \"" + itemHandle); dip.disseminate(context, dso, pkgParams, dest); } }
/** * Save the handle. * * <p>If the handleID is -1 then a new handle is created. * * @param context The current dspace context * @param handleID The handle ID, or -1 for a new handle. * @param url The handle URL * @param resourceTypeID The type of referenced resource * @param resourceID ID of referenced resource * @return A result */ public static FlowResult processSaveHandle( Context context, int handleID, String handle, String url, int resourceTypeID, int resourceID, boolean archiveOldHandle) throws SQLException, AuthorizeException, UIException { FlowResult result = new FlowResult(); result.setParameter("handle_id", handleID); result.setContinue(false); result.setOutcome(false); // If we have errors, the form needs to be resubmitted to fix those problems if (StringUtils.isEmpty(handle)) { result.addError("handle_empty"); } if (resourceTypeID == -1 && resourceID == -1 && StringUtils.isEmpty(url)) { result.addError("url_empty"); } else if (StringUtils.isEmpty(url)) { if (resourceTypeID == -1) { result.addError("resource_type_id_empty"); } if (resourceID == -1) { result.addError("resource_id_empty"); } } if (result.getErrors() == null) { try { Handle h = null; if (handleID == -1) { h = Handle.create(context, null, handle); } else { h = Handle.find(context, handleID); if (h.getHandle() != handle) { HandleManager.changeHandle(context, h.getHandle(), handle, archiveOldHandle); } } h.setHandle(handle); h.setURL(url); h.setResourceTypeID(resourceTypeID); h.setResourceID(resourceID); h.update(); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_handle_successfully_saved); } catch (Exception e) { result.setMessage(T_handle_saving_failed); log.error(e.getMessage()); context.abort(); } } return result; }
/** * Delete item in collection. * * @param collectionId Id of collection which will be deleted. * @param itemId Id of item in colletion. * @return It returns status code: OK(200). NOT_FOUND(404) if item or collection was not found, * UNAUTHORIZED(401) if user is not allowed to delete item or permission to write into * collection. * @throws WebApplicationException It can be thrown by: SQLException, when was problem with * database reading or writting. AuthorizeException, when was problem with authorization to * item or collection. IOException, when was problem with removing item. ContextException, * when was problem with creating context of DSpace. */ @DELETE @Path("/{collection_id}/items/{item_id}") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response deleteCollectionItem( @PathParam("collection_id") Integer collectionId, @PathParam("item_id") Integer itemId, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { log.info("Delete item(id=" + itemId + ") in collection(id=" + collectionId + ")."); org.dspace.core.Context context = null; try { context = createContext(getUser(headers)); org.dspace.content.Collection dspaceCollection = findCollection(context, collectionId, org.dspace.core.Constants.WRITE); org.dspace.content.Item item = null; org.dspace.content.ItemIterator dspaceItems = dspaceCollection.getItems(); while (dspaceItems.hasNext()) { org.dspace.content.Item dspaceItem = dspaceItems.next(); if (dspaceItem.getID() == itemId) { item = dspaceItem; } } if (item == null) { context.abort(); log.warn("Item(id=" + itemId + ") was not found!"); throw new WebApplicationException(Response.Status.NOT_FOUND); } else if (!AuthorizeManager.authorizeActionBoolean( context, item, org.dspace.core.Constants.REMOVE)) { context.abort(); if (context.getCurrentUser() != null) { log.error( "User(" + context.getCurrentUser().getEmail() + ") has not permission to delete item!"); } else { log.error("User(anonymous) has not permission to delete item!"); } throw new WebApplicationException(Response.Status.UNAUTHORIZED); } writeStats( dspaceCollection, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwarderfor, headers, request, context); writeStats( item, UsageEvent.Action.REMOVE, user_ip, user_agent, xforwarderfor, headers, request, context); dspaceCollection.removeItem(item); context.complete(); } catch (ContextException e) { processException( "Could not delete item(id=" + itemId + ") in collection(id=" + collectionId + "), ContextException. Message: " + e.getMessage(), context); } catch (SQLException e) { processException( "Could not delete item(id=" + itemId + ") in collection(id=" + collectionId + "), SQLException. Message: " + e, context); } catch (AuthorizeException e) { processException( "Could not delete item(id=" + itemId + ") in collection(id=" + collectionId + "), AuthorizeException. Message: " + e, context); } catch (IOException e) { processException( "Could not delete item(id=" + itemId + ") in collection(id=" + collectionId + "), IOException. Message: " + e, context); } finally { processFinally(context); } log.info( "Item(id=" + itemId + ") in collection(id=" + collectionId + ") was successfully deleted."); return Response.ok().build(); }
/** * Method for invoking subscriptions via the command line * * @param argv command-line arguments, none used yet */ public static void main(String[] argv) { log.info("#### START DELETE: -----" + new Date() + " ----- ####"); String usage = "it.cilea.hku.authority.ScriptRPSubscribe [-t] or nothing to send out subscriptions."; Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); CommandLine line = null; { Option opt = new Option("t", "test", false, "Run test session"); opt.setRequired(false); options.addOption(opt); } { Option opt = new Option("h", "help", false, "Print this help message"); opt.setRequired(false); options.addOption(opt); } try { line = new PosixParser().parse(options, argv); } catch (Exception e) { // automatically generate the help statement formatter.printHelp(usage, e.getMessage(), options, ""); System.exit(1); } if (line.hasOption("h")) { // automatically generate the help statement formatter.printHelp(usage, options); System.exit(1); } boolean test = line.hasOption("t"); if (test) log.setLevel(Level.DEBUG); Context context = null; try { context = new Context(); Researcher researcher = new Researcher(); ApplicationService applicationService = researcher.getApplicationService(); List<CrisComponentsService> serviceComponent = researcher.getAllCrisComponents(); for (CrisComponentsService service : serviceComponent) { for (ICRISComponent component : service.getComponents().values()) { RelationConfiguration relationConfiguration = component.getRelationConfiguration(); if (Item.class.isAssignableFrom(relationConfiguration.getRelationClass())) { Integer key = CrisConstants.getEntityType(component.getTarget()); String query = relationConfiguration.getQuery(); if (!mapRelationFields.containsKey(key)) { List<String> rels = new LinkedList<String>(); rels.add(query); mapRelationFields.put(key, rels); } else { mapRelationFields.get(key).add(query); } } } } processDaily(researcher, applicationService, context, test); } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (context != null && context.isValid()) { // Nothing is actually written context.abort(); } } log.info("#### END: -----" + new Date() + " ----- ####"); System.exit(0); }
public static void main(String[] argv) throws Exception { // set headless for non-gui workstations System.setProperty("java.awt.headless", "true"); // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption( "v", "verbose", false, "print all extracted text and other details to STDOUT"); options.addOption("f", "force", false, "force all bitstreams to be processed"); options.addOption( "n", "noindex", false, "do NOT update the search index after filtering bitstreams"); options.addOption("i", "identifier", true, "ONLY process bitstreams belonging to identifier"); options.addOption("m", "maximum", true, "process no more than maximum items"); options.addOption("h", "help", false, "help"); CommandLine line = parser.parse(options, argv); if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("MediaFilter\n", options); System.exit(0); } if (line.hasOption('v')) { isVerbose = true; } if (line.hasOption('n')) { updateIndex = false; } if (line.hasOption('f')) { isForce = true; } if (line.hasOption('i')) { identifier = line.getOptionValue('i'); } if (line.hasOption('m')) { max2Process = Integer.parseInt(line.getOptionValue('m')); if (max2Process <= 1) { System.out.println("Invalid maximum value '" + line.getOptionValue('m') + "' - ignoring"); max2Process = Integer.MAX_VALUE; } } // set up filters filterClasses = (MediaFilter[]) PluginManager.getPluginSequence(MediaFilter.class); for (int i = 0; i < filterClasses.length; i++) { String filterName = filterClasses[i].getClass().getName(); String formats = ConfigurationManager.getProperty("filter." + filterName + ".inputFormats"); if (formats != null) { filterFormats.put(filterName, Arrays.asList(formats.split(",[\\s]*"))); } } Context c = null; try { c = new Context(); // have to be super-user to do the filtering c.setIgnoreAuthorization(true); // now apply the filters if (identifier == null) { applyFiltersAllItems(c); } else // restrict application scope to identifier { DSpaceObject dso = HandleManager.resolveToObject(c, identifier); if (dso == null) { throw new IllegalArgumentException( "Cannot resolve " + identifier + " to a DSpace object"); } switch (dso.getType()) { case Constants.COMMUNITY: applyFiltersCommunity(c, (Community) dso); break; case Constants.COLLECTION: applyFiltersCollection(c, (Collection) dso); break; case Constants.ITEM: applyFiltersItem(c, (Item) dso); break; } } // update search index? if (updateIndex) { System.out.println("Updating search index:"); DSIndexer.updateIndex(c); } c.complete(); c = null; } finally { if (c != null) { c.abort(); } } }
public static void main(String[] argv) throws Exception { DSIndexer.setBatchProcessingMode(true); Date startTime = new Date(); int status = 0; try { // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("a", "add", false, "add items to DSpace"); options.addOption("r", "replace", false, "replace items in mapfile"); options.addOption("d", "delete", false, "delete items listed in mapfile"); options.addOption("s", "source", true, "source of items (directory)"); options.addOption("z", "zip", true, "name of zip file"); options.addOption("c", "collection", true, "destination collection(s) Handle or database ID"); options.addOption("m", "mapfile", true, "mapfile items in mapfile"); options.addOption("e", "eperson", true, "email of eperson doing importing"); options.addOption("w", "workflow", false, "send submission through collection's workflow"); options.addOption( "n", "notify", false, "if sending submissions through the workflow, send notification emails"); options.addOption("t", "test", false, "test run - do not actually import items"); options.addOption("p", "template", false, "apply template"); options.addOption("R", "resume", false, "resume a failed import (add only)"); options.addOption("q", "quiet", false, "don't display metadata"); options.addOption("h", "help", false, "help"); CommandLine line = parser.parse(options, argv); String command = null; // add replace remove, etc String sourcedir = null; String mapfile = null; String eperson = null; // db ID or email String[] collections = null; // db ID or handles if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("ItemImport\n", options); System.out.println( "\nadding items: ItemImport -a -e eperson -c collection -s sourcedir -m mapfile"); System.out.println( "\nadding items from zip file: ItemImport -a -e eperson -c collection -s sourcedir -z filename.zip -m mapfile"); System.out.println( "replacing items: ItemImport -r -e eperson -c collection -s sourcedir -m mapfile"); System.out.println("deleting items: ItemImport -d -e eperson -m mapfile"); System.out.println( "If multiple collections are specified, the first collection will be the one that owns the item."); System.exit(0); } if (line.hasOption('a')) { command = "add"; } if (line.hasOption('r')) { command = "replace"; } if (line.hasOption('d')) { command = "delete"; } if (line.hasOption('w')) { useWorkflow = true; if (line.hasOption('n')) { useWorkflowSendEmail = true; } } if (line.hasOption('t')) { isTest = true; System.out.println("**Test Run** - not actually importing items."); } if (line.hasOption('p')) { template = true; } if (line.hasOption('s')) // source { sourcedir = line.getOptionValue('s'); } if (line.hasOption('m')) // mapfile { mapfile = line.getOptionValue('m'); } if (line.hasOption('e')) // eperson { eperson = line.getOptionValue('e'); } if (line.hasOption('c')) // collections { collections = line.getOptionValues('c'); } if (line.hasOption('R')) { isResume = true; System.out.println("**Resume import** - attempting to import items not already imported"); } if (line.hasOption('q')) { isQuiet = true; } boolean zip = false; String zipfilename = ""; String ziptempdir = ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir"); if (line.hasOption('z')) { zip = true; zipfilename = sourcedir + System.getProperty("file.separator") + line.getOptionValue('z'); } // now validate // must have a command set if (command == null) { System.out.println( "Error - must run with either add, replace, or remove (run with -h flag for details)"); System.exit(1); } else if ("add".equals(command) || "replace".equals(command)) { if (sourcedir == null) { System.out.println("Error - a source directory containing items must be set"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (mapfile == null) { System.out.println("Error - a map file to hold importing results must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (eperson == null) { System.out.println("Error - an eperson to do the importing must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (collections == null) { System.out.println("Error - at least one destination collection must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } } else if ("delete".equals(command)) { if (eperson == null) { System.out.println("Error - an eperson to do the importing must be specified"); System.exit(1); } if (mapfile == null) { System.out.println("Error - a map file must be specified"); System.exit(1); } } // can only resume for adds if (isResume && !"add".equals(command)) { System.out.println("Error - resume option only works with --add command"); System.exit(1); } // do checks around mapfile - if mapfile exists and 'add' is selected, // resume must be chosen File myFile = new File(mapfile); if (!isResume && "add".equals(command) && myFile.exists()) { System.out.println("Error - the mapfile " + mapfile + " already exists."); System.out.println( "Either delete it or use --resume if attempting to resume an aborted import."); System.exit(1); } // does the zip file exist and can we write to the temp directory if (zip) { File zipfile = new File(sourcedir); if (!zipfile.canRead()) { System.out.println("Zip file '" + sourcedir + "' does not exist, or is not readable."); System.exit(1); } if (ziptempdir == null) { System.out.println( "Unable to unzip import file as the key 'org.dspace.app.itemexport.work.dir' is not set in dspace.cfg"); System.exit(1); } zipfile = new File(ziptempdir); if (!zipfile.isDirectory()) { System.out.println( "'" + ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir") + "' as defined by the key 'org.dspace.app.itemexport.work.dir' in dspace.cfg " + "is not a valid directory"); System.exit(1); } File tempdir = new File(ziptempdir); if (!tempdir.exists() && !tempdir.mkdirs()) { log.error("Unable to create temporary directory"); } sourcedir = ziptempdir + System.getProperty("file.separator") + line.getOptionValue("z"); ziptempdir = ziptempdir + System.getProperty("file.separator") + line.getOptionValue("z") + System.getProperty("file.separator"); } ItemImport myloader = new ItemImport(); // create a context Context c = new Context(); // find the EPerson, assign to context EPerson myEPerson = null; if (eperson.indexOf('@') != -1) { // @ sign, must be an email myEPerson = EPerson.findByEmail(c, eperson); } else { myEPerson = EPerson.find(c, Integer.parseInt(eperson)); } if (myEPerson == null) { System.out.println("Error, eperson cannot be found: " + eperson); System.exit(1); } c.setCurrentUser(myEPerson); // find collections Collection[] mycollections = null; // don't need to validate collections set if command is "delete" if (!"delete".equals(command)) { System.out.println("Destination collections:"); mycollections = new Collection[collections.length]; // validate each collection arg to see if it's a real collection for (int i = 0; i < collections.length; i++) { // is the ID a handle? if (collections[i].indexOf('/') != -1) { // string has a / so it must be a handle - try and resolve // it mycollections[i] = (Collection) HandleManager.resolveToObject(c, collections[i]); // resolved, now make sure it's a collection if ((mycollections[i] == null) || (mycollections[i].getType() != Constants.COLLECTION)) { mycollections[i] = null; } } // not a handle, try and treat it as an integer collection // database ID else if (collections[i] != null) { mycollections[i] = Collection.find(c, Integer.parseInt(collections[i])); } // was the collection valid? if (mycollections[i] == null) { throw new IllegalArgumentException( "Cannot resolve " + collections[i] + " to collection"); } // print progress info String owningPrefix = ""; if (i == 0) { owningPrefix = "Owning "; } System.out.println(owningPrefix + " Collection: " + mycollections[i].getMetadata("name")); } } // end of validating collections try { // If this is a zip archive, unzip it first if (zip) { ZipFile zf = new ZipFile(zipfilename); ZipEntry entry; Enumeration<? extends ZipEntry> entries = zf.entries(); while (entries.hasMoreElements()) { entry = entries.nextElement(); if (entry.isDirectory()) { if (!new File(ziptempdir + entry.getName()).mkdir()) { log.error("Unable to create contents directory"); } } else { System.out.println("Extracting file: " + entry.getName()); int index = entry.getName().lastIndexOf('/'); if (index == -1) { // Was it created on Windows instead? index = entry.getName().lastIndexOf('\\'); } if (index > 0) { File dir = new File(ziptempdir + entry.getName().substring(0, index)); if (!dir.mkdirs()) { log.error("Unable to create directory"); } } byte[] buffer = new byte[1024]; int len; InputStream in = zf.getInputStream(entry); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(ziptempdir + entry.getName())); while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); } in.close(); out.close(); } } } c.turnOffAuthorisationSystem(); if ("add".equals(command)) { myloader.addItems(c, mycollections, sourcedir, mapfile, template); } else if ("replace".equals(command)) { myloader.replaceItems(c, mycollections, sourcedir, mapfile, template); } else if ("delete".equals(command)) { myloader.deleteItems(c, mapfile); } // complete all transactions c.complete(); } catch (Exception e) { // abort all operations if (mapOut != null) { mapOut.close(); } mapOut = null; c.abort(); e.printStackTrace(); System.out.println(e); status = 1; } // Delete the unzipped file try { if (zip) { System.gc(); System.out.println("Deleting temporary zip directory: " + ziptempdir); ItemImport.deleteDirectory(new File(ziptempdir)); } } catch (Exception ex) { System.out.println("Unable to delete temporary zip archive location: " + ziptempdir); } if (mapOut != null) { mapOut.close(); } if (isTest) { System.out.println("***End of Test Run***"); } } finally { DSIndexer.setBatchProcessingMode(false); Date endTime = new Date(); System.out.println("Started: " + startTime.getTime()); System.out.println("Ended: " + endTime.getTime()); System.out.println( "Elapsed time: " + ((endTime.getTime() - startTime.getTime()) / 1000) + " secs (" + (endTime.getTime() - startTime.getTime()) + " msecs)"); } System.exit(status); }