diff --git a/dspace-api/src/main/java/org/dspace/app/itemexport/ItemExport.java b/dspace-api/src/main/java/org/dspace/app/itemexport/ItemExport.java index 5399479712..1639ab0a7e 100644 --- a/dspace-api/src/main/java/org/dspace/app/itemexport/ItemExport.java +++ b/dspace-api/src/main/java/org/dspace/app/itemexport/ItemExport.java @@ -74,7 +74,7 @@ import org.dspace.handle.HandleManager; *

* Modified by David Little, UCSD Libraries 12/21/04 to allow the registration * of files (bitstreams) into DSpace. - * + * * @author David Little * @author Jay Paz */ @@ -86,12 +86,12 @@ public class ItemExport * used for export download */ public static final String COMPRESSED_EXPORT_MIME_TYPE = "application/zip"; - + /** log4j logger */ private static Logger log = Logger.getLogger(ItemExport.class); /* - * + * */ public static void main(String[] argv) throws Exception { @@ -390,7 +390,7 @@ public class ItemExport /** * Discover the different schemas in use and output a separate metadata XML * file for each schema. - * + * * @param c * @param i * @param destDir @@ -561,7 +561,7 @@ public class ItemExport * were originally registered will be marked in the contents file as such. * However, the export directory will contain actual copies of the content * files being exported. - * + * * @param c * the DSpace context * @param i @@ -720,7 +720,7 @@ public class ItemExport /** * Convenience methot to create export a single Community, Collection, or * Item - * + * * @param dso * - the dspace object to export * @param context @@ -740,7 +740,7 @@ public class ItemExport /** * Convenience method to export a List of dspace objects (Community, * Collection or Item) - * + * * @param dsObjects * - List containing dspace objects * @param context @@ -758,7 +758,7 @@ public class ItemExport /** * Convenience methot to create export a single Community, Collection, or * Item - * + * * @param dso * - the dspace object to export * @param context @@ -778,7 +778,7 @@ public class ItemExport /** * Convenience method to export a List of dspace objects (Community, * Collection or Item) - * + * * @param dsObjects * - List containing dspace objects * @param context @@ -797,7 +797,7 @@ public class ItemExport * Does the work creating a List with all the Items in the Community or * Collection It then kicks off a new Thread to export the items, zip the * export directory and send confirmation email - * + * * @param dsObjects * - List of dspace objects to process * @param context @@ -1008,7 +1008,7 @@ public class ItemExport { iitems.close(); } - + // Make sure the database connection gets closed in all conditions. try { context.complete(); @@ -1027,7 +1027,7 @@ public class ItemExport /** * Create a file name based on the date and eperson - * + * * @param eperson * - eperson who requested export and will be able to download it * @param date @@ -1061,7 +1061,7 @@ public class ItemExport /** * Use config file entry for org.dspace.app.itemexport.download.dir and id * of the eperson to create a download directory name - * + * * @param ePersonID * - id of the eperson who requested export archive * @return String representing a directory in the form of @@ -1085,7 +1085,7 @@ public class ItemExport /** * Returns config file entry for org.dspace.app.itemexport.work.dir - * + * * @return String representing config file entry for * org.dspace.app.itemexport.work.dir * @throws Exception @@ -1104,7 +1104,7 @@ public class ItemExport /** * Used to read the export archived. Inteded for download. - * + * * @param fileName * the name of the file to download * @param eperson @@ -1129,7 +1129,7 @@ public class ItemExport /** * Get the file size of the export archive represented by the file name. - * + * * @param fileName * name of the file to get the size. * @throws Exception @@ -1175,7 +1175,7 @@ public class ItemExport * The file name of the export archive contains the eperson id of the person * who created it When requested for download this method can check if the * person requesting it is the same one that created it - * + * * @param context * dspace context * @param fileName @@ -1208,7 +1208,7 @@ public class ItemExport /** * Reads the download directory for the eperson to see if any export * archives are available - * + * * @param eperson * @return a list of file names representing export archives that have been * processed @@ -1245,7 +1245,7 @@ public class ItemExport * A clean up method that is ran before a new export archive is created. It * uses the config file entry 'org.dspace.app.itemexport.life.span.hours' to * determine if the current exports are too old and need pruging - * + * * @param epersonID * - the id of the eperson to clean up * @throws Exception @@ -1328,7 +1328,7 @@ public class ItemExport * with calling method about success or failure. We accomplis this * communication with email instead. Send a success email once the export * archive is complete and ready for download - * + * * @param context * - the current Context * @param eperson @@ -1344,7 +1344,7 @@ public class ItemExport try { Locale supportedLocale = I18nUtil.getEPersonLocale(eperson); - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_success")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_success")); email.addRecipient(eperson.getEmail()); email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/exportdownload/" + fileName); email.addArgument(ConfigurationManager.getProperty("org.dspace.app.itemexport.life.span.hours")); @@ -1362,7 +1362,7 @@ public class ItemExport * with calling method about success or failure. We accomplis this * communication with email instead. Send an error email if the export * archive fails - * + * * @param eperson * - EPerson to send the error message to * @param error @@ -1376,7 +1376,7 @@ public class ItemExport try { Locale supportedLocale = I18nUtil.getEPersonLocale(eperson); - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_error")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_error")); email.addRecipient(eperson.getEmail()); email.addArgument(error); email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/feedback"); @@ -1461,7 +1461,7 @@ public class ItemExport // byte[] b = new byte[ (int)(cpFile.length()) ]; - cpFileInputStream = new FileInputStream(cpFile); + cpFileInputStream = new FileInputStream(cpFile); ZipEntry cpZipEntry = new ZipEntry(strZipEntryName); cpZipOutputStream.putNextEntry(cpZipEntry); diff --git a/dspace-api/src/main/java/org/dspace/content/Collection.java b/dspace-api/src/main/java/org/dspace/content/Collection.java index f9c350ccf4..20bba5eb53 100644 --- a/dspace-api/src/main/java/org/dspace/content/Collection.java +++ b/dspace-api/src/main/java/org/dspace/content/Collection.java @@ -31,6 +31,7 @@ import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.I18nUtil; +import org.dspace.core.LicenseManager; import org.dspace.core.LogManager; import org.dspace.eperson.Group; import org.dspace.event.Event; @@ -52,7 +53,7 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem; * database after calling update. The default group of * submitters is slightly different - creating or removing this has instant * effect. - * + * * @author Robert Tansley * @version $Revision$ */ @@ -96,7 +97,7 @@ public class Collection extends DSpaceObject /** * Construct a collection with the given table row - * + * * @param context * the context this object exists in * @param row @@ -139,7 +140,7 @@ public class Collection extends DSpaceObject submitters = groupFromColumn("submitter"); admins = groupFromColumn("admin"); - + // Get our Handle if any handle = HandleManager.findHandle(context, this); @@ -153,12 +154,12 @@ public class Collection extends DSpaceObject /** * Get a collection from the database. Loads in the metadata - * + * * @param context * DSpace context object * @param id * ID of the collection - * + * * @return the collection, or null if the ID is invalid. * @throws SQLException */ @@ -199,10 +200,10 @@ public class Collection extends DSpaceObject /** * Create a new collection, with a new ID. This method is not public, and * does not check authorisation. - * + * * @param context * DSpace context object - * + * * @return the newly created collection * @throws SQLException * @throws AuthorizeException @@ -288,10 +289,10 @@ public class Collection extends DSpaceObject /** * 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 */ @@ -339,7 +340,7 @@ public class Collection extends DSpaceObject /** * Get the in_archive items in this collection. The order is indeterminate. - * + * * @return an iterator over the items in the collection. * @throws SQLException */ @@ -358,7 +359,7 @@ public class Collection extends DSpaceObject /** * Get all the items in this collection. The order is indeterminate. - * + * * @return an iterator over the items in the collection. * @throws SQLException */ @@ -376,7 +377,7 @@ public class Collection extends DSpaceObject /** * Get the internal ID of this collection - * + * * @return the internal identifier */ public int getID() @@ -402,36 +403,36 @@ public class Collection extends DSpaceObject /** * Get the value of a metadata field - * + * * @param field * the name of the metadata field to get - * + * * @return the value of the metadata field - * + * * @exception IllegalArgumentException * if the requested metadata field doesn't exist */ public String getMetadata(String field) { String metadata = collectionRow.getStringColumn(field); - return (metadata == null) ? "" : metadata; + return (metadata == null) ? "" : metadata; } /** * Set a metadata value - * + * * @param field * the name of the metadata field to get * @param value * value to set the field to - * + * * @exception IllegalArgumentException * if the requested metadata field doesn't exist * @exception MissingResourceException */ public void setMetadata(String field, String value) throws MissingResourceException { - if ((field.trim()).equals("name") + if ((field.trim()).equals("name") && (value == null || value.trim().equals(""))) { try @@ -443,9 +444,9 @@ public class Collection extends DSpaceObject value = "Untitled"; } } - - /* - * Set metadata field to null if null + + /* + * Set metadata field to null if null * and trim strings to eliminate excess * whitespace. */ @@ -457,7 +458,7 @@ public class Collection extends DSpaceObject { collectionRow.setColumn(field, value.trim()); } - + modifiedMetadata = true; addDetails(field); } @@ -470,7 +471,7 @@ public class Collection extends DSpaceObject /** * Get the logo for the collection. null is returned if the * collection does not have a logo. - * + * * @return the logo of the collection, or null */ public Bitstream getLogo() @@ -546,10 +547,10 @@ public class Collection extends DSpaceObject * Note that while the new group is created in the database, the association * between the group and the collection is not written until * update is called. - * + * * @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 * @throws AuthorizeException @@ -581,7 +582,7 @@ public class Collection extends DSpaceObject * Set the workflow group corresponding to a particular workflow step. * null can be passed in if there should be no associated * group for that workflow step; any existing group is NOT deleted. - * + * * @param step * the workflow step (1-3) * @param g @@ -606,10 +607,10 @@ public class Collection extends DSpaceObject * Get the the workflow group corresponding to a particular workflow step. * This returns null if there is no group associated with * this collection for the given step. - * + * * @param step * the workflow step (1-3) - * + * * @return the group of reviewers or null */ public Group getWorkflowGroup(int step) @@ -622,7 +623,7 @@ public class Collection extends DSpaceObject * 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. - * + * * @return the default group of submitters associated with this collection * @throws SQLException * @throws AuthorizeException @@ -645,7 +646,7 @@ public class Collection extends DSpaceObject // register this as the submitter group collectionRow.setColumn("submitter", submitters.getID()); - + AuthorizeManager.addPolicy(ourContext, this, Constants.ADD, submitters); modified = true; @@ -653,9 +654,9 @@ public class Collection extends DSpaceObject } /** - * 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 + * 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. */ public void removeSubmitters() throws SQLException, AuthorizeException @@ -672,11 +673,11 @@ public class Collection extends DSpaceObject // Remove the link to the collection table. collectionRow.setColumnNull("submitter"); submitters = null; - + modified = true; } - + /** * Get the default group of submitters, if there is one. Note that the * authorization system may allow others to submit to the collection, so @@ -684,7 +685,7 @@ public class Collection extends DSpaceObject *

* The default group of submitters for collection 100 is the one called * collection_100_submit. - * + * * @return the default group of submitters, or null if there * is no default group. */ @@ -697,7 +698,7 @@ public class Collection extends DSpaceObject * 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. - * + * * @return the default group of editors associated with this collection * @throws SQLException * @throws AuthorizeException @@ -713,7 +714,7 @@ public class Collection extends DSpaceObject ourContext.turnOffAuthorisationSystem(); admins = Group.create(ourContext); ourContext.restoreAuthSystemState(); - + admins.setName("COLLECTION_" + getID() + "_ADMIN"); admins.update(); } @@ -723,15 +724,15 @@ public class Collection extends DSpaceObject // register this as the admin group collectionRow.setColumn("admin", admins.getID()); - + modified = true; return admins; } - + /** - * 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 + * 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. */ public void removeAdministrators() throws SQLException, AuthorizeException @@ -748,7 +749,7 @@ public class Collection extends DSpaceObject // Remove the link to the collection table. collectionRow.setColumnNull("admin"); admins = null; - + modified = true; } @@ -759,7 +760,7 @@ public class Collection extends DSpaceObject *

* The default group of administrators for collection 100 is the one called * collection_100_admin. - * + * * @return group of administrators, or null if there is no * default group. */ @@ -772,7 +773,7 @@ public class Collection extends DSpaceObject * 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. - * + * * @return the license for this collection */ public String getLicense() @@ -782,7 +783,7 @@ public class Collection extends DSpaceObject if (license == null || license.trim().equals("")) { // Fallback to site-wide default - license = ConfigurationManager.getDefaultSubmissionLicense(); + license = LicenseManager.getDefaultSubmissionLicense(); } return license; @@ -790,8 +791,8 @@ public class Collection extends DSpaceObject /** * Get the license that users must grant before submitting to this - * collection. - * + * collection. + * * @return the license for this collection */ public String getLicenseCollection() @@ -801,7 +802,7 @@ public class Collection extends DSpaceObject /** * Find out if the collection has a custom license - * + * * @return true if the collection has a custom license */ public boolean hasCustomLicense() @@ -814,7 +815,7 @@ public class Collection extends DSpaceObject /** * Set the license for this collection. Passing in null means * that the site-wide default will be used. - * + * * @param license * the license, or null */ @@ -828,7 +829,7 @@ public class Collection extends DSpaceObject * returned if the collection does not have a template. Submission * mechanisms may copy this template to provide a convenient starting point * for a submission. - * + * * @return the item template, or null */ public Item getTemplateItem() throws SQLException @@ -841,7 +842,7 @@ public class Collection extends DSpaceObject * no action is taken. Caution: Make sure you call update on * the collection after doing this, or the item will have been created but * the collection record will not refer to it. - * + * * @throws SQLException * @throws AuthorizeException */ @@ -868,7 +869,7 @@ public class Collection extends DSpaceObject * record in the database, the collection record will be changed, including * any other changes made; in other words, this method does an * update. - * + * * @throws SQLException * @throws AuthorizeException * @throws IOException @@ -881,7 +882,7 @@ public class Collection extends DSpaceObject collectionRow.setColumnNull("template_item_id"); DatabaseManager.update(ourContext, collectionRow); - + if (template != null) { log.info(LogManager.getHeader(ourContext, "remove_template_item", @@ -894,7 +895,7 @@ public class Collection extends DSpaceObject ourContext.restoreAuthSystemState(); template = null; } - + ourContext.addEvent(new Event(Event.MODIFY, Constants.COLLECTION, getID(), "remove_template_item")); } @@ -903,7 +904,7 @@ public class Collection extends DSpaceObject * the item and the collection - it does nothing like set an issue date, * remove a personal workspace item etc. This has instant effect; * update need not be called. - * + * * @param item * item to add * @throws SQLException @@ -930,7 +931,7 @@ public class Collection extends DSpaceObject /** * Remove an item. If the item is then orphaned, it is deleted. - * + * * @param item * item to remove * @throws SQLException @@ -956,20 +957,20 @@ public class Collection extends DSpaceObject } log.info(LogManager.getHeader(ourContext, "remove_item", "collection_id=" + getID() + ",item_id=" + item.getID())); - + DatabaseManager.updateQuery(ourContext, "DELETE FROM collection2item WHERE collection_id= ? "+ "AND item_id= ? ", getID(), item.getID()); DatabaseManager.setConstraintImmediate(ourContext, "coll2item_item_fk"); - + ourContext.addEvent(new Event(Event.REMOVE, Constants.COLLECTION, getID(), Constants.ITEM, item.getID(), item.getHandle())); } /** * Update the collection metadata (including logo and workflow groups) to * the database. Inserts if this is a new collection. - * + * * @throws SQLException * @throws IOException * @throws AuthorizeException @@ -996,7 +997,7 @@ public class Collection extends DSpaceObject clearDetails(); } } - + public boolean canEditBoolean() throws java.sql.SQLException { return canEditBoolean(true); @@ -1020,7 +1021,7 @@ public class Collection extends DSpaceObject { canEdit(true); } - + public void canEdit(boolean useInheritance) throws AuthorizeException, SQLException { Community[] parents = getCommunities(); @@ -1047,7 +1048,7 @@ public class Collection extends DSpaceObject * Delete the collection, including the metadata and logo. Items that are * then orphans are deleted. Groups associated with this collection * (workflow participants and submitters) are NOT deleted. - * + * * @throws SQLException * @throws AuthorizeException * @throws IOException @@ -1064,12 +1065,12 @@ public class Collection extends DSpaceObject // remove subscriptions - hmm, should this be in Subscription.java? DatabaseManager.updateQuery(ourContext, - "DELETE FROM subscription WHERE collection_id= ? ", + "DELETE FROM subscription WHERE collection_id= ? ", getID()); // Remove Template Item removeTemplateItem(); - + // Remove items ItemIterator items = getAllItems(); @@ -1079,7 +1080,7 @@ public class Collection extends DSpaceObject { Item item = items.next(); IndexBrowse ib = new IndexBrowse(ourContext); - + if (item.isOwningCollection(this)) { // the collection to be deleted is the owning collection, thus remove @@ -1092,12 +1093,12 @@ public class Collection extends DSpaceObject // Browse.itemRemoved(ourContext, itemId); collections[i].removeItem(item); } - - } + + } // the item was only mapped to this collection, so just remove it else { - //notify Browse of removing item mapping. + //notify Browse of removing item mapping. ib.indexItem(item); // Browse.itemChanged(ourContext, item); removeItem(item); @@ -1226,7 +1227,7 @@ public class Collection extends DSpaceObject /** * Get the communities this collection appears in - * + * * @return array of Community objects * @throws SQLException */ @@ -1282,10 +1283,10 @@ public class Collection extends DSpaceObject /** * Return true if other is the same Collection * as this object, false otherwise - * + * * @param other * object to compare to - * + * * @return true if object passed in represents the same * collection as this object */ @@ -1321,7 +1322,7 @@ public class Collection extends DSpaceObject /** * Utility method for reading in a group from a group ID in a column. If the * column is null, null is returned. - * + * * @param col * the column name to read * @return the group referred to by that column, or null @@ -1339,7 +1340,7 @@ public class Collection extends DSpaceObject /** * return type found in Constants - * + * * @return int Constants.COLLECTION */ public int getType() @@ -1351,13 +1352,13 @@ public class Collection extends DSpaceObject * 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 * @param comm * (optional) restrict search to a community, else null * @param actionID * of the action - * + * * @return Collection [] of collections with matching permissions * @throws SQLException */ @@ -1437,7 +1438,7 @@ public class Collection extends DSpaceObject return itemcount; } - + public DSpaceObject getAdminObject(int action) throws SQLException { DSpaceObject adminObject = null; @@ -1473,7 +1474,7 @@ public class Collection extends DSpaceObject } return adminObject; } - + @Override public DSpaceObject getParentObject() throws SQLException { diff --git a/dspace-api/src/main/java/org/dspace/core/ConfigurationManager.java b/dspace-api/src/main/java/org/dspace/core/ConfigurationManager.java index 31ca94e61f..5ebd29d5d2 100644 --- a/dspace-api/src/main/java/org/dspace/core/ConfigurationManager.java +++ b/dspace-api/src/main/java/org/dspace/core/ConfigurationManager.java @@ -43,7 +43,7 @@ import org.apache.log4j.helpers.OptionConverter; * of the DSpace installation directory (specified as the property * dspace.dir in the main configuration file.) * - * + * * @author Robert Tansley * @author Larry Stone - Interpolated values. * @author Mark Diggory - General Improvements to detection, logging and loading. @@ -56,20 +56,17 @@ public class ConfigurationManager /** The configuration properties */ private static Properties properties = null; - + /** module configuration properties */ private static Map moduleProps = new HashMap(); - /** The default license */ - private static String license; - // limit of recursive depth of property variable interpolation in // configuration; anything greater than this is very likely to be a loop. private static final int RECURSION_LIMIT = 9; protected ConfigurationManager() { - + } /** @@ -80,7 +77,7 @@ public class ConfigurationManager { return properties != null; } - + public static boolean isConfigured(String module) { return moduleProps.get(module) != null; @@ -97,24 +94,24 @@ public class ConfigurationManager // { // properties = null; // } - + /** * REMOVED - Flushing the properties could be dangerous in the current DSpace state * Need to consider how it will affect in-flight processes * * Discard properties for a module - will force a reload from disk * when any of module's properties are requested - * + * * @param module the module name */ // public static void flush(String module) // { // moduleProps.remove(module); // } - + /** * Returns all properties in main configuration - * + * * @return properties - all non-modular properties */ public static Properties getProperties() @@ -135,7 +132,7 @@ public class ConfigurationManager /** * Returns all properties for a given module - * + * * @param module * the name of the module * @return properties - all module's properties @@ -163,10 +160,10 @@ public class ConfigurationManager /** * Get a configuration property - * + * * @param property * the name of the property - * + * * @return the value of the property, or null if the property * does not exist. */ @@ -176,11 +173,11 @@ public class ConfigurationManager String value = props == null ? null : props.getProperty(property); return (value != null) ? value.trim() : null; } - + /** * Get a module configuration property value. - * - * @param module + * + * @param module * the name of the module, or null for regular configuration * property * @param property @@ -195,7 +192,7 @@ public class ConfigurationManager { return getProperty(property); } - + String value = null; Properties modProps = getMutableProperties(module); @@ -215,10 +212,10 @@ public class ConfigurationManager /** * Get a configuration property as an integer - * + * * @param property * the name of the property - * + * * @return the value of the property. 0 is returned if the * property does not exist. To differentiate between this case and * when the property actually is zero, use getProperty. @@ -227,16 +224,16 @@ public class ConfigurationManager { return getIntProperty(property, 0); } - + /** * Get a module configuration property as an integer * * @param module * the name of the module - * + * * @param property * the name of the property - * + * * @return the value of the property. 0 is returned if the * property does not exist. To differentiate between this case and * when the property actually is zero, use getProperty. @@ -248,10 +245,10 @@ public class ConfigurationManager /** * Get a configuration property as an integer, with default - * + * * @param property * the name of the property - * + * * @param defaultValue * value to return if property is not found or is not an Integer. * @@ -264,16 +261,16 @@ public class ConfigurationManager { return getIntProperty(null, property, defaultValue); } - + /** * Get a module configuration property as an integer, with default - * + * * @param module * the name of the module - * + * * @param property * the name of the property - * + * * @param defaultValue * value to return if property is not found or is not an Integer. * @@ -316,12 +313,12 @@ public class ConfigurationManager { return getLongProperty(property, 0); } - + /** * Get a module configuration property as a long * * @param module - * the name of the module + * the name of the module * @param property * the name of the property * @@ -333,10 +330,10 @@ public class ConfigurationManager { return getLongProperty(module, property, 0); } - + /** * Get a configuration property as an long, with default - * + * * * @param property * the name of the property @@ -356,7 +353,7 @@ public class ConfigurationManager /** * Get a configuration property as an long, with default - * + * * @param module the module, or null for regular property * * @param property @@ -390,91 +387,14 @@ public class ConfigurationManager return longValue; } - /** - * Get the License - * - * @param - * licenseFile file name - * - * @return - * license text - * - */ - public static String getLicenseText(String licenseFile) - { - // Load in default license - - InputStream is = null; - InputStreamReader ir = null; - BufferedReader br = null; - try - { - is = new FileInputStream(licenseFile); - ir = new InputStreamReader(is, "UTF-8"); - br = new BufferedReader(ir); - String lineIn; - license = ""; - while ((lineIn = br.readLine()) != null) - { - license = license + lineIn + '\n'; - } - } - catch (IOException e) - { - fatal("Can't load configuration", e); - - // FIXME: Maybe something more graceful here, but with the - // configuration we can't do anything - throw new IllegalStateException("Failed to read default license.", e); - } - finally - { - if (br != null) - { - try - { - br.close(); - } - catch (IOException ioe) - { - } - } - - if (ir != null) - { - try - { - ir.close(); - } - catch (IOException ioe) - { - - } - } - if (is != null) - { - try - { - is.close(); - } - catch (IOException ioe) - { - - } - } - } - - return license; - } - /** * Get a configuration property as a boolean. True is indicated if the value * of the property is TRUE or YES (case * insensitive.) - * + * * @param property * the name of the property - * + * * @return the value of the property. false is returned if * the property does not exist. To differentiate between this case * and when the property actually is false, use @@ -484,17 +404,17 @@ public class ConfigurationManager { return getBooleanProperty(property, false); } - + /** - * Get a module configuration property as a boolean. True is indicated if + * Get a module configuration property as a boolean. True is indicated if * the value of the property is TRUE or YES (case * insensitive.) - * - * @param module the module, or null for regular property - * + * + * @param module the module, or null for regular property + * * @param property * the name of the property - * + * * @return the value of the property. false is returned if * the property does not exist. To differentiate between this case * and when the property actually is false, use @@ -504,7 +424,7 @@ public class ConfigurationManager { return getBooleanProperty(module, property, false); } - + /** * Get a configuration property as a boolean, with default. * True is indicated if the value @@ -532,8 +452,8 @@ public class ConfigurationManager * True is indicated if the value * of the property is TRUE or YES (case * insensitive.) - * - * @param module module, or null for regular property + * + * @param module module, or null for regular property * * @param property * the name of the property @@ -564,19 +484,19 @@ public class ConfigurationManager /** * Returns an enumeration of all the keys in the DSpace configuration - * + * * @return an enumeration of all the keys in the DSpace configuration */ public static Enumeration propertyNames() { return propertyNames(null); } - + /** * Returns an enumeration of all the keys in a module configuration - * - * @param module module, or null for regular property - * + * + * @param module module, or null for regular property + * * @return an enumeration of all the keys in the module configuration, * or null if the module does not exist. */ @@ -586,235 +506,13 @@ public class ConfigurationManager return props == null ? null : props.propertyNames(); } - /** - * Get the template for an email message. The message is suitable for - * inserting values using java.text.MessageFormat. - * - * @param emailFile - * full name for the email template, for example "/dspace/config/emails/register". - * - * @return the email object, with the content and subject filled out from - * the template - * - * @throws IOException - * if the template couldn't be found, or there was some other - * error reading the template - */ - public static Email getEmail(String emailFile) throws IOException - { - String charset = null; - String subject = ""; - StringBuffer contentBuffer = new StringBuffer(); - - // Read in template - InputStream is = null; - InputStreamReader ir = null; - BufferedReader br = null; - try - { - is = new FileInputStream(emailFile); - ir = new InputStreamReader(is, "UTF-8"); - br = new BufferedReader(ir); - - boolean more = true; - - while (more) - { - String line = br.readLine(); - - if (line == null) - { - more = false; - } - else if (line.toLowerCase().startsWith("subject:")) - { - // Extract the first subject line - everything to the right - // of the colon, trimmed of whitespace - subject = line.substring(8).trim(); - } - else if (line.toLowerCase().startsWith("charset:")) - { - // Extract the character set from the email - charset = line.substring(8).trim(); - } - else if (!line.startsWith("#")) - { - // Add non-comment lines to the content - contentBuffer.append(line); - contentBuffer.append("\n"); - } - } - } - finally - { - if (br != null) - { - try { - br.close(); - } catch (IOException ioe) - { - } - } - if (ir != null) - { - try { - ir.close(); - } catch (IOException ioe) - { - } - } - if (is != null) - { - try { - is.close(); - } catch (IOException ioe) - { - } - } - } - // Create an email - Email email = new Email(); - email.setSubject(subject); - email.setContent(contentBuffer.toString()); - - if (charset != null) - { - email.setCharset(charset); - } - - return email; - } - - /** - * Get the site-wide default license that submitters need to grant - * - * @return the default license - */ - public static String getDefaultSubmissionLicense() - { - if (properties == null) - { - loadConfig(null); - } - - return license; - } - - /** - * Get the path for the news files. - * - */ - public static String getNewsFilePath() - { - String filePath = ConfigurationManager.getProperty("dspace.dir") - + File.separator + "config" + File.separator; - - return filePath; - } - - /** - * Reads news from a text file. - * - * @param newsFile - * name of the news file to read in, relative to the news file path. - */ - public static String readNewsFile(String newsFile) - { - String fileName = getNewsFilePath(); - - fileName += newsFile; - - StringBuilder text = new StringBuilder(); - - try - { - // retrieve existing news from file - FileInputStream fir = new FileInputStream(fileName); - InputStreamReader ir = new InputStreamReader(fir, "UTF-8"); - BufferedReader br = new BufferedReader(ir); - - String lineIn; - - while ((lineIn = br.readLine()) != null) - { - text.append(lineIn); - } - - br.close(); - ir.close(); - fir.close(); - } - catch (IOException e) - { - warn("news_read: " + e.getLocalizedMessage()); - } - - return text.toString(); - } - - /** - * Writes news to a text file. - * - * @param newsFile - * name of the news file to read in, relative to the news file path. - * @param news - * the text to be written to the file. - */ - public static String writeNewsFile(String newsFile, String news) - { - String fileName = getNewsFilePath(); - - fileName += newsFile; - - try - { - // write the news out to the appropriate file - FileOutputStream fos = new FileOutputStream(fileName); - OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8"); - PrintWriter out = new PrintWriter(osr); - out.print(news); - out.close(); - } - catch (IOException e) - { - warn("news_write: " + e.getLocalizedMessage()); - } - - return news; - } - - /** - * Writes license to a text file. - * - * @param licenseFile - * name for the file int which license will be written, - * relative to the current directory. - */ - public static void writeLicenseFile(String licenseFile, String newLicense) - { - try - { - // write the news out to the appropriate file - FileOutputStream fos = new FileOutputStream(licenseFile); - OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8"); - PrintWriter out = new PrintWriter(osr); - out.print(newLicense); - out.close(); - } - catch (IOException e) - { - warn("license_write: " + e.getLocalizedMessage()); - } - - license = newLicense; - } - + /** The configuration that was loaded. */ private static File loadedFile = null; /** * Return the file that configuration was actually loaded from. Only returns * a valid File after configuration has been loaded. - * + * * @deprecated Please remove all direct usage of the configuration file. * @return File naming configuration data file, or null if not loaded yet. */ @@ -883,17 +581,16 @@ public class ConfigurationManager } catch (IOException ioE) { - fatal("Can't load configuration: " + (modFile == null ? "" : modFile.getAbsolutePath()), ioE); + fatal("Can't load configuration: " + + (modFile == null ? "" : modFile.getAbsolutePath()), ioE); } - - return; } /** * Load the DSpace configuration properties. Only does anything if * properties are not already loaded. Properties are loaded in from the * specified file, or default locations. - * + * * @param configFile * The dspace.cfg configuration file to use, or * null to try default locations @@ -906,7 +603,7 @@ public class ConfigurationManager } URL url = null; - + InputStream is = null; InputStreamReader reader = null; try @@ -922,27 +619,27 @@ public class ConfigurationManager // This isn't really a fatal error though, so catch and ignore log.warn("Unable to access system properties, ignoring.", se); } - + // should only occur after a flush() if (loadedFile != null) { info("Reloading current config file: " + loadedFile.getAbsolutePath()); - + url = loadedFile.toURI().toURL(); } else if (configFile != null) { info("Loading provided config file: " + configFile); - + loadedFile = new File(configFile); url = loadedFile.toURI().toURL(); - + } // Has the default configuration location been overridden? else if (configProperty != null) { info("Loading system provided config property (-Ddspace.configuration): " + configProperty); - + // Load the overriding configuration loadedFile = new File(configProperty); url = loadedFile.toURI().toURL(); @@ -954,11 +651,11 @@ public class ConfigurationManager if (url != null) { info("Loading from classloader: " + url); - + loadedFile = new File(url.getPath()); } } - + if (url == null) { fatal("Cannot find dspace.cfg"); @@ -988,8 +685,8 @@ public class ConfigurationManager { fatal("Can't load configuration: " + url, e); - // FIXME: Maybe something more graceful here, but with the - // configuration we can't do anything + // FIXME: Maybe something more graceful here, but without a + // configuration we can't do anything. throw new IllegalStateException("Cannot load configuration: " + url, e); } finally @@ -1006,131 +703,61 @@ public class ConfigurationManager if (is != null) { try - { + { is.close(); } catch (IOException ioe) - { - } - } - } - - // Load in default license - File licenseFile = new File(getProperty("dspace.dir") + File.separator - + "config" + File.separator + "default.license"); - - FileInputStream fir = null; - InputStreamReader ir = null; - BufferedReader br = null; - try - { - - fir = new FileInputStream(licenseFile); - ir = new InputStreamReader(fir, "UTF-8"); - br = new BufferedReader(ir); - String lineIn; - license = ""; - - while ((lineIn = br.readLine()) != null) - { - license = license + lineIn + '\n'; - } - - br.close(); - - } - catch (IOException e) - { - fatal("Can't load license: " + licenseFile.toString() , e); - - // FIXME: Maybe something more graceful here, but with the - // configuration we can't do anything - throw new IllegalStateException("Cannot load license: " + licenseFile.toString(),e); - } - finally - { - if (br != null) - { - try { - br.close(); - } - catch (IOException ioe) - { - } - } - - if (ir != null) - { - try - { - ir.close(); - } - catch (IOException ioe) - { - } - } - - if (fir != null) - { - try - { - fir.close(); - } - catch (IOException ioe) - { } } } - - try { /* * Initialize Logging once ConfigurationManager is initialized. - * - * This is selection from a property in dspace.cfg, if the property + * + * This is controlled by a property in dspace.cfg. If the property * is absent then nothing will be configured and the application - * will use the defaults provided by log4j. - * + * will use the defaults provided by log4j. + * * Property format is: - * + * * log.init.config = ${dspace.dir}/config/log4j.properties * or * log.init.config = ${dspace.dir}/config/log4j.xml - * + * * See default log4j initialization documentation here: * http://logging.apache.org/log4j/docs/manual.html - * + * * If there is a problem with the file referred to in - * "log.configuration" it needs to be sent to System.err + * "log.configuration", it needs to be sent to System.err * so do not instantiate another Logging configuration. * */ String dsLogConfiguration = ConfigurationManager.getProperty("log.init.config"); - if (dsLogConfiguration == null || System.getProperty("dspace.log.init.disable") != null) + if (dsLogConfiguration == null || System.getProperty("dspace.log.init.disable") != null) { - /* - * Do nothing if log config not set in dspace.cfg or "dspace.log.init.disable" - * system property set. Leave it upto log4j to properly init its logging + /* + * Do nothing if log config not set in dspace.cfg or "dspace.log.init.disable" + * system property set. Leave it upto log4j to properly init its logging * via classpath or system properties. */ - info("Using default log4j provided log configuration," + - "if unintended, check your dspace.cfg for (log.init.config)"); + info("Using default log4j provided log configuration." + + " If unintended, check your dspace.cfg for (log.init.config)"); } else { info("Using dspace provided log configuration (log.init.config)"); - - + + File logConfigFile = new File(dsLogConfiguration); - + if(logConfigFile.exists()) { info("Loading: " + dsLogConfiguration); - + OptionConverter.selectAndConfigure(logConfigFile.toURI() .toURL(), null, org.apache.log4j.LogManager .getLoggerRepository()); @@ -1147,7 +774,7 @@ public class ConfigurationManager fatal("Can't load dspace provided log4j configuration", e); throw new IllegalStateException("Cannot load dspace provided log4j configuration",e); } - + } /** @@ -1224,7 +851,7 @@ public class ConfigurationManager * name from dspace.cfg to the standard * output. If the property does not exist, nothing is written. * - * + * * @param argv * command-line arguments */ @@ -1246,7 +873,7 @@ public class ConfigurationManager System.exit(0); } else if ((argv.length == 4) && argv[0].equals("-module") && - argv[2].equals("-property")) + argv[2].equals("-property")) { String val = getProperty(argv[1], argv[3]); @@ -1269,7 +896,7 @@ public class ConfigurationManager System.exit(1); } - + private static void info(String string) { if (!isLog4jConfigured()) @@ -1320,8 +947,8 @@ public class ConfigurationManager } /* - * Only current solution available to detect - * if log4j is truly configured. + * Only current solution available to detect + * if log4j is truly configured. */ private static boolean isLog4jConfigured() { diff --git a/dspace-api/src/main/java/org/dspace/core/Email.java b/dspace-api/src/main/java/org/dspace/core/Email.java index 540b978912..892be854a0 100644 --- a/dspace-api/src/main/java/org/dspace/core/Email.java +++ b/dspace-api/src/main/java/org/dspace/core/Email.java @@ -7,9 +7,12 @@ */ package org.dspace.core; +import java.io.BufferedReader; import org.apache.log4j.Logger; import java.io.File; +import java.io.FileReader; +import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; @@ -54,57 +57,47 @@ import javax.mail.internet.MimeMultipart; * starts with "Subject:" the text on the right of the colon is used for the * subject line. For example: *

- * + * *

- *    
+ *
  *     # This is a comment line which is stripped
  *     #
  *     # Parameters:   {0}  is a person's name
  *     #               {1}  is the name of a submission
  *     #
  *     Subject: Example e-mail
- *    
+ *
  *     Dear {0},
- *    
+ *
  *     Thank you for sending us your submission "{1}".
- *     
+ *
  * 
- * + * *

* If the example code above was used to send this mail, the resulting mail * would have the subject Example e-mail and the body would be: *

- * + * *

- *    
- *    
+ *
+ *
  *     Dear John,
- *    
+ *
  *     Thank you for sending us your submission "On the Testing of DSpace".
- *     
+ *
  * 
- * + * *

* Note that parameters like {0} cannot be placed in the subject * of the e-mail; they won't get filled out. - * - * + * + * * @author Robert Tansley * @author Jim Downing - added attachment handling code * @version $Revision$ */ public class Email { - /* - * Implementation note: It might be necessary to add a quick utility method - * like "send(to, subject, message)". We'll see how far we get without it - - * having all emails as templates in the config allows customisation and - * internationalisation. - * - * Note that everything is stored and the run in send() so that only send() - * throws a MessagingException. - */ - /** The content of the message */ private String content; @@ -143,7 +136,7 @@ public class Email /** * Add a recipient - * + * * @param email * the recipient's email address */ @@ -156,7 +149,7 @@ public class Email * Set the content of the message. Setting this "resets" the message * formatting -addArgument will start. Comments and any * "Subject:" line must be stripped. - * + * * @param cnt * the content of the message */ @@ -168,7 +161,7 @@ public class Email /** * Set the subject of the message - * + * * @param s * the subject of the message */ @@ -179,7 +172,7 @@ public class Email /** * Set the reply-to email address - * + * * @param email * the reply-to email address */ @@ -190,7 +183,7 @@ public class Email /** * Fill out the next argument in the template - * + * * @param arg * the value for the next argument */ @@ -224,7 +217,7 @@ public class Email /** * Sends the email. - * + * * @throws MessagingException * if there was a problem sending the mail. */ @@ -255,16 +248,16 @@ public class Email // If no character set specified, attempt to retrieve a default if (charset == null) { - charset = ConfigurationManager.getProperty("mail.charset"); + charset = ConfigurationManager.getProperty("mail.charset"); } // Get session Session session; - + // Get the SMTP server authentication information String username = ConfigurationManager.getProperty("mail.server.username"); String password = ConfigurationManager.getProperty("mail.server.password"); - + if (username != null) { props.put("mail.smtp.auth", "true"); @@ -321,7 +314,7 @@ public class Email { message.setSubject(fullSubject); } - + // Add attachments if (attachments.isEmpty()) { @@ -366,6 +359,78 @@ public class Email Transport.send(message); } + /** + * Get the template for an email message. The message is suitable for + * inserting values using java.text.MessageFormat. + * + * @param emailFile + * full name for the email template, for example "/dspace/config/emails/register". + * + * @return the email object, with the content and subject filled out from + * the template + * + * @throws IOException + * if the template couldn't be found, or there was some other + * error reading the template + */ + public static Email getEmail(String emailFile) + throws IOException + { + String charset = null; + String subject = ""; + StringBuilder contentBuffer = new StringBuilder(); + BufferedReader reader = null; + try + { + reader = new BufferedReader(new FileReader(emailFile)); + boolean more = true; + while (more) + { + String line = reader.readLine(); + if (line == null) + { + more = false; + } + else if (line.toLowerCase().startsWith("subject:")) + { + subject = line.substring(8).trim(); + } + else if (line.toLowerCase().startsWith("charset:")) + { + charset = line.substring(8).trim(); + } + else if (!line.startsWith("#")) + { + contentBuffer.append(line); + contentBuffer.append("\n"); + } + } + } finally + { + if (reader != null) + { + reader.close(); + } + } + Email email = new Email(); + email.setSubject(subject); + email.setContent(contentBuffer.toString()); + if (charset != null) + { + email.setCharset(charset); + } + return email; + } + /* + * Implementation note: It might be necessary to add a quick utility method + * like "send(to, subject, message)". We'll see how far we get without it - + * having all emails as templates in the config allows customisation and + * internationalisation. + * + * Note that everything is stored and the run in send() so that only send() + * throws a MessagingException. + */ + /** * Test method to send an email to check email server settings * @@ -402,9 +467,9 @@ public class Email /** * Utility struct class for handling file attachments. - * + * * @author ojd20 - * + * */ private static class FileAttachment { @@ -418,7 +483,7 @@ public class Email String name; } - + /** * Inner Class for SMTP authentication information */ @@ -426,16 +491,16 @@ public class Email { // User name private String name; - + // Password private String password; - + public SMTPAuthenticator(String n, String p) { name = n; password = p; } - + protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(name, password); diff --git a/dspace-api/src/main/java/org/dspace/core/LicenseManager.java b/dspace-api/src/main/java/org/dspace/core/LicenseManager.java new file mode 100644 index 0000000000..a82ea98a84 --- /dev/null +++ b/dspace-api/src/main/java/org/dspace/core/LicenseManager.java @@ -0,0 +1,191 @@ + +package org.dspace.core; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Encapsulate the deposit license. + * + * @author mhwood + */ +public class LicenseManager +{ + private static final Logger log = LoggerFactory.getLogger(LicenseManager.class); + + /** The default license */ + private static String license; + + /** + * Writes license to a text file. + * + * @param licenseFile + * name for the file into which license will be written, + * relative to the current directory. + */ + public static void writeLicenseFile(String licenseFile, + String newLicense) + { + try + { + FileOutputStream fos = new FileOutputStream(licenseFile); + OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8"); + PrintWriter out = new PrintWriter(osr); + out.print(newLicense); + out.close(); + } catch (IOException e) + { + log.warn("license_write: " + e.getLocalizedMessage()); + } + license = newLicense; + } + + /** + * Get the License + * + * @param + * licenseFile file name + * + * @return + * license text + * + */ + public static String getLicenseText(String licenseFile) + { + FileReader fr = null; + BufferedReader br = null; + try + { + fr = new FileReader(licenseFile); + br = new BufferedReader(fr); + String lineIn; + license = ""; + while ((lineIn = br.readLine()) != null) + { + license = license + lineIn + '\n'; + } + } catch (IOException e) + { + log.error("Can't load configuration", e); + throw new IllegalStateException("Failed to read default license.", e); + } finally + { + if (br != null) + { + try + { + br.close(); + } catch (IOException ioe) + { + } + } + if (fr != null) + { + try + { + fr.close(); + } catch (IOException ioe) + { + } + } + } + return license; + } + + /** + * Get the site-wide default license that submitters need to grant + * + * @return the default license + */ + public static String getDefaultSubmissionLicense() + { + if (null == license) + { + init(); + } + return license; + } + + /** + * Load in the default license. + */ + private static void init() + { + File licenseFile = new File(ConfigurationManager.getProperty("dspace.dir") + + File.separator + "config" + File.separator + "default.license"); + + FileInputStream fir = null; + InputStreamReader ir = null; + BufferedReader br = null; + try + { + + fir = new FileInputStream(licenseFile); + ir = new InputStreamReader(fir, "UTF-8"); + br = new BufferedReader(ir); + String lineIn; + LicenseManager.license = ""; + + while ((lineIn = br.readLine()) != null) + { + LicenseManager.license = LicenseManager.license + lineIn + '\n'; + } + + br.close(); + + } + catch (IOException e) + { + log.error("Can't load license: " + licenseFile.toString() , e); + + // FIXME: Maybe something more graceful here, but with the + // configuration we can't do anything + throw new IllegalStateException("Cannot load license: " + + licenseFile.toString(),e); + } + finally + { + if (br != null) + { + try + { + br.close(); + } + catch (IOException ioe) + { + } + } + + if (ir != null) + { + try + { + ir.close(); + } + catch (IOException ioe) + { + } + } + + if (fir != null) + { + try + { + fir.close(); + } + catch (IOException ioe) + { + } + } + } + } +} diff --git a/dspace-api/src/main/java/org/dspace/core/NewsManager.java b/dspace-api/src/main/java/org/dspace/core/NewsManager.java new file mode 100644 index 0000000000..aafc473a7b --- /dev/null +++ b/dspace-api/src/main/java/org/dspace/core/NewsManager.java @@ -0,0 +1,107 @@ + +package org.dspace.core; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Encapsulate access to the news texts. + * + * @author mhwood + */ +public class NewsManager +{ + private static final Logger log = LoggerFactory.getLogger(NewsManager.class); + + /** Not instantiable. */ + private NewsManager() {} + + /** + * Reads news from a text file. + * + * @param newsFile + * name of the news file to read in, relative to the news file path. + */ + public static String readNewsFile(String newsFile) + { + String fileName = getNewsFilePath(); + + fileName += newsFile; + + StringBuilder text = new StringBuilder(); + + try + { + // retrieve existing news from file + FileInputStream fir = new FileInputStream(fileName); + InputStreamReader ir = new InputStreamReader(fir, "UTF-8"); + BufferedReader br = new BufferedReader(ir); + + String lineIn; + + while ((lineIn = br.readLine()) != null) + { + text.append(lineIn); + } + + br.close(); + } + catch (IOException e) + { + log.warn("news_read: " + e.getLocalizedMessage()); + } + + return text.toString(); + } + + /** + * Writes news to a text file. + * + * @param newsFile + * name of the news file to read in, relative to the news file path. + * @param news + * the text to be written to the file. + */ + public static String writeNewsFile(String newsFile, String news) + { + String fileName = getNewsFilePath(); + + fileName += newsFile; + + try + { + // write the news out to the appropriate file + FileOutputStream fos = new FileOutputStream(fileName); + OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8"); + PrintWriter out = new PrintWriter(osr); + out.print(news); + out.close(); + } + catch (IOException e) + { + log.warn("news_write: " + e.getLocalizedMessage()); + } + + return news; + } + + /** + * Get the path for the news files. + * + */ + public static String getNewsFilePath() + { + String filePath = ConfigurationManager.getProperty("dspace.dir") + + File.separator + "config" + File.separator; + + return filePath; + } +} diff --git a/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java b/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java index 43819abbc6..216fb81d66 100644 --- a/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java @@ -78,9 +78,9 @@ public class SolrServiceImpl implements SearchService, IndexingService { public static final String FILTER_SEPARATOR = "\n|||\n"; public static final String AUTHORITY_SEPARATOR = "###"; - + public static final String STORE_SEPARATOR = "\n|||\n"; - + public static final String VARIANTS_STORE_SEPARATOR = "###"; /** @@ -326,7 +326,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { try { ItemIterator items = null; try { - for (items = Item.findAllUnfiltered(context); items.hasNext();) + for (items = Item.findAllUnfiltered(context); items.hasNext();) { Item item = items.next(); indexContent(context, item, force); @@ -461,7 +461,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { if (recipient != null) { - Email email = ConfigurationManager + Email email = Email .getEmail(I18nUtil.getEmailFilename( Locale.getDefault(), "internal_error")); email.addRecipient(recipient); @@ -754,7 +754,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { SolrInputDocument doc = buildDocument(Constants.ITEM, item.getID(), handle, locations); - + log.debug("Building Item: " + handle); doc.addField("withdrawn", item.isWithdrawn()); @@ -839,7 +839,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { toProjectionFields.add(projectionFieldsString); } } - + DCValue[] mydc = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); for (DCValue meta : mydc) { @@ -848,7 +848,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { String value = meta.value; - if (value == null) + if (value == null) { continue; } @@ -864,7 +864,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { { continue; } - + String authority = null; String preferedLabel = null; List variants = null; @@ -878,7 +878,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { meta.schema, meta.element, meta.qualifier):Choices.CF_ACCEPTED; - + if (isAuthorityControlled && meta.authority != null && meta.confidence >= minConfidence) { @@ -965,7 +965,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } doc.addField(searchFilter.getIndexFieldName(), value); doc.addField(searchFilter.getIndexFieldName() + "_keyword", value); - + if (authority != null && preferedLabel == null) { doc.addField(searchFilter.getIndexFieldName() @@ -1006,7 +1006,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { + AUTHORITY_SEPARATOR + authority); } } - + //Add a dynamic fields for auto complete in search doc.addField(searchFilter.getIndexFieldName() + "_ac", value.toLowerCase() + separator + value); @@ -1024,7 +1024,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { + "_ac", var.toLowerCase() + separator + var); } - } + } if(searchFilter.getFilterType().equals(DiscoverySearchFilterFacet.FILTER_TYPE_FACET)) { @@ -1140,7 +1140,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { variantsToStore.append(VARIANTS_STORE_SEPARATOR); variantsToStore.append(var); } - } + } doc.addField( field + "_stored", value + STORE_SEPARATOR + preferedLabel @@ -1152,7 +1152,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { + STORE_SEPARATOR + authority + STORE_SEPARATOR + meta.language); } - + if (meta.language != null && !meta.language.trim().equals("")) { String langField = field + "." + meta.language; @@ -1179,9 +1179,9 @@ public class SolrServiceImpl implements SearchService, IndexingService { { handlePrefix = "http://hdl.handle.net/"; } - + doc.addField("publication_grp",values[0].value.replaceFirst(handlePrefix,"") ); - + } else { @@ -1272,7 +1272,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } catch (RuntimeException e) { log.error("Error while writing item to discovery index: " + handle + " message:"+ e.getMessage(), e); - } + } } /** @@ -1415,7 +1415,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { { return search(context, dso, query, false); } - + public DiscoverResult search(Context context, DSpaceObject dso, DiscoverQuery discoveryQuery, boolean includeWithdrawn) throws SearchServiceException { if(dso != null) { @@ -1460,7 +1460,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } solrQuery.setQuery(query); - + if (!includeWithdrawn) { solrQuery.addFilterQuery("NOT(withdrawn:true)"); @@ -1615,7 +1615,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } return null; } - + protected DiscoverResult retrieveResult(Context context, DiscoverQuery query, QueryResponse solrQueryResponse) throws SQLException { DiscoverResult result = new DiscoverResult(); @@ -1722,7 +1722,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { name = name.substring(0, name.lastIndexOf(']')).replaceAll("TO", "-"); String filter = facetQuery.substring(facetQuery.indexOf('[')); filter = filter.substring(0, filter.lastIndexOf(']') + 1); - + Integer count = sortedFacetQueries.get(facetQuery); //No need to show empty years @@ -1821,7 +1821,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { return new ArrayList(0); } } - + public DiscoverFilterQuery toFilterQuery(Context context, String field, String operator, String value) throws SQLException{ DiscoverFilterQuery result = new DiscoverFilterQuery(); @@ -1925,7 +1925,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } return results; } - + @Override public String toSortFieldIndex(String metadataField, String type) { @@ -2020,7 +2020,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } return value; } - + protected String transformAuthorityValue(Context context, String field, String value) throws SQLException { if (field.endsWith("_filter") || field.endsWith("_ac") || field.endsWith("_acid")) @@ -2051,7 +2051,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } return null; } - + protected String transformSortValue(Context context, String field, String value) throws SQLException { if(field.equals("location.comm") || field.equals("location.coll")) { diff --git a/dspace-api/src/main/java/org/dspace/eperson/AccountManager.java b/dspace-api/src/main/java/org/dspace/eperson/AccountManager.java index 64f54d7c13..95bbd958de 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/AccountManager.java +++ b/dspace-api/src/main/java/org/dspace/eperson/AccountManager.java @@ -31,9 +31,9 @@ import org.dspace.storage.rdbms.TableRow; * randomly generated and thus hard to guess. When the user presents the token * back to the system, the AccountManager can use the token to determine the * identity of the eperson. - * + * * *NEW* now ignores expiration dates so that tokens never expire - * + * * @author Peter Breton * @version $Revision$ */ @@ -49,12 +49,12 @@ public class AccountManager /** * Email registration info to the given email address. - * + * * Potential error conditions: Cannot create registration data in database * (throws SQLException) Error sending email (throws MessagingException) * Error reading email template (throws IOException) Authorization error * (throws AuthorizeException) - * + * * @param context * DSpace context * @param email @@ -69,12 +69,12 @@ public class AccountManager /** * Email forgot password info to the given email address. - * + * * Potential error conditions: No EPerson with that email (returns null) * Cannot create registration data in database (throws SQLException) Error * sending email (throws MessagingException) Error reading email template * (throws IOException) Authorization error (throws AuthorizeException) - * + * * @param context * DSpace context * @param email @@ -93,11 +93,11 @@ public class AccountManager * person by either the sendRegistrationInfo or sendForgotPasswordInfo * methods. *

- * + * *

* If the token is not found return null. *

- * + * * @param context * DSpace context * @param token @@ -125,7 +125,7 @@ public class AccountManager /** * Return the e-mail address referred to by a token, or null if email * address can't be found ignores expiration of token - * + * * @param context * DSpace context * @param token @@ -153,7 +153,7 @@ public class AccountManager /** * Delete token. - * + * * @param context * DSpace context * @param token @@ -171,16 +171,16 @@ public class AccountManager /* * THIS IS AN INTERNAL METHOD. THE SEND PARAMETER ALLOWS IT TO BE USED FOR * TESTING PURPOSES. - * + * * Send an info to the EPerson with the given email address. If isRegister * is TRUE, this is registration email; otherwise, it is forgot-password * email. If send is TRUE, the email is sent; otherwise it is skipped. - * + * * Potential error conditions: No EPerson with that email (returns null) * Cannot create registration data in database (throws SQLException) Error * sending email (throws MessagingException) Error reading email template * (throws IOException) Authorization error (throws AuthorizeException) - * + * * @param context DSpace context @param email Email address to send the * forgot-password email to @param isRegister If true, this is for * registration; otherwise, it is for forgot-password @param send If true, @@ -227,10 +227,10 @@ public class AccountManager /** * Send a DSpace message to the given email address. - * + * * If isRegister is true, this is registration email; * otherwise, it is a forgot-password email. - * + * * @param email * The email address to mail to * @param isRegister @@ -255,7 +255,7 @@ public class AccountManager .append("token=").append(rd.getStringColumn("token")) .toString(); Locale locale = context.getCurrentLocale(); - Email bean = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, isRegister ? "register" + Email bean = Email.getEmail(I18nUtil.getEmailFilename(locale, isRegister ? "register" : "change_password")); bean.addRecipient(email); bean.addArgument(specialLink); diff --git a/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java b/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java index 44ec870f07..fd6738f8e2 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java +++ b/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java @@ -72,7 +72,7 @@ public class EPersonConsumer implements Consumer try { EPerson eperson = EPerson.find(context, id); - Email adminEmail = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "registration_notify")); + Email adminEmail = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "registration_notify")); adminEmail.addRecipient(notifyRecipient); adminEmail.addArgument(ConfigurationManager.getProperty("dspace.name")); @@ -80,7 +80,7 @@ public class EPersonConsumer implements Consumer adminEmail.addArgument(eperson.getFirstName() + " " + eperson.getLastName()); // Name adminEmail.addArgument(eperson.getEmail()); adminEmail.addArgument(new Date()); - + adminEmail.setReplyTo(eperson.getEmail()); adminEmail.send(); diff --git a/dspace-api/src/main/java/org/dspace/eperson/Subscribe.java b/dspace-api/src/main/java/org/dspace/eperson/Subscribe.java index 3e01a44a64..4fe492d1c5 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/Subscribe.java +++ b/dspace-api/src/main/java/org/dspace/eperson/Subscribe.java @@ -48,7 +48,7 @@ import org.dspace.storage.rdbms.TableRowIterator; /** * Class defining methods for sending new item e-mail alerts to users - * + * * @author Robert Tansley * @version $Revision$ */ @@ -60,7 +60,7 @@ public class Subscribe /** * Subscribe an e-person to a collection. An e-mail will be sent every day a * new item appears in the collection. - * + * * @param context * DSpace context * @param eperson @@ -76,10 +76,10 @@ public class Subscribe || ((context.getCurrentUser() != null) && (context .getCurrentUser().getID() == eperson.getID()))) { - // already subscribed? + // already subscribed? TableRowIterator r = DatabaseManager.query(context, "SELECT * FROM subscription WHERE eperson_id= ? " + - " AND collection_id= ? ", + " AND collection_id= ? ", eperson.getID(),collection.getID()); try @@ -117,7 +117,7 @@ public class Subscribe * Unsubscribe an e-person to a collection. Passing in null * for the collection unsubscribes the e-person from all collections they * are subscribed to. - * + * * @param context * DSpace context * @param eperson @@ -141,10 +141,10 @@ public class Subscribe eperson.getID()); } else - { + { DatabaseManager.updateQuery(context, "DELETE FROM subscription WHERE eperson_id= ? " + - "AND collection_id= ? ", + "AND collection_id= ? ", eperson.getID(),collection.getID()); log.info(LogManager.getHeader(context, "unsubscribe", @@ -161,7 +161,7 @@ public class Subscribe /** * Find out which collections an e-person is subscribed to - * + * * @param context * DSpace context * @param eperson @@ -195,7 +195,7 @@ public class Subscribe tri.close(); } } - + Collection[] collArray = new Collection[collections.size()]; return (Collection[]) collections.toArray(collArray); @@ -203,7 +203,7 @@ public class Subscribe /** * Is that e-person subscribed to that collection? - * + * * @param context * DSpace context * @param eperson @@ -217,7 +217,7 @@ public class Subscribe { TableRowIterator tri = DatabaseManager.query(context, "SELECT * FROM subscription WHERE eperson_id= ? " + - "AND collection_id= ? ", + "AND collection_id= ? ", eperson.getID(),collection.getID()); try @@ -246,10 +246,10 @@ public class Subscribe *

* For example, if today's date is 2002-10-10 (in UTC) items made available * during 2002-10-09 (UTC) will be included. - * + * * @param context * DSpace context object - * @param test + * @param test */ public static void processDaily(Context context, boolean test) throws SQLException, IOException @@ -306,7 +306,7 @@ public class Subscribe tri.close(); } } - + // Process the last person if (currentEPerson != null) { @@ -327,36 +327,36 @@ public class Subscribe * Sends an email to the given e-person with details of new items in the * given collections, items that appeared yesterday. No e-mail is sent if * there aren't any new items in any of the collections. - * + * * @param context * DSpace context object * @param eperson * eperson to send to * @param collections * List of collection IDs (Integers) - * @param test + * @param test */ public static void sendEmail(Context context, EPerson eperson, List collections, boolean test) throws IOException, MessagingException, SQLException { // Get a resource bundle according to the eperson language preferences - Locale supportedLocale = I18nUtil.getEPersonLocale(eperson); + Locale supportedLocale = I18nUtil.getEPersonLocale(eperson); ResourceBundle labels = ResourceBundle.getBundle("Messages", supportedLocale); - + // Get the start and end dates for yesterday - // The date should reflect the timezone as well. Otherwise we stand to lose that information + // The date should reflect the timezone as well. Otherwise we stand to lose that information // in truncation and roll to an earlier date than intended. Calendar cal = Calendar.getInstance(TimeZone.getDefault()); cal.setTime(new Date()); - + // What we actually want to pass to Harvest is "Midnight of yesterday in my current timezone" // Truncation will actually pass in "Midnight of yesterday in UTC", which will be, // at least in CDT, "7pm, the day before yesterday, in my current timezone". cal.add(Calendar.HOUR, -24); Date thisTimeYesterday = cal.getTime(); - + cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); @@ -374,7 +374,7 @@ public class Subscribe try { boolean includeAll = ConfigurationManager.getBooleanProperty("harvest.includerestricted.subscription", true); - + // we harvest all the changed item from yesterday until now List itemInfos = Harvest.harvest(context, c, new DCDate(midnightYesterday).toString(), null, 0, // Limit // and @@ -386,7 +386,7 @@ public class Subscribe false, // But not containers false, // Or withdrawals includeAll); - + if (ConfigurationManager.getBooleanProperty("eperson.subscription.onlynew", false)) { // get only the items archived yesterday @@ -394,7 +394,7 @@ public class Subscribe } else { - // strip out the item archived today or + // strip out the item archived today or // not archived yesterday and modified today itemInfos = filterOutToday(itemInfos); } @@ -411,19 +411,19 @@ public class Subscribe { isFirst = false; } - + emailText.append(labels.getString("org.dspace.eperson.Subscribe.new-items")).append(" ").append( c.getMetadata("name")).append(": ").append( itemInfos.size()).append("\n\n"); - + for (int j = 0; j < itemInfos.size(); j++) { HarvestedItemInfo hii = (HarvestedItemInfo) itemInfos .get(j); - + DCValue[] titles = hii.item.getDC("title", null, Item.ANY); emailText.append(" ").append(labels.getString("org.dspace.eperson.Subscribe.title")).append(" "); - + if (titles.length > 0) { emailText.append(titles[0].value); @@ -432,22 +432,22 @@ public class Subscribe { emailText.append(labels.getString("org.dspace.eperson.Subscribe.untitled")); } - + DCValue[] authors = hii.item.getDC("contributor", Item.ANY, Item.ANY); - + if (authors.length > 0) { emailText.append("\n ").append(labels.getString("org.dspace.eperson.Subscribe.authors")).append(" ").append( authors[0].value); - + for (int k = 1; k < authors.length; k++) { emailText.append("\n ").append( authors[k].value); } } - + emailText.append("\n ").append(labels.getString("org.dspace.eperson.Subscribe.id")).append(" ").append( HandleManager.getCanonicalForm(hii.handle)).append( "\n\n"); @@ -463,47 +463,47 @@ public class Subscribe // Send an e-mail if there were any new items if (emailText.length() > 0) { - + if(test) { log.info(LogManager.getHeader(context, "subscription:", "eperson=" + eperson.getEmail() )); log.info(LogManager.getHeader(context, "subscription:", "text=" + emailText.toString() )); } else { - - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "subscription")); + + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "subscription")); email.addRecipient(eperson.getEmail()); email.addArgument(emailText.toString()); email.send(); - + log.info(LogManager.getHeader(context, "sent_subscription", "eperson_id=" + eperson.getID() )); - + } - + } } /** * Method for invoking subscriptions via the command line - * + * * @param argv * command-line arguments, none used yet */ - public static void main(String[] argv) + public static void main(String[] argv) { String usage = "org.dspace.eperson.Subscribe [-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); @@ -527,14 +527,14 @@ public class Subscribe formatter.printHelp(usage, options); System.exit(1); } - + boolean test = line.hasOption("t"); if(test) { log.setLevel(Level.DEBUG); } - + Context context = null; try @@ -556,7 +556,7 @@ public class Subscribe } } } - + private static List filterOutToday(List completeList) { log.debug("Filtering out all today item to leave new items list size=" @@ -614,7 +614,7 @@ public class Subscribe } else { - // the item has been modified yesterday... + // the item has been modified yesterday... filteredList.add(infoObject); } } @@ -632,11 +632,11 @@ public class Subscribe Date thisTimeYesterday = new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000)); String yesterday = sdf.format(thisTimeYesterday); - + for (HarvestedItemInfo infoObject : completeList) { DCValue[] dateAccArr = infoObject.item.getMetadata("dc", "date", "accessioned", Item.ANY); - + if (dateAccArr != null && dateAccArr.length > 0) { for(DCValue date : dateAccArr) @@ -656,9 +656,9 @@ public class Subscribe } } } - - + + } else { diff --git a/dspace-api/src/main/java/org/dspace/harvest/OAIHarvester.java b/dspace-api/src/main/java/org/dspace/harvest/OAIHarvester.java index a7b325677b..6374f31c99 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/OAIHarvester.java +++ b/dspace-api/src/main/java/org/dspace/harvest/OAIHarvester.java @@ -71,73 +71,73 @@ import ORG.oclc.oai.harvester2.verb.ListSets; /** - * This class handles OAI harvesting of externally located records into this repository. - * + * This class handles OAI harvesting of externally located records into this repository. + * * @author Alexey Maslov */ public class OAIHarvester { - + /* The main harvesting thread */ private static HarvestScheduler harvester; private static Thread mainHarvestThread; - + /** log4j category */ private static Logger log = Logger.getLogger(OAIHarvester.class); - + private static final Namespace ATOM_NS = Namespace.getNamespace("http://www.w3.org/2005/Atom"); private static final Namespace ORE_NS = Namespace.getNamespace("http://www.openarchives.org/ore/terms/"); private static final Namespace OAI_NS = Namespace.getNamespace("http://www.openarchives.org/OAI/2.0/"); - + public static final String OAI_ADDRESS_ERROR = "invalidAddress"; public static final String OAI_SET_ERROR = "noSuchSet"; public static final String OAI_DMD_ERROR = "metadataNotSupported"; public static final String OAI_ORE_ERROR = "oreNotSupported"; - - + + // The collection this harvester instance is dealing with Collection targetCollection; HarvestedCollection harvestRow; - + // our context Context ourContext; - + // Namespace used by the ORE serialization format // Set in dspace.cfg as harvester.oai.oreSerializationFormat.{ORESerialKey} = {ORESerialNS} private Namespace ORESerialNS; private String ORESerialKey; - + // Namespace of the descriptive metadata that should be harvested in addition to the ORE // Set in dspace.cfg as harvester.oai.metadataformats.{MetadataKey} = {MetadataNS},{Display Name} private Namespace metadataNS; - private String metadataKey; - + private String metadataKey; + // DOMbuilder class for the DOM -> JDOM conversions private static DOMBuilder db = new DOMBuilder(); - + // The point at which this thread should terminate itself /* Initialize the harvester with a collection object */ - public OAIHarvester(Context c, DSpaceObject dso, HarvestedCollection hc) throws HarvestingException, SQLException + public OAIHarvester(Context c, DSpaceObject dso, HarvestedCollection hc) throws HarvestingException, SQLException { if (dso.getType() != Constants.COLLECTION) { throw new HarvestingException("OAIHarvester can only harvest collections"); } - + ourContext = c; targetCollection = (Collection)dso; - + harvestRow = hc; if (harvestRow == null || !harvestRow.isHarvestable()) { throw new HarvestingException("Provided collection is not set up for harvesting"); } - + // Set the ORE options Namespace ORESerializationNamespace = OAIHarvester.getORENamespace(); - + if (ORESerializationNamespace == null) { log.error("No ORE serialization namespace declared; see dspace.cfg option \"harvester.oai.oreSerializationFormat.{ORESerialKey} = {ORESerialNS}\""); throw new HarvestingException("No ORE serialization namespace specified"); @@ -145,29 +145,29 @@ public class OAIHarvester { ORESerialNS = Namespace.getNamespace(ORESerializationNamespace.getURI()); ORESerialKey = ORESerializationNamespace.getPrefix(); } - + // Set the metadata options metadataKey = harvestRow.getHarvestMetadataConfig(); metadataNS = OAIHarvester.getDMDNamespace(metadataKey); - + if (metadataNS == null) { log.error("No matching metadata namespace found for \"" + metadataKey + "\", see oai.cfg option \"harvester.oai.metadataformats.{MetadataKey} = {MetadataNS},{Display Name}\""); throw new HarvestingException("Metadata declaration not found"); - } + } } - - + + /** * Search the configuration options and find the ORE serializaition string - * @return Namespace of the supported ORE format. Returns null if not found. + * @return Namespace of the supported ORE format. Returns null if not found. */ private static Namespace getORENamespace() { String ORESerializationString = null; String ORESeialKey = null; String oreString = "harvester.oai.oreSerializationFormat."; - + Enumeration pe = ConfigurationManager.propertyNames("oai"); - + while (pe.hasMoreElements()) { String key = (String)pe.nextElement(); @@ -178,27 +178,27 @@ public class OAIHarvester { return Namespace.getNamespace(ORESeialKey, ORESerializationString); } } - + // Fallback if the configuration option is not present return Namespace.getNamespace("ore", ATOM_NS.getURI()); } - + /** * Cycle through the options and find the metadata namespace matching the provided key. - * @param metadataKey + * @param metadataKey * @return Namespace of the designated metadata format. Returns null of not found. */ private static Namespace getDMDNamespace(String metadataKey) { String metadataString = null; String metaString = "harvester.oai.metadataformats."; - + Enumeration pe = ConfigurationManager.propertyNames("oai"); - + while (pe.hasMoreElements()) { String key = (String)pe.nextElement(); - + if (key.startsWith(metaString) && key.substring(metaString.length()).equals((metadataKey))) { metadataString = ConfigurationManager.getProperty("oai", key); String namespacePiece; @@ -216,17 +216,17 @@ public class OAIHarvester { } return null; } - - - - - - /** - * Performs a harvest cycle on this collection. This will query the remote OAI-PMH provider, check for updates since last - * harvest, and ingest the returned items. + + + + + + /** + * Performs a harvest cycle on this collection. This will query the remote OAI-PMH provider, check for updates since last + * harvest, and ingest the returned items. */ - public void runHarvest() throws SQLException, IOException, AuthorizeException - { + public void runHarvest() throws SQLException, IOException, AuthorizeException + { // figure out the relevant parameters String oaiSource = harvestRow.getOaiSource(); String oaiSetId = harvestRow.getOaiSetId(); @@ -242,13 +242,13 @@ public class OAIHarvester { { fromDate = processDate(harvestRow.getHarvestDate()); } - + Date startTime = new Date(); - String toDate = processDate(startTime,0); - + String toDate = processDate(startTime,0); + String dateGranularity; - - try + + try { // obtain the desired descriptive metadata format and verify that the OAI server actually provides it // do the same thing for ORE, which should be encoded in Atom and carry its namespace @@ -261,7 +261,7 @@ public class OAIHarvester { fromDate = fromDate.substring(0, dateGranularity.length()); } toDate = toDate.substring(0, dateGranularity.length()); - + descMDPrefix = oaiResolveNamespaceToPrefix(oaiSource, metadataNS.getURI()); OREPrefix = oaiResolveNamespaceToPrefix(oaiSource, ORESerialNS.getURI()); } @@ -272,7 +272,7 @@ public class OAIHarvester { catch (ConnectException fe) { log.error("The OAI server did not respond."); throw new HarvestingException("The OAI server did not respond.", fe); - } + } if (descMDPrefix == null) { log.error("The OAI server does not support this metadata format"); throw new HarvestingException("The OAI server does not support this metadata format: " + metadataNS.getURI()); @@ -280,53 +280,53 @@ public class OAIHarvester { if (OREPrefix == null && harvestRow.getHarvestType() != HarvestedCollection.TYPE_DMD) { throw new HarvestingException("The OAI server does not support ORE dissemination in the configured serialization format: " + ORESerialNS.getURI()); } - + Document oaiResponse = null; - Element root = null; + Element root = null; String resumptionToken; - + // set the status indicating the collection is currently being processed harvestRow.setHarvestStatus(HarvestedCollection.STATUS_BUSY); harvestRow.setHarvestMessage("Collection is currently being harvested"); harvestRow.setHarvestStartTime(startTime); harvestRow.update(); ourContext.commit(); - + // expiration timer starts int expirationInterval = ConfigurationManager.getIntProperty("oai", "harvester.threadTimeout"); if (expirationInterval == 0) { expirationInterval = 24; } - + Calendar calendar = Calendar.getInstance(); calendar.setTime(startTime); calendar.add(Calendar.HOUR, expirationInterval); Date expirationTime = calendar.getTime(); - + // main loop to keep requesting more objects until we're done List records; Set errorSet = new HashSet(); - + ListRecords listRecords = new ListRecords(oaiSource, fromDate, toDate, oaiSetId, descMDPrefix); log.debug("Harvesting request parameters: listRecords " + oaiSource + " " + fromDate + " " + toDate + " " + oaiSetId + " " + descMDPrefix); if (listRecords != null) { log.info("HTTP Request: " + listRecords.getRequestURL()); } - while (listRecords != null) + while (listRecords != null) { records = new ArrayList(); oaiResponse = db.build(listRecords.getDocument()); - if (listRecords.getErrors() != null && listRecords.getErrors().getLength() > 0) + if (listRecords.getErrors() != null && listRecords.getErrors().getLength() > 0) { - for (int i=0; i0) + if (records != null && records.size()>0) { log.info("Found " + records.size() + " records to process"); for (Element record : records) { @@ -358,7 +358,7 @@ public class OAIHarvester { { throw new HarvestingException("runHarvest method timed out for collection " + targetCollection.getID()); } - + processRecord(record,OREPrefix); ourContext.commit(); } @@ -379,13 +379,13 @@ public class OAIHarvester { catch (HarvestingException hex) { log.error("Harvesting error occured while processing an OAI record: " + hex.getMessage()); harvestRow.setHarvestMessage("Error occured while processing an OAI record"); - + // if the last status is also an error, alert the admin if (harvestRow.getHarvestMessage().contains("Error")) { alertAdmin(HarvestedCollection.STATUS_OAI_ERROR, hex); } harvestRow.setHarvestStatus(HarvestedCollection.STATUS_OAI_ERROR); - return; + return; } catch (Exception ex) { harvestRow.setHarvestMessage("Unknown error occured while generating an OAI response"); @@ -394,14 +394,14 @@ public class OAIHarvester { log.error("Error occured while generating an OAI response: " + ex.getMessage() + " " + ex.getCause()); ex.printStackTrace(); return; - } + } finally { harvestRow.update(); targetCollection.update(); ourContext.commit(); ourContext.restoreAuthSystemState(); } - + // If we got to this point, it means the harvest was completely successful Date finishTime = new Date(); long timeTaken = finishTime.getTime() - startTime.getTime(); @@ -411,24 +411,24 @@ public class OAIHarvester { harvestRow.update(); ourContext.commit(); } - + /** - * Process an individual PMH record, making (or updating) a corresponding DSpace Item. + * Process an individual PMH record, making (or updating) a corresponding DSpace Item. * @param record a JDOM Element containing the actual PMH record with descriptive metadata. * @param OREPrefix the metadataprefix value used by the remote PMH server to disseminate ORE. Only used for collections set up to harvest content. */ - private void processRecord(Element record, String OREPrefix) throws SQLException, AuthorizeException, IOException, CrosswalkException, HarvestingException, ParserConfigurationException, SAXException, TransformerException + private void processRecord(Element record, String OREPrefix) throws SQLException, AuthorizeException, IOException, CrosswalkException, HarvestingException, ParserConfigurationException, SAXException, TransformerException { WorkspaceItem wi = null; Date timeStart = new Date(); - + // grab the oai identifier String itemOaiID = record.getChild("header", OAI_NS).getChild("identifier", OAI_NS).getText(); Element header = record.getChild("header",OAI_NS); - + // look up the item corresponding to the OAI identifier Item item = HarvestedItem.getItemByOAIId(ourContext, itemOaiID, targetCollection.getID()); - + // Make sure the item hasn't been deleted in the mean time if (header.getAttribute("status") != null && header.getAttribute("status").getValue().equals("deleted")) { log.info("Item " + itemOaiID + " has been marked as deleted on the OAI server."); @@ -436,44 +436,44 @@ public class OAIHarvester { { targetCollection.removeItem(item); } - - ourContext.restoreAuthSystemState(); + + ourContext.restoreAuthSystemState(); return; } - + // If we are only harvesting descriptive metadata, the record should already contain all we need List descMD = record.getChild("metadata", OAI_NS).getChildren(); IngestionCrosswalk MDxwalk = (IngestionCrosswalk)PluginManager.getNamedPlugin(IngestionCrosswalk.class, this.metadataKey); - - // Otherwise, obtain the ORE ReM and initiate the ORE crosswalk + + // Otherwise, obtain the ORE ReM and initiate the ORE crosswalk IngestionCrosswalk ORExwalk = null; Element oreREM = null; if (harvestRow.getHarvestType() > 1) { oreREM = getMDrecord(harvestRow.getOaiSource(), itemOaiID, OREPrefix).get(0); ORExwalk = (IngestionCrosswalk)PluginManager.getNamedPlugin(IngestionCrosswalk.class, this.ORESerialKey); } - + // Ignore authorization ourContext.turnOffAuthorisationSystem(); - + HarvestedItem hi; - - if (item != null) // found an item so we modify - { + + if (item != null) // found an item so we modify + { log.debug("Item " + item.getHandle() + " was found locally. Using it to harvest " + itemOaiID + "."); - - // FIXME: check for null pointer if for some odd reason we don't have a matching hi + + // FIXME: check for null pointer if for some odd reason we don't have a matching hi hi = HarvestedItem.find(ourContext, item.getID()); - + // Compare last-harvest on the item versus the last time the item was updated on the OAI provider side - // If ours is more recent, forgo this item, since it's probably a left-over from a previous harvesting attempt + // If ours is more recent, forgo this item, since it's probably a left-over from a previous harvesting attempt Date OAIDatestamp = Utils.parseISO8601Date(header.getChildText("datestamp", OAI_NS)); Date itemLastHarvest = hi.getHarvestDate(); if (itemLastHarvest != null && OAIDatestamp.before(itemLastHarvest)) { log.info("Item " + item.getHandle() + " was harvested more recently than the last update time reporetd by the OAI server; skipping."); return; } - + // Otherwise, clear and re-import the metadata and bitstreams item.clearMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); if (descMD.size() == 1) @@ -488,26 +488,26 @@ public class OAIHarvester { // Import the actual bitstreams if (harvestRow.getHarvestType() == 3) { log.info("Running ORE ingest on: " + item.getHandle()); - + Bundle[] allBundles = item.getBundles(); for (Bundle bundle : allBundles) { item.removeBundle(bundle); } ORExwalk.ingest(ourContext, item, oreREM); } - + scrubMetadata(item); - } - else - // NOTE: did not find, so we create (presumably, there will never be a case where an item already + } + else + // NOTE: did not find, so we create (presumably, there will never be a case where an item already // exists in a harvest collection but does not have an OAI_id) { wi = WorkspaceItem.create(ourContext, targetCollection, false); item = wi.getItem(); - + hi = HarvestedItem.create(ourContext, item.getID(), itemOaiID); //item.setOaiID(itemOaiID); - + if (descMD.size() == 1) { MDxwalk.ingest(ourContext, item, descMD.get(0)); @@ -516,18 +516,18 @@ public class OAIHarvester { { MDxwalk.ingest(ourContext, item, descMD); } - + if (harvestRow.getHarvestType() == 3) { ORExwalk.ingest(ourContext, item, oreREM); } - + // see if we can do something about the wonky metadata scrubMetadata(item); - + // see if a handle can be extracted for the item String handle = extractHandle(item); - - if (handle != null) + + if (handle != null) { DSpaceObject dso = HandleManager.resolveToObject(ourContext, handle); if (dso != null) @@ -535,12 +535,12 @@ public class OAIHarvester { throw new HarvestingException("Handle collision: attempted to re-assign handle '" + handle + "' to an incoming harvested item '" + hi.getOaiID() + "'."); } } - + try { item = InstallItem.installItem(ourContext, wi, handle); //item = InstallItem.installItem(ourContext, wi); } - // clean up the workspace item if something goes wrong before + // clean up the workspace item if something goes wrong before catch(SQLException se) { wi.deleteWrapper(); throw se; @@ -554,27 +554,27 @@ public class OAIHarvester { throw ae; } } - + // Now create the special ORE bundle and drop the ORE document in it - if (harvestRow.getHarvestType() == 2 || harvestRow.getHarvestType() == 3) + if (harvestRow.getHarvestType() == 2 || harvestRow.getHarvestType() == 3) { Bundle OREBundle = item.createBundle("ORE"); - + XMLOutputter outputter = new XMLOutputter(); String OREString = outputter.outputString(oreREM); ByteArrayInputStream OREStream = new ByteArrayInputStream(OREString.getBytes()); - + Bitstream OREBitstream = OREBundle.createBitstream(OREStream); OREBitstream.setName("ORE.xml"); BitstreamFormat bf = FormatIdentifier.guessFormat(ourContext, OREBitstream); OREBitstream.setFormat(bf); OREBitstream.update(); - + OREBundle.addBitstream(OREBitstream); OREBundle.update(); } - + //item.setHarvestDate(new Date()); hi.setHarvestDate(new Date()); @@ -583,7 +583,7 @@ public class OAIHarvester { + this.harvestRow.getOaiSource() + " on " + new DCDate(hi.getHarvestDate()) + " (GMT). Item's OAI Record identifier: " + hi.getOaiID(); item.addMetadata("dc", "description", "provenance", "en", provenanceMsg); - + item.update(); hi.update(); long timeTaken = new Date().getTime() - timeStart.getTime(); @@ -592,47 +592,47 @@ public class OAIHarvester { // Stop ignoring authorization ourContext.restoreAuthSystemState(); } - - - + + + /** * Scan an item's metadata, looking for the value "identifier.*". If it meets the parameters that identify it as valid handle - * as set in dspace.cfg (harvester.acceptedHandleServer and harvester.rejectedHandlePrefix), use that handle instead of - * minting a new one. + * as set in dspace.cfg (harvester.acceptedHandleServer and harvester.rejectedHandlePrefix), use that handle instead of + * minting a new one. * @param item a newly created, but not yet installed, DSpace Item * @return null or the handle to be used. */ - private String extractHandle(Item item) + private String extractHandle(Item item) { String acceptedHandleServersString = ConfigurationManager.getProperty("oai", "harvester.acceptedHandleServer"); if (acceptedHandleServersString == null) { acceptedHandleServersString = "hdl.handle.net"; } - + String rejectedHandlePrefixString = ConfigurationManager.getProperty("oai", "harvester.rejectedHandlePrefix"); if (rejectedHandlePrefixString == null) { rejectedHandlePrefixString = "123456789"; } - + DCValue[] values = item.getMetadata("dc", "identifier", Item.ANY, Item.ANY); - - if (values.length > 0 && !acceptedHandleServersString.equals("")) + + if (values.length > 0 && !acceptedHandleServersString.equals("")) { String[] acceptedHandleServers = acceptedHandleServersString.split(","); String[] rejectedHandlePrefixes = rejectedHandlePrefixString.split(","); - - for (DCValue value : values) + + for (DCValue value : values) { // 0 1 2 3 4 - // http://hdl.handle.net/1234/12 + // http://hdl.handle.net/1234/12 String[] urlPieces = value.value.split("/"); if (urlPieces.length != 5) { continue; } - + for (String server : acceptedHandleServers) { if (urlPieces[2].equals(server)) { for (String prefix : rejectedHandlePrefixes) { @@ -641,22 +641,22 @@ public class OAIHarvester { return urlPieces[3] + "/" + urlPieces[4]; } } - + } } } } - + return null; } - - + + /** * Scans an item's newly ingested metadata for elements not defined in this DSpace instance. It then takes action based - * on a configurable parameter (fail, ignore, add). + * on a configurable parameter (fail, ignore, add). * @param item a DSpace item recently pushed through an ingestion crosswalk but prior to update/installation */ - private void scrubMetadata(Item item) throws SQLException, HarvestingException, AuthorizeException, IOException + private void scrubMetadata(Item item) throws SQLException, HarvestingException, AuthorizeException, IOException { // The two options, with three possibilities each: add, ignore, fail String schemaChoice = ConfigurationManager.getProperty("oai", "harvester.unknownSchema"); @@ -664,17 +664,17 @@ public class OAIHarvester { { schemaChoice = "fail"; } - + String fieldChoice = ConfigurationManager.getProperty("oai", "harvester.unknownField"); if (fieldChoice == null) { fieldChoice = "fail"; } - + List clearList = new ArrayList(); - + DCValue[] values = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); - for (DCValue value : values) + for (DCValue value : values) { // Verify that the schema exists MetadataSchema mdSchema = MetadataSchema.find(ourContext, value.schema); @@ -693,12 +693,12 @@ public class OAIHarvester { } clearList.add(value.schema); } - // ignore the offending schema, quietly dropping all of its metadata elements before they clog our gears + // ignore the offending schema, quietly dropping all of its metadata elements before they clog our gears else if (schemaChoice.equals("ignore")) { item.clearMetadata(value.schema, Item.ANY, Item.ANY, Item.ANY); continue; } - // otherwise, go ahead and generate the error + // otherwise, go ahead and generate the error else { throw new HarvestingException("The '" + value.schema + "' schema has not been defined in this DSpace instance. "); } @@ -727,105 +727,105 @@ public class OAIHarvester { } } } - - return; + + return; } - - - - + + + + /** * Process a date, converting it to RFC3339 format, setting the timezone to UTC and subtracting time padding * from the config file. - * @param date source Date + * @param date source Date * @return a string in the format 'yyyy-mm-ddThh:mm:ssZ' and converted to UTC timezone */ private String processDate(Date date) { Integer timePad = ConfigurationManager.getIntProperty("oai", "harvester.timePadding"); - + if (timePad == 0) { timePad = 120; } - + return processDate(date, timePad); } - + /** * Process a date, converting it to RFC3339 format, setting the timezone to UTC and subtracting time padding * from the config file. * @param date source Date - * @param secondsPad number of seconds to subtract from the date + * @param secondsPad number of seconds to subtract from the date * @return a string in the format 'yyyy-mm-ddThh:mm:ssZ' and converted to UTC timezone */ private String processDate(Date date, int secondsPad) { - + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); - + Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.SECOND, -1*secondsPad); date = calendar.getTime(); - - return formatter.format(date); + + return formatter.format(date); } - - + + /** - * Query OAI-PMH server for the granularity of its datestamps. - * @throws TransformerException - * @throws SAXException - * @throws ParserConfigurationException - * @throws IOException + * Query OAI-PMH server for the granularity of its datestamps. + * @throws TransformerException + * @throws SAXException + * @throws ParserConfigurationException + * @throws IOException */ - private String oaiGetDateGranularity(String oaiSource) throws IOException, ParserConfigurationException, SAXException, TransformerException + private String oaiGetDateGranularity(String oaiSource) throws IOException, ParserConfigurationException, SAXException, TransformerException { Identify iden = new Identify(oaiSource); return iden.getDocument().getElementsByTagNameNS(OAI_NS.getURI(), "granularity").item(0).getTextContent(); } - + /** - * Query the OAI-PMH server for its mapping of the supplied namespace and metadata prefix. - * For example for a typical OAI-PMH server a query "http://www.openarchives.org/OAI/2.0/oai_dc/" would return "oai_dc". + * Query the OAI-PMH server for its mapping of the supplied namespace and metadata prefix. + * For example for a typical OAI-PMH server a query "http://www.openarchives.org/OAI/2.0/oai_dc/" would return "oai_dc". * @param oaiSource the address of the OAI-PMH provider * @param MDNamespace the namespace that we are trying to resolve to the metadataPrefix * @return metadataPrefix the OAI-PMH provider has assigned to the supplied namespace */ - public static String oaiResolveNamespaceToPrefix(String oaiSource, String MDNamespace) throws IOException, ParserConfigurationException, SAXException, TransformerException, ConnectException + public static String oaiResolveNamespaceToPrefix(String oaiSource, String MDNamespace) throws IOException, ParserConfigurationException, SAXException, TransformerException, ConnectException { String metaPrefix = null; // Query the OAI server for the metadata ListMetadataFormats lmf = new ListMetadataFormats(oaiSource); - + if (lmf != null) { Document lmfResponse = db.build(lmf.getDocument()); List mdFormats = lmfResponse.getRootElement().getChild("ListMetadataFormats", OAI_NS).getChildren("metadataFormat", OAI_NS); - + for (Element mdFormat : mdFormats) { - if (MDNamespace.equals(mdFormat.getChildText("metadataNamespace", OAI_NS))) + if (MDNamespace.equals(mdFormat.getChildText("metadataNamespace", OAI_NS))) { metaPrefix = mdFormat.getChildText("metadataPrefix", OAI_NS); break; } } } - - return metaPrefix; + + return metaPrefix; } - + /** - * Generate and send an email to the administrator. Prompted by errors encountered during harvesting. + * Generate and send an email to the administrator. Prompted by errors encountered during harvesting. * @param status the current status of the collection, usually HarvestedCollection.STATUS_OAI_ERROR or HarvestedCollection.STATUS_UNKNOWN_ERROR * @param ex the Exception that prompted this action */ - private void alertAdmin(int status, Exception ex) + private void alertAdmin(int status, Exception ex) { try { String recipient = ConfigurationManager.getProperty("alert.recipient"); - + if (recipient != null) { - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(Locale.getDefault(), "harvesting_error")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(Locale.getDefault(), "harvesting_error")); email.addRecipient(recipient); email.addArgument(targetCollection.getID()); email.addArgument(new Date()); @@ -851,22 +851,22 @@ public class OAIHarvester { } catch (Exception e) { log.warn("Unable to send email alert", e); } - + } - - - + + + /** - * Query the OAI-PMH provider for a specific metadata record. + * Query the OAI-PMH provider for a specific metadata record. * @param oaiSource the address of the OAI-PMH provider - * @param itemOaiId the OAI identifier of the target item + * @param itemOaiId the OAI identifier of the target item * @param metadataPrefix the OAI metadataPrefix of the desired metadata - * @return list of JDOM elements corresponding to the metadata entries in the located record. + * @return list of JDOM elements corresponding to the metadata entries in the located record. */ - private List getMDrecord(String oaiSource, String itemOaiId, String metadataPrefix) throws IOException, ParserConfigurationException, SAXException, TransformerException, HarvestingException + private List getMDrecord(String oaiSource, String itemOaiId, String metadataPrefix) throws IOException, ParserConfigurationException, SAXException, TransformerException, HarvestingException { GetRecord getRecord = new GetRecord(oaiSource,itemOaiId,metadataPrefix); - Set errorSet = new HashSet(); + Set errorSet = new HashSet(); // If the metadata is not available for this item, can the whole thing if (getRecord != null && getRecord.getErrors() != null && getRecord.getErrors().getLength() > 0) { for (int i=0; i verifyOAIharvester() { String oaiSource = harvestRow.getOaiSource(); String oaiSetId = harvestRow.getOaiSetId(); String metaPrefix = harvestRow.getHarvestMetadataConfig(); - + return verifyOAIharvester(oaiSource, oaiSetId, metaPrefix, true); } - + /** * Verify the existance of an OAI server with the specified set and supporting the provided metadata formats. * @param oaiSource the address of the OAI-PMH provider - * @param oaiSetId + * @param oaiSetId * @param metaPrefix * @param testORE whether the method should also check the PMH provider for ORE support * @return list of errors encountered during verification. Empty list indicates a "success" condition. */ - public static List verifyOAIharvester(String oaiSource, String oaiSetId, String metaPrefix, boolean testORE) + public static List verifyOAIharvester(String oaiSource, String oaiSetId, String metaPrefix, boolean testORE) { List errorSet = new ArrayList(); - + // First, make sure the metadata we need is supported by the target server Namespace ORE_NS = OAIHarvester.getORENamespace(); String OREOAIPrefix = null; Namespace DMD_NS = OAIHarvester.getDMDNamespace(metaPrefix); String DMDOAIPrefix = null; - + try { Identify idenTest = new Identify(oaiSource); } @@ -920,7 +920,7 @@ public class OAIHarvester { errorSet.add(OAI_ADDRESS_ERROR + ": OAI server could not be reached."); return errorSet; } - + try { OREOAIPrefix = OAIHarvester.oaiResolveNamespaceToPrefix(oaiSource, ORE_NS.getURI()); DMDOAIPrefix = OAIHarvester.oaiResolveNamespaceToPrefix(oaiSource, DMD_NS.getURI()); @@ -930,7 +930,7 @@ public class OAIHarvester { DMD_NS.getPrefix() + ":" + DMDOAIPrefix + ")"); return errorSet; } - + if (testORE && OREOAIPrefix == null) { errorSet.add(OAI_ORE_ERROR + ": The OAI server does not support ORE dissemination"); @@ -939,8 +939,8 @@ public class OAIHarvester { { errorSet.add(OAI_DMD_ERROR + ": The OAI server does not support dissemination in this format"); } - - // Now scan the sets and make sure the one supplied is in the list + + // Now scan the sets and make sure the one supplied is in the list boolean foundSet = false; try { //If we do not want to harvest from one set, then skip this. @@ -986,16 +986,16 @@ public class OAIHarvester { return errorSet; } - - + + /** - * Start harvest scheduler. + * Start harvest scheduler. */ public static synchronized void startNewScheduler() throws SQLException, AuthorizeException { Context c = new Context(); HarvestedCollection.exists(c); c.complete(); - + if (mainHarvestThread != null && harvester != null) { stopScheduler(); } @@ -1004,9 +1004,9 @@ public class OAIHarvester { mainHarvestThread = new Thread(harvester); mainHarvestThread.start(); } - + /** - * Stop an active harvest scheduler. + * Stop an active harvest scheduler. */ public static synchronized void stopScheduler() throws SQLException, AuthorizeException { synchronized(HarvestScheduler.lock) { @@ -1016,28 +1016,28 @@ public class OAIHarvester { mainHarvestThread = null; harvester = null; } - + /** - * Pause an active harvest scheduler. + * Pause an active harvest scheduler. */ public static void pauseScheduler() throws SQLException, AuthorizeException { synchronized(HarvestScheduler.lock) { HarvestScheduler.interrupt = HarvestScheduler.HARVESTER_INTERRUPT_PAUSE; HarvestScheduler.lock.notify(); - } + } } - + /** - * Resume a paused harvest scheduler. + * Resume a paused harvest scheduler. */ public static void resumeScheduler() throws SQLException, AuthorizeException { HarvestScheduler.interrupt = HarvestScheduler.HARVESTER_INTERRUPT_RESUME; } - + public static void resetScheduler() throws SQLException, AuthorizeException, IOException { Context context = new Context(); List cids = HarvestedCollection.findAll(context); - for (Integer cid : cids) + for (Integer cid : cids) { HarvestedCollection hc = HarvestedCollection.find(context, cid); hc.setHarvestStartTime(null); @@ -1046,14 +1046,14 @@ public class OAIHarvester { } context.commit(); } - - + + /** - * Exception class specifically assigned to recoverable errors that occur during harvesting. Throughout the harvest process, various exceptions - * are caught and turned into a HarvestingException. Uncaught exceptions are irrecoverable errors. + * Exception class specifically assigned to recoverable errors that occur during harvesting. Throughout the harvest process, various exceptions + * are caught and turned into a HarvestingException. Uncaught exceptions are irrecoverable errors. * @author alexey */ - public static class HarvestingException extends Exception + public static class HarvestingException extends Exception { public HarvestingException() { super(); @@ -1062,7 +1062,7 @@ public class OAIHarvester { public HarvestingException(String message, Throwable t) { super(message, t); } - + public HarvestingException(String message) { super(message); } @@ -1071,38 +1071,38 @@ public class OAIHarvester { super(t); } } - + /** - * The class responsible for scheduling harvesting cycles are regular intervals. + * The class responsible for scheduling harvesting cycles are regular intervals. * @author alexey */ - public static class HarvestScheduler implements Runnable + public static class HarvestScheduler implements Runnable { private EPerson harvestAdmin; private Context mainContext; - + public static final Object lock = new Object(); - + private static Stack harvestThreads; private static Integer maxActiveThreads; protected static volatile Integer activeThreads = 0; - + public static final int HARVESTER_STATUS_RUNNING = 1; public static final int HARVESTER_STATUS_SLEEPING = 2; public static final int HARVESTER_STATUS_PAUSED = 3; public static final int HARVESTER_STATUS_STOPPED = 4; - + public static final int HARVESTER_INTERRUPT_NONE = 0; public static final int HARVESTER_INTERRUPT_PAUSE = 1; public static final int HARVESTER_INTERRUPT_STOP = 2; public static final int HARVESTER_INTERRUPT_RESUME = 3; public static final int HARVESTER_INTERRUPT_INSERT_THREAD = 4; public static final int HARVESTER_INTERRUPT_KILL_THREAD = 5; - + private static int status = HARVESTER_STATUS_STOPPED; private static int interrupt = HARVESTER_INTERRUPT_NONE; private static Integer interruptValue = 0; - + private static long minHeartbeat; private static long maxHeartbeat; @@ -1132,7 +1132,7 @@ public class OAIHarvester { default: return("Automatic harvesting is not active. "); } } - + public HarvestScheduler() throws SQLException, AuthorizeException { mainContext = new Context(); String harvestAdminParam = ConfigurationManager.getProperty("harvester.eperson"); @@ -1141,9 +1141,9 @@ public class OAIHarvester { { harvestAdmin = EPerson.findByEmail(mainContext, harvestAdminParam); } - + harvestThreads = new Stack(); - + maxActiveThreads = ConfigurationManager.getIntProperty("oai", "harvester.maxThreads"); if (maxActiveThreads == 0) { @@ -1164,12 +1164,12 @@ public class OAIHarvester { public void run() { scheduleLoop(); } - + private void scheduleLoop() { long i=0; - while(true) + while(true) { - try + try { synchronized (HarvestScheduler.class) { switch (interrupt) @@ -1202,17 +1202,17 @@ public class OAIHarvester { } status = HARVESTER_STATUS_RUNNING; - + // Stage #1: if something is ready for harvest, push it onto the ready stack, mark it as "queued" mainContext = new Context(); List cids = HarvestedCollection.findReady(mainContext); log.info("Collections ready for immediate harvest: " + cids.toString()); - + for (Integer cid : cids) { addThread(cid); } - - // Stage #2: start up all the threads currently in the queue up to the maximum number + + // Stage #2: start up all the threads currently in the queue up to the maximum number while (!harvestThreads.isEmpty()) { synchronized(HarvestScheduler.class) { activeThreads++; @@ -1220,24 +1220,24 @@ public class OAIHarvester { Thread activeThread = new Thread(harvestThreads.pop()); activeThread.start(); log.info("Thread started: " + activeThread.toString()); - + /* Wait while the number of threads running is greater than or equal to max */ while (activeThreads >= maxActiveThreads) { /* Wait a second */ Thread.sleep(1000); } } - + // Finally, wait for the last few remaining threads to finish // TODO: this step might be unnecessary. Theoretically a single very long harvest process // could then lock out all the other ones from starting on their next iteration. // FIXME: also, this might lead to a situation when a single thread getting stuck without - // throwing an exception would shut down the whole scheduler + // throwing an exception would shut down the whole scheduler while (activeThreads != 0) { /* Wait a second */ Thread.sleep(1000); } - + // Commit everything try { mainContext.commit(); @@ -1246,15 +1246,15 @@ public class OAIHarvester { } catch (SQLException e) { e.printStackTrace(); mainContext.abort(); - } - - } + } + + } catch (Exception e) { log.error("Exception on iteration: " + i); e.printStackTrace(); } - - // Stage #3: figure out how long until the next iteration and wait + + // Stage #3: figure out how long until the next iteration and wait try { Context tempContext = new Context(); int nextCollectionId = HarvestedCollection.findOldestHarvest(tempContext); @@ -1275,75 +1275,75 @@ public class OAIHarvester { nextTime = calendar.getTime(); nextHarvest = nextTime.getTime() + - new Date().getTime(); } - + long upperBound = Math.min(nextHarvest,maxHeartbeat); long delay = Math.max(upperBound, minHeartbeat) + 1000; - - + + tempContext.complete(); - + status = HARVESTER_STATUS_SLEEPING; synchronized(lock) { lock.wait(delay); } - } + } catch (InterruptedException ie) { log.warn("Interrupt: " + ie.getMessage()); - } + } catch (SQLException e) { e.printStackTrace(); } - + i++; } } - - + + /** - * Adds a thread to the ready stack. Can also be called externally to queue up a collection - * for harvesting before it is "due" for another cycle. This allows starting a harvest process - * from the UI that still "plays nice" with these thread mechanics instead of making an - * asynchronous call to runHarvest(). + * Adds a thread to the ready stack. Can also be called externally to queue up a collection + * for harvesting before it is "due" for another cycle. This allows starting a harvest process + * from the UI that still "plays nice" with these thread mechanics instead of making an + * asynchronous call to runHarvest(). */ public static void addThread(int collecionID) throws SQLException, IOException, AuthorizeException { log.debug("****** Entered the addThread method. Active threads: " + harvestThreads.toString()); Context subContext = new Context(); //subContext.setCurrentUser(harvestAdmin); - + HarvestedCollection hc = HarvestedCollection.find(subContext, collecionID); hc.setHarvestStatus(HarvestedCollection.STATUS_QUEUED); hc.update(); subContext.commit(); - + HarvestThread ht = new HarvestThread(subContext, hc); - harvestThreads.push(ht); - + harvestThreads.push(ht); + log.debug("****** Queued up a thread. Active threads: " + harvestThreads.toString()); - log.info("Thread queued up: " + ht.toString()); + log.info("Thread queued up: " + ht.toString()); } - + } - + /** - * A harvester thread used to execute a single harvest cycle on a collection + * A harvester thread used to execute a single harvest cycle on a collection * @author alexey */ private static class HarvestThread extends Thread { Context context; HarvestedCollection hc; - - + + HarvestThread(Context context, HarvestedCollection hc) throws SQLException { this.context = context; this.hc = hc; } - + public void run() { log.info("Thread for collection " + hc.getCollectionId() + " starts."); - runHarvest(); + runHarvest(); } - - private void runHarvest() + + private void runHarvest() { Collection dso = null; try { @@ -1361,7 +1361,7 @@ public class OAIHarvester { log.error("General exception in thread: " + this.toString()); log.error(ex.getMessage() + " " + ex.getCause()); hc.setHarvestMessage("Error occured while generating an OAI response"); - hc.setHarvestStatus(HarvestedCollection.STATUS_UNKNOWN_ERROR); + hc.setHarvestStatus(HarvestedCollection.STATUS_UNKNOWN_ERROR); } finally { @@ -1378,12 +1378,12 @@ public class OAIHarvester { log.error("Unexpected exception while recovering from a harvesting error: " + e.getMessage(), e); context.abort(); } - + synchronized (HarvestScheduler.class) { HarvestScheduler.activeThreads--; - } - } - + } + } + log.info("Thread for collection " + hc.getCollectionId() + " completes."); } } diff --git a/dspace-api/src/main/java/org/dspace/search/DSIndexer.java b/dspace-api/src/main/java/org/dspace/search/DSIndexer.java index 69b6ea988b..78fccc7cfa 100644 --- a/dspace-api/src/main/java/org/dspace/search/DSIndexer.java +++ b/dspace-api/src/main/java/org/dspace/search/DSIndexer.java @@ -74,18 +74,18 @@ import org.dspace.app.util.Util; * collections, communities, etc. It is meant to either be invoked from the * command line (see dspace/bin/index-all) or via the indexContent() methods * within DSpace. - * + * * As of 1.4.2 this class has new incremental update of index functionality * and better detection of locked state thanks to Lucene 2.1 moving write.lock. * It will attempt to attain a lock on the index in the event that an update * is requested and will wait a maximum of 30 seconds (a worst case scenario) - * to attain the lock before giving up and logging the failure to log4j and - * to the DSpace administrator email account. - * + * to attain the lock before giving up and logging the failure to log4j and + * to the DSpace administrator email account. + * * The Administrator can choose to run DSIndexer in a cron that * repeats regularly, a failed attempt to index from the UI will be "caught" up * on in that cron. - * + * * @author Mark Diggory * @author Graham Triggs */ @@ -127,11 +127,11 @@ public class DSIndexer this.type = type; } } - + private static String indexDirectory = ConfigurationManager.getProperty("search.dir"); - + private static int maxfieldlength = -1; - + // TODO: Support for analyzers per language, or multiple indices /** The analyzer for this DSpace instance */ private static volatile Analyzer analyzer = null; @@ -154,13 +154,13 @@ public class DSIndexer }; static { - + // calculate maxfieldlength if (ConfigurationManager.getProperty("search.maxfieldlength") != null) { maxfieldlength = ConfigurationManager.getIntProperty("search.maxfieldlength"); } - + // read in indexes from the config ArrayList indexConfigList = new ArrayList(); @@ -169,24 +169,24 @@ public class DSIndexer { indexConfigList.add(ConfigurationManager.getProperty("search.index." + i)); } - + if (indexConfigList.size() > 0) { indexConfigArr = new IndexConfig[indexConfigList.size()]; - + for (int i = 0; i < indexConfigList.size(); i++) { indexConfigArr[i] = new IndexConfig(); String index = indexConfigList.get(i); - + String[] configLine = index.split(":"); - + indexConfigArr[i].indexName = configLine[0]; - + // Get the schema, element and qualifier for the index // TODO: Should check valid schema, element, qualifier? String[] parts = configLine[1].split("\\."); - + switch (parts.length) { case 3: @@ -208,7 +208,7 @@ public class DSIndexer } } } - + /* * Increase the default write lock so that Indexing can be interrupted. */ @@ -246,10 +246,10 @@ public class DSIndexer /** * If the handle for the "dso" already exists in the index, and - * the "dso" has a lastModified timestamp that is newer than - * the document in the index then it is updated, otherwise a + * the "dso" has a lastModified timestamp that is newer than + * the document in the index then it is updated, otherwise a * new document is added. - * + * * @param context Users Context * @param dso DSpace Object (Item, Collection or Community * @throws SQLException @@ -261,10 +261,10 @@ public class DSIndexer } /** * If the handle for the "dso" already exists in the index, and - * the "dso" has a lastModified timestamp that is newer than - * the document in the index then it is updated, otherwise a + * the "dso" has a lastModified timestamp that is newer than + * the document in the index then it is updated, otherwise a * new document is added. - * + * * @param context Users Context * @param dso DSpace Object (Item, Collection or Community * @param force Force update even if not stale. @@ -290,7 +290,7 @@ public class DSIndexer /** * unIndex removes an Item, Collection, or Community only works if the * DSpaceObject has a handle (uses the handle for its unique ID) - * + * * @param context DSpace context * @param dso DSpace Object, can be Community, Item, or Collection * @throws SQLException @@ -311,9 +311,9 @@ public class DSIndexer /** * Unindex a Document in the Lucene Index. - * + * * @param context - * @param handle + * @param handle * @throws SQLException * @throws IOException */ @@ -336,7 +336,7 @@ public class DSIndexer // handle!"); } } - + /** * reIndexContent removes something from the index, then re-indexes it * @@ -356,10 +356,10 @@ public class DSIndexer emailException(exception); } } - + /** * create full index - wiping old index - * + * * @param c context to use */ public static void createIndex(Context c) throws SQLException, IOException @@ -367,15 +367,15 @@ public class DSIndexer /* Create a new index, blowing away the old. */ openIndex(true).close(); - + /* Reindex all content preemptively. */ DSIndexer.updateIndex(c, true); } - + /** - * Optimize the existing index. Important to do regularly to reduce + * Optimize the existing index. Important to do regularly to reduce * filehandle usage and keep performance fast! - * + * * @param c Users Context * @throws SQLException * @throws IOException @@ -396,13 +396,13 @@ public class DSIndexer } /** - * When invoked as a command-line tool, creates, updates, removes + * When invoked as a command-line tool, creates, updates, removes * content from the whole index * * @param args * the command-line arguments, none used - * @throws IOException - * @throws SQLException + * @throws IOException + * @throws SQLException */ public static void main(String[] args) throws SQLException, IOException { @@ -508,25 +508,25 @@ public class DSIndexer * Iterates over all Items, Collections and Communities. And updates * them in the index. Uses decaching to control memory footprint. * Uses indexContent and isStale ot check state of item in index. - * + * * @param context */ public static void updateIndex(Context context) { updateIndex(context,false); } - + /** * Iterates over all Items, Collections and Communities. And updates * them in the index. Uses decaching to control memory footprint. * Uses indexContent and isStale to check state of item in index. - * + * * At first it may appear counterintuitive to have an IndexWriter/Reader * opened and closed on each DSO. But this allows the UI processes * to step in and attain a lock and write to the index even if other * processes/jvms are running a reindex. - * + * * @param context - * @param force + * @param force */ public static void updateIndex(Context context, boolean force) { try @@ -568,19 +568,19 @@ public class DSIndexer log.error(e.getMessage(), e); } } - + /** - * Iterates over all documents in the Lucene index and verifies they + * Iterates over all documents in the Lucene index and verifies they * are in database, if not, they are removed. - * + * * @param context - * @throws IOException - * @throws SQLException + * @throws IOException + * @throws SQLException */ public static void cleanIndex(Context context) throws IOException, SQLException { IndexReader reader = DSQuery.getIndexReader(); - + for(int i = 0 ; i < reader.numDocs(); i++) { if(!reader.isDeleted(i)) @@ -610,7 +610,7 @@ public class DSIndexer } } } - + /** * Get the Lucene analyzer to use according to current configuration (or * default). TODO: Should have multiple analyzers (and maybe indices?) for @@ -844,7 +844,7 @@ public class DSIndexer .getProperty("alert.recipient"); if (recipient != null) { - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(Locale.getDefault(), "internal_error")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(Locale.getDefault(), "internal_error")); email.addRecipient(recipient); email.addArgument(ConfigurationManager .getProperty("dspace.url")); @@ -871,11 +871,11 @@ public class DSIndexer } } - + /** * Is stale checks the lastModified time stamp in the database and the index * to determine if the index is stale. - * + * * @param lastModified * @throws SQLException * @throws IOException @@ -883,14 +883,14 @@ public class DSIndexer private static boolean requiresIndexing(Term t, Date lastModified) throws SQLException, IOException { - + boolean reindexItem = false; boolean inIndex = false; - + IndexReader ir = DSQuery.getIndexReader(); - + TermDocs docs = ir.termDocs(t); - + while(docs.next()) { inIndex = true; @@ -899,7 +899,7 @@ public class DSIndexer Field lastIndexed = doc.getField(LAST_INDEXED_FIELD); - if (lastIndexed == null || Long.parseLong(lastIndexed.stringValue()) < + if (lastIndexed == null || Long.parseLong(lastIndexed.stringValue()) < lastModified.getTime()) { reindexItem = true; } @@ -933,7 +933,7 @@ public class DSIndexer { writer.setMaxFieldLength(maxfieldlength); } - + return writer; } @@ -1069,7 +1069,7 @@ public class DSIndexer mydc = item.getMetadata(indexConfigArr[i].schema, indexConfigArr[i].element, indexConfigArr[i].qualifier, Item.ANY); } - + //Index the controlled vocabularies localized display values for all localized input-forms.xml (e.g. input-forms_el.xml) if ("inputform".equalsIgnoreCase(indexConfigArr[i].type)){ @@ -1110,7 +1110,7 @@ public class DSIndexer } - + for (j = 0; j < mydc.length; j++) { if (!StringUtils.isEmpty(mydc[j].value)) @@ -1389,7 +1389,7 @@ public class DSIndexer /** * Helper function to retrieve a date using a best guess of the potential date encodings on a field - * + * * @param t * @return */ @@ -1441,7 +1441,7 @@ public class DSIndexer log.error("Unable to parse date format", pe); } } - + return null; } diff --git a/dspace-api/src/main/java/org/dspace/workflow/WorkflowManager.java b/dspace-api/src/main/java/org/dspace/workflow/WorkflowManager.java index 350dacf80a..25409ec5a3 100644 --- a/dspace-api/src/main/java/org/dspace/workflow/WorkflowManager.java +++ b/dspace-api/src/main/java/org/dspace/workflow/WorkflowManager.java @@ -46,26 +46,26 @@ import org.dspace.utils.DSpace; /** * Workflow state machine - * + * * Notes: - * + * * Determining item status from the database: - * + * * When an item has not been submitted yet, it is in the user's personal * workspace (there is a row in PersonalWorkspace pointing to it.) - * + * * When an item is submitted and is somewhere in a workflow, it has a row in the * WorkflowItem table pointing to it. The state of the workflow can be * determined by looking at WorkflowItem.getState() - * + * * When a submission is complete, the WorkflowItem pointing to the item is * destroyed and the archive() method is called, which hooks the item up to the * archive. - * + * * Notification: When an item enters a state that requires notification, * (WFSTATE_STEP1POOL, WFSTATE_STEP2POOL, WFSTATE_STEP3POOL,) the workflow needs * to notify the appropriate groups that they have a pending task to claim. - * + * * Revealing lists of approvers, editors, and reviewers. A method could be added * to do this, but it isn't strictly necessary. (say public List * getStateEPeople( WorkflowItem wi, int state ) could return people affected by @@ -138,7 +138,7 @@ public class WorkflowManager /** * startWorkflow() begins a workflow - in a single transaction do away with * the PersonalWorkspace entry and turn it into a WorkflowItem. - * + * * @param c * Context * @param wsi @@ -176,7 +176,7 @@ public class WorkflowManager // now get the workflow started wfi.setState(WFSTATE_SUBMIT); - advance(c, wfi, null); + advance(c, wfi, null); // Return the workflow item return wfi; @@ -201,7 +201,7 @@ public class WorkflowManager * getOwnedTasks() returns a List of WorkflowItems containing the tasks * claimed and owned by an EPerson. The GUI displays this info on the * MyDSpace page. - * + * * @param e * The EPerson we want to fetch owned tasks for. */ @@ -212,7 +212,7 @@ public class WorkflowManager String myquery = "SELECT * FROM WorkflowItem WHERE owner= ? "; - TableRowIterator tri = DatabaseManager.queryTable(c, + TableRowIterator tri = DatabaseManager.queryTable(c, "workflowitem", myquery,e.getID()); try @@ -236,7 +236,7 @@ public class WorkflowManager /** * getPooledTasks() returns a List of WorkflowItems an EPerson could claim * (as a reviewer, etc.) for display on a user's MyDSpace page. - * + * * @param e * The Eperson we want to fetch the pooled tasks for. */ @@ -265,13 +265,13 @@ public class WorkflowManager tri.close(); } } - + return mylist; } /** * claim() claims a workflow task for an EPerson - * + * * @param wi * WorkflowItem to do the claim on * @param e @@ -322,7 +322,7 @@ public class WorkflowManager * the item arrives at the submit state, then remove the WorkflowItem and * call the archive() method to put it in the archive, and email notify the * submitter of a successful submission - * + * * @param c * Context * @param wi @@ -335,26 +335,26 @@ public class WorkflowManager { advance(c, wi, e, true, true); } - + /** * advance() sends an item forward in the workflow (reviewers, * approvers, and editors all do an 'approve' to move the item forward) if * the item arrives at the submit state, then remove the WorkflowItem and * call the archive() method to put it in the archive, and email notify the * submitter of a successful submission - * + * * @param c * Context * @param wi * WorkflowItem do do the approval on * @param e * EPerson doing the approval - * + * * @param curate * boolean indicating whether curation tasks should be done - * + * * @param record - * boolean indicating whether to record action + * boolean indicating whether to record action */ public static boolean advance(Context c, WorkflowItem wi, EPerson e, boolean curate, boolean record) @@ -362,7 +362,7 @@ public class WorkflowManager { int taskstate = wi.getState(); boolean archived = false; - + // perform curation tasks if needed if (curate && WorkflowCurator.needsCuration(wi)) { @@ -381,9 +381,9 @@ public class WorkflowManager { case WFSTATE_SUBMIT: archived = doState(c, wi, WFSTATE_STEP1POOL, e); - + break; - + case WFSTATE_STEP1: // authorize DSpaceActions.SUBMIT_REVIEW @@ -430,7 +430,7 @@ public class WorkflowManager /** * unclaim() returns an owned task/item to the pool - * + * * @param c * Context * @param wi @@ -481,7 +481,7 @@ public class WorkflowManager * abort() aborts a workflow, completely deleting it (administrator do this) * (it will basically do a reject from any state - the item ends up back in * the user's PersonalWorkspace - * + * * @param c * Context * @param wi @@ -540,7 +540,7 @@ public class WorkflowManager { // get a list of all epeople in group (or any subgroups) EPerson[] epa = Group.allMembers(c, mygroup); - + // there were reviewers, change the state // and add them to the list createTasks(c, wi, epa); @@ -582,7 +582,7 @@ public class WorkflowManager { //get a list of all epeople in group (or any subgroups) EPerson[] epa = Group.allMembers(c, mygroup); - + // there were approvers, change the state // timestamp, and add them to the list createTasks(c, wi, epa); @@ -619,7 +619,7 @@ public class WorkflowManager { // get a list of all epeople in group (or any subgroups) EPerson[] epa = Group.allMembers(c, mygroup); - + // there were editors, change the state // timestamp, and add them to the list createTasks(c, wi, epa); @@ -707,7 +707,7 @@ public class WorkflowManager * Commit the contained item to the main archive. The item is associated * with the relevant collection, added to the search index, and any other * tasks such as assigning dates are performed. - * + * * @return the fully archived item. */ private static Item archive(Context c, WorkflowItem wfi) @@ -742,8 +742,8 @@ public class WorkflowManager EPerson ep = i.getSubmitter(); // Get the Locale Locale supportedLocale = I18nUtil.getEPersonLocale(ep); - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive")); - + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive")); + // Get the item handle to email to user String handle = HandleManager.findHandle(c, i); @@ -780,7 +780,7 @@ public class WorkflowManager /** * Return the workflow item to the workspace of the submitter. The workflow * item is removed, and a workspace item created. - * + * * @param c * Context * @param wfi @@ -825,7 +825,7 @@ public class WorkflowManager * rejects an item - rejection means undoing a submit - WorkspaceItem is * created, and the WorkflowItem is removed, user is emailed * rejection_message. - * + * * @param c * Context * @param wi @@ -899,10 +899,10 @@ public class WorkflowManager static void deleteTasks(Context c, WorkflowItem wi) throws SQLException { String myrequest = "DELETE FROM TaskListItem WHERE workflow_id= ? "; - + DatabaseManager.updateQuery(c, myrequest, wi.getID()); } - + // send notices of curation activity public static void notifyOfCuration(Context c, WorkflowItem wi, EPerson[] epa, String taskName, String action, String message) throws SQLException, IOException @@ -921,7 +921,7 @@ public class WorkflowManager for (int i = 0; i < epa.length; i++) { Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]); - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "flowtask_notify")); email.addArgument(title); email.addArgument(coll.getMetadata("name")); @@ -935,7 +935,7 @@ public class WorkflowManager } catch (MessagingException e) { - log.warn(LogManager.getHeader(c, "notifyOfCuration", "cannot email users" + + log.warn(LogManager.getHeader(c, "notifyOfCuration", "cannot email users" + " of workflow_item_id" + wi.getID())); } } @@ -971,7 +971,7 @@ public class WorkflowManager for (int i = 0; i < epa.length; i++) { Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]); - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task")); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(submitter); @@ -981,17 +981,17 @@ public class WorkflowManager { case WFSTATE_STEP1POOL: message = messages.getString("org.dspace.workflow.WorkflowManager.step1"); - + break; - + case WFSTATE_STEP2POOL: message = messages.getString("org.dspace.workflow.WorkflowManager.step2"); - + break; - + case WFSTATE_STEP3POOL: message = messages.getString("org.dspace.workflow.WorkflowManager.step3"); - + break; } email.addArgument(message); @@ -1030,7 +1030,7 @@ public class WorkflowManager // Get rejector's name String rejector = getEPersonName(e); Locale supportedLocale = I18nUtil.getEPersonLocale(e); - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject")); email.addRecipient(getSubmitterEPerson(wi).getEmail()); email.addArgument(title); @@ -1072,7 +1072,7 @@ public class WorkflowManager /** * get the title of the item in this workflow - * + * * @param wi the workflow item object */ public static String getItemTitle(WorkflowItem wi) throws SQLException @@ -1093,7 +1093,7 @@ public class WorkflowManager /** * get the name of the eperson who started this workflow - * + * * @param wi the workflow item */ public static String getSubmitterName(WorkflowItem wi) throws SQLException diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java index 55ec75a7e6..6cf9f176d0 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java @@ -156,7 +156,7 @@ public class WorkflowUtils extends Util{ if (recipient != null) { - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), "internal_error")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), "internal_error")); email.addRecipient(recipient); email.addArgument(ConfigurationManager diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowManager.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowManager.java index ad42112961..2e1ab1c4dd 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowManager.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowManager.java @@ -107,7 +107,7 @@ public class XmlWorkflowManager { // suppress email, and delete key noEMail.remove(wfi.getItem().getID()); } else { - Email mail = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), emailTemplate)); + Email mail = Email.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), emailTemplate)); for (String argument : arguments) { mail.addArgument(argument); } @@ -396,7 +396,7 @@ public class XmlWorkflowManager { EPerson ep = i.getSubmitter(); // Get the Locale Locale supportedLocale = I18nUtil.getEPersonLocale(ep); - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive")); // Get the item handle to email to user String handle = HandleManager.findHandle(c, i); @@ -856,7 +856,7 @@ public class XmlWorkflowManager { // Get rejector's name String rejector = getEPersonName(e); Locale supportedLocale = I18nUtil.getEPersonLocale(e); - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject")); email.addRecipient(wi.getSubmitter().getEmail()); email.addArgument(title); diff --git a/dspace-api/src/test/java/org/dspace/content/CollectionTest.java b/dspace-api/src/test/java/org/dspace/content/CollectionTest.java index f33647b918..d754cd948f 100644 --- a/dspace-api/src/test/java/org/dspace/content/CollectionTest.java +++ b/dspace-api/src/test/java/org/dspace/content/CollectionTest.java @@ -20,8 +20,8 @@ import static org.hamcrest.CoreMatchers.*; import mockit.*; import org.dspace.app.util.AuthorizeUtil; import org.dspace.authorize.AuthorizeManager; -import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; +import org.dspace.core.LicenseManager; /** * Unit Tests for class Collection @@ -198,7 +198,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest */ @Test @Override - public void testGetID() + public void testGetID() { assertTrue("testGetID 0", c.getID() >= 1); } @@ -208,7 +208,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest */ @Test @Override - public void testGetHandle() + public void testGetHandle() { //default instance has a random handle assertTrue("testGetHandle 0", c.getHandle().contains("123456789/")); @@ -662,17 +662,17 @@ public class CollectionTest extends AbstractDSpaceObjectTest * Test of getLicense method, of class Collection. */ @Test - public void testGetLicense() + public void testGetLicense() { assertThat("testGetLicense 0", c.getLicense(), notNullValue()); - assertThat("testGetLicense 1", c.getLicense(), equalTo(ConfigurationManager.getDefaultSubmissionLicense())); + assertThat("testGetLicense 1", c.getLicense(), equalTo(LicenseManager.getDefaultSubmissionLicense())); } /** * Test of getLicenseCollection method, of class Collection. */ @Test - public void testGetLicenseCollection() + public void testGetLicenseCollection() { assertThat("testGetLicenseCollection 0", c.getLicenseCollection(), notNullValue()); assertThat("testGetLicenseCollection 1", c.getLicenseCollection(), equalTo("")); @@ -682,7 +682,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest * Test of hasCustomLicense method, of class Collection. */ @Test - public void testHasCustomLicense() + public void testHasCustomLicense() { assertFalse("testHasCustomLicense 0", c.hasCustomLicense()); } @@ -691,7 +691,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest * Test of setLicense method, of class Collection. */ @Test - public void testSetLicense() + public void testSetLicense() { String license = "license for test"; c.setLicense(license); @@ -705,7 +705,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest * Test of getTemplateItem method, of class Collection. */ @Test - public void testGetTemplateItem() throws Exception + public void testGetTemplateItem() throws Exception { assertThat("testGetTemplateItem 0", c.getTemplateItem(), nullValue()); } @@ -1336,7 +1336,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest assertFalse("testCanEditBooleanNoAuth_boolean 0",c.canEditBoolean(false)); } - + /** * Test of canEditBoolean method, of class Collection. */ @@ -1789,7 +1789,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest */ @Test @Override - public void testGetType() + public void testGetType() { assertThat("testGetType 0", c.getType(), equalTo(Constants.COLLECTION)); } @@ -1798,7 +1798,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest * Test of findAuthorized method, of class Collection. */ @Test - public void testFindAuthorized() throws Exception + public void testFindAuthorized() throws Exception { context.turnOffAuthorisationSystem(); Community com = Community.create(null, context); diff --git a/dspace-api/src/test/java/org/dspace/content/LicenseUtilsTest.java b/dspace-api/src/test/java/org/dspace/content/LicenseUtilsTest.java index f85bb1c997..1b00cced4a 100644 --- a/dspace-api/src/test/java/org/dspace/content/LicenseUtilsTest.java +++ b/dspace-api/src/test/java/org/dspace/content/LicenseUtilsTest.java @@ -13,13 +13,13 @@ import java.sql.SQLException; import java.util.HashMap; import org.dspace.authorize.AuthorizeException; import org.dspace.eperson.EPerson; -import org.dspace.core.ConfigurationManager; import org.dspace.AbstractUnitTest; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import org.apache.log4j.Logger; +import org.dspace.core.LicenseManager; import org.junit.*; import static org.junit.Assert.* ; import static org.hamcrest.CoreMatchers.*; @@ -81,7 +81,7 @@ public class LicenseUtilsTest extends AbstractUnitTest String templateLong = "Template license: %1$s %2$s %3$s %5$s %6$s %8$s %9$s %10$s %11$s"; String templateResult = "Template license: first name last name test@email.com "; String templateLongResult = "Template license: first name last name test@email.com arg1 arg2 arg3 arg4"; - String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); + String defaultLicense = LicenseManager.getDefaultSubmissionLicense(); context.turnOffAuthorisationSystem(); //TODO: the tested method doesn't verify the input, will throw NPE if any parameter is null @@ -154,10 +154,10 @@ public class LicenseUtilsTest extends AbstractUnitTest additionalInfo = new LinkedHashMap(); additionalInfo.put("arg1", "arg1"); additionalInfo.put("arg2", "arg2"); - additionalInfo.put("arg3", "arg3"); + additionalInfo.put("arg3", "arg3"); additionalInfo.put("arg4", "arg4"); assertThat("testGetLicenseText_5args 5", LicenseUtils.getLicenseText(locale, collection, item, person, additionalInfo), equalTo(templateLongResult)); - + context.restoreAuthSystemState(); } @@ -175,7 +175,7 @@ public class LicenseUtilsTest extends AbstractUnitTest String template = "Template license: %1$s %2$s %3$s %5$s %6$s"; String templateResult = "Template license: first name last name test@email.com "; - String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); + String defaultLicense = LicenseManager.getDefaultSubmissionLicense(); context.turnOffAuthorisationSystem(); //TODO: the tested method doesn't verify the input, will throw NPE if any parameter is null @@ -207,7 +207,7 @@ public class LicenseUtilsTest extends AbstractUnitTest person = EPerson.create(context); person.setFirstName("first name"); person.setLastName("last name"); - person.setEmail("test@email.com"); + person.setEmail("test@email.com"); assertThat("testGetLicenseText_5args 3", LicenseUtils.getLicenseText(locale, collection, item, person), equalTo(templateResult)); locale = Locale.GERMAN; @@ -227,11 +227,11 @@ public class LicenseUtilsTest extends AbstractUnitTest * Test of grantLicense method, of class LicenseUtils. */ @Test - public void testGrantLicense() throws Exception + public void testGrantLicense() throws Exception { context.turnOffAuthorisationSystem(); Item item = Item.create(context); - String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); + String defaultLicense = LicenseManager.getDefaultSubmissionLicense(); LicenseUtils.grantLicense(context, item, defaultLicense); diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedbackServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedbackServlet.java index b8328b94f3..0f3c625242 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedbackServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedbackServlet.java @@ -109,7 +109,7 @@ public class FeedbackServlet extends DSpaceServlet // All data is there, send the email try { - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback")); email.addRecipient(ConfigurationManager .getProperty("feedback.recipient")); diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SuggestServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SuggestServlet.java index 1781919a29..3ae850b93f 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SuggestServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SuggestServlet.java @@ -77,7 +77,7 @@ public class SuggestServlet extends DSpaceServlet // Obtain information from request String handle = request.getParameter("handle"); - + // Lookup Item title & collection String title = null; String collName = null; @@ -85,7 +85,7 @@ public class SuggestServlet extends DSpaceServlet { Item item = (Item) HandleManager.resolveToObject(context, handle); if (item != null) - { + { DCValue[] titleDC = item.getDC("title", null, Item.ANY); if (titleDC != null && titleDC.length > 0) { @@ -111,18 +111,18 @@ public class SuggestServlet extends DSpaceServlet collName = ""; } request.setAttribute("suggest.title", title); - + // User email from context EPerson currentUser = context.getCurrentUser(); String authEmail = null; String userName = null; - + if (currentUser != null) { authEmail = currentUser.getEmail(); userName = currentUser.getFullName(); - } - + } + if (request.getParameter("submit") != null) { String recipAddr = request.getParameter("recip_email"); @@ -177,13 +177,13 @@ public class SuggestServlet extends DSpaceServlet } String itemUri = HandleManager.getCanonicalForm(handle); String itemUrl = HandleManager.resolveToURL(context,handle); - String message = request.getParameter("message"); + String message = request.getParameter("message"); String siteName = ConfigurationManager.getProperty("dspace.name"); // All data is there, send the email try { - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "suggest")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "suggest")); email.addRecipient(recipAddr); // recipient address email.addArgument(recipName); // 1st arg - recipient name email.addArgument(senderName); // 2nd arg - sender name @@ -192,14 +192,14 @@ public class SuggestServlet extends DSpaceServlet email.addArgument(itemUri); // 5th arg - item handle URI email.addArgument(itemUrl); // 6th arg - item local URL email.addArgument(collName); // 7th arg - collection name - email.addArgument(message); // 8th arg - user comments - + email.addArgument(message); // 8th arg - user comments + // Set sender's address as 'reply-to' address if supplied if ( senderAddr != null && ! "".equals(senderAddr)) { email.setReplyTo(senderAddr); } - + // Only actually send the email if feature is enabled if (ConfigurationManager.getBooleanProperty("webui.suggest.enable", false)) { @@ -226,7 +226,7 @@ public class SuggestServlet extends DSpaceServlet log.info(LogManager.getHeader(context, "show_suggest_form", "problem=false")); request.setAttribute("authenticated.email", authEmail); request.setAttribute("eperson.name", userName); - JSPManager.showJSP(request, response, "/suggest/suggest.jsp"); //asd + JSPManager.showJSP(request, response, "/suggest/suggest.jsp"); //asd } } @@ -236,5 +236,5 @@ public class SuggestServlet extends DSpaceServlet { // Treat as a GET doDSGet(context, request, response); - } + } } diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/LicenseEditServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/LicenseEditServlet.java index 3feaae990c..a8cb206818 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/LicenseEditServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/LicenseEditServlet.java @@ -20,18 +20,19 @@ import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; -import org.dspace.core.I18nUtil; +import org.dspace.core.I18nUtil; +import org.dspace.core.LicenseManager; /** * Servlet for editing the default license - * + * * @author Stuart Lewis */ public class LicenseEditServlet extends DSpaceServlet { /** * Handle GET requests. This does nothing but forwards - * the request on to the POST handler. + * the request on to the POST handler. */ protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, @@ -59,7 +60,7 @@ public class LicenseEditServlet extends DSpaceServlet else if (!button.equals("submit_save")) { // Get the existing text from the ConfigurationManager - String license = ConfigurationManager.getLicenseText(I18nUtil.getDefaultLicense(c)); + String license = LicenseManager.getLicenseText(I18nUtil.getDefaultLicense(c)); // Pass the existing license back to the JSP request.setAttribute("license", license); @@ -76,11 +77,11 @@ public class LicenseEditServlet extends DSpaceServlet if (license.trim().equals("")) { // Get the existing text from the ConfigurationManager - license = ConfigurationManager.getLicenseText(I18nUtil.getDefaultLicense(c)); + license = LicenseManager.getLicenseText(I18nUtil.getDefaultLicense(c)); // Pass the existing license back to the JSP request.setAttribute("license", license); - + // Pass the 'empty' message back request.setAttribute("empty", "true"); @@ -90,14 +91,14 @@ public class LicenseEditServlet extends DSpaceServlet else { // Write the string out to file - ConfigurationManager.writeLicenseFile(I18nUtil.getDefaultLicense(c), license); - + LicenseManager.writeLicenseFile(I18nUtil.getDefaultLicense(c), license); + // Pass the existing license back to the JSP request.setAttribute("license", license); - + // Pass the 'edited' message back request.setAttribute("edited", "true"); - + // Show edit page JSPManager.showJSP(request, response, "/dspace-admin/license-edit.jsp"); } diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/NewsEditServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/NewsEditServlet.java index e2f3fb32a6..513cc84529 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/NewsEditServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/NewsEditServlet.java @@ -20,10 +20,11 @@ import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; +import org.dspace.core.NewsManager; /** * Servlet for editing the front page news - * + * * @author gcarpent */ public class NewsEditServlet extends DSpaceServlet @@ -47,11 +48,11 @@ public class NewsEditServlet extends DSpaceServlet //Are we editing the top news or the sidebar news? String position = request.getParameter("position"); - + if (button.equals("submit_edit")) { //get the existing text from the file - news = ConfigurationManager.readNewsFile(position); + news = NewsManager.readNewsFile(position); //pass the position back to the JSP request.setAttribute("position", position); @@ -69,7 +70,7 @@ public class NewsEditServlet extends DSpaceServlet news = (String) request.getParameter("news"); //write the string out to file - ConfigurationManager.writeNewsFile(position, news); + NewsManager.writeNewsFile(position, news); JSPManager .showJSP(request, response, "/dspace-admin/news-main.jsp"); diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/UIUtil.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/UIUtil.java index dbd518f447..12df5f9829 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/UIUtil.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/UIUtil.java @@ -40,7 +40,7 @@ import org.dspace.eperson.EPerson; /** * Miscellaneous UI utility methods - * + * * @author Robert Tansley * @version $Revision$ */ @@ -51,7 +51,7 @@ public class UIUtil extends Util /** log4j category */ public static final Logger log = Logger.getLogger(UIUtil.class); - + /** * Pattern used to get file.ext from filename (which can be a path) */ @@ -62,20 +62,20 @@ public class UIUtil extends Util * for this HTTP request, it is re-used, otherwise it is created. If a user * has authenticated with the system, the current user of the context is set * appropriately. - * + * * @param request * the HTTP request - * + * * @return a context object */ public static Context obtainContext(HttpServletRequest request) throws SQLException { - + //Set encoding to UTF-8, if not set yet //This avoids problems of using the HttpServletRequest - //in the getSpecialGroups() for an AuthenticationMethod, - //which causes the HttpServletRequest to default to + //in the getSpecialGroups() for an AuthenticationMethod, + //which causes the HttpServletRequest to default to //non-UTF-8 encoding. try { @@ -88,9 +88,9 @@ public class UIUtil extends Util { log.error("Unable to set encoding to UTF-8.", e); } - + Context c = (Context) request.getAttribute("dspace.context"); - + if (c == null) { @@ -149,7 +149,7 @@ public class UIUtil extends Util // Store the context in the request request.setAttribute("dspace.context", c); } - + // Set the locale to be used Locale sessionLocale = getSessionLocale(request); Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale); @@ -162,10 +162,10 @@ public class UIUtil extends Util * Get the current community location, that is, where the user "is". This * returns null if there is no location, i.e. "all of DSpace" * is the location. - * + * * @param request * current HTTP request - * + * * @return the current community location, or null */ public static Community getCommunityLocation(HttpServletRequest request) @@ -177,10 +177,10 @@ public class UIUtil extends Util * Get the current collection location, that is, where the user "is". This * returns null if there is no collection location, i.e. the location is * "all of DSpace" or a community. - * + * * @param request * current HTTP request - * + * * @return the current collection location, or null */ public static Collection getCollectionLocation(HttpServletRequest request) @@ -193,7 +193,7 @@ public class UIUtil extends Util * later use. This is necessary because forwarding a request removes this * information. The attribute is only written if it hasn't been before; thus * it can be called after a forward safely. - * + * * @param request * the HTTP request */ @@ -216,10 +216,10 @@ public class UIUtil extends Util /** * Get the original request URL. - * + * * @param request * the HTTP request - * + * * @return the original request URL */ public static String getOriginalURL(HttpServletRequest request) @@ -232,7 +232,7 @@ public class UIUtil extends Util /** * Write a human-readable version of a DCDate. - * + * * @param d * the date * @param time @@ -240,8 +240,8 @@ public class UIUtil extends Util * @param localTime * if true, adjust for local timezone, otherwise GMT * @param request - * the servlet request - * + * the servlet request + * * @return the date in a human-readable form. */ public static String displayDate(DCDate d, boolean time, boolean localTime, HttpServletRequest request) @@ -252,7 +252,7 @@ public class UIUtil extends Util /** * Return a string for logging, containing useful information about the * current request - the URL, the method and parameters. - * + * * @param request * the request object. * @return a multi-line string containing information about the request. @@ -288,15 +288,15 @@ public class UIUtil extends Util return report.toString(); } - - + + /** * Get the Locale for a session according to the user's language selection or language preferences. * Order of selection * - language selected via UI * - language as set by application * - language browser default - * + * * @param request * the request Object * @return supportedLocale @@ -314,8 +314,8 @@ public class UIUtil extends Util /* get session locale according to user selection */ sessionLocale = new Locale(paramLocale); } - - + + if (sessionLocale == null) { /* get session locale set by application */ @@ -331,17 +331,17 @@ public class UIUtil extends Util { sessionLocale = request.getLocale(); } - + if (sessionLocale == null) { sessionLocale = I18nUtil.DEFAULTLOCALE; } supportedLocale = I18nUtil.getSupportedLocale(sessionLocale); - - return supportedLocale; - } - + return supportedLocale; + } + + /** * Send an alert to the designated "alert recipient" - that is, when a * database error or internal error occurs, this person is sent an e-mail @@ -354,7 +354,7 @@ public class UIUtil extends Util * This method "swallows" any exception that might occur - it will just be * logged. This is because this method will usually be invoked as part of an * error handling routine anyway. - * + * * @param request * the HTTP request leading to the error * @param exception @@ -374,7 +374,7 @@ public class UIUtil extends Util if (recipient != null) { - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, "internal_error")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(locale, "internal_error")); email.addRecipient(recipient); email.addArgument(ConfigurationManager .getProperty("dspace.url")); @@ -406,7 +406,7 @@ public class UIUtil extends Util { log.warn("No context, the database might be down or the connection pool exhausted."); } - + if (user != null) { email.addArgument(user.getFullName() + " (" + user.getEmail() + ")"); @@ -425,10 +425,10 @@ public class UIUtil extends Util log.warn("Unable to send email alert", e); } } - + /** * Evaluate filename and client and encode appropriate disposition - * + * * @param filename * @param request * @param response @@ -437,31 +437,31 @@ public class UIUtil extends Util public static void setBitstreamDisposition(String filename, HttpServletRequest request, HttpServletResponse response) { - + String name = filename; - + Matcher m = p.matcher(name); - + if (m.find() && !m.group().equals("")) { name = m.group(); } - try + try { String agent = request.getHeader("USER-AGENT"); - if (null != agent && -1 != agent.indexOf("MSIE")) + if (null != agent && -1 != agent.indexOf("MSIE")) { name = URLEncoder.encode(name, "UTF8"); - } - else if (null != agent && -1 != agent.indexOf("Mozilla")) + } + else if (null != agent && -1 != agent.indexOf("Mozilla")) { name = MimeUtility.encodeText(name, "UTF8", "B"); - } + } - } - catch (UnsupportedEncodingException e) + } + catch (UnsupportedEncodingException e) { log.error(e.getMessage(),e); } diff --git a/dspace-lni/src/main/java/org/dspace/app/dav/DAVSite.java b/dspace-lni/src/main/java/org/dspace/app/dav/DAVSite.java index 7b051e237f..ecb9ceb826 100644 --- a/dspace-lni/src/main/java/org/dspace/app/dav/DAVSite.java +++ b/dspace-lni/src/main/java/org/dspace/app/dav/DAVSite.java @@ -20,6 +20,8 @@ import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Community; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; +import org.dspace.core.LicenseManager; +import org.dspace.core.NewsManager; import org.jdom.Element; @@ -61,7 +63,7 @@ class DAVSite extends DAVResource /** * Instantiates a new DAV site. - * + * * @param context the context * @param request the request * @param response the response @@ -76,14 +78,14 @@ class DAVSite extends DAVResource /** * Match resource URI. - * + * * @param context the context * @param request the request * @param response the response * @param pathElt the path elt - * + * * @return the DAV resource - * + * * @throws DAVStatusException the DAV status exception * @throws SQLException the SQL exception */ @@ -143,15 +145,15 @@ class DAVSite extends DAVResource } else if (elementsEqualIsh(property, news_topProperty)) { - value = ConfigurationManager.readNewsFile("news-top.html"); + value = NewsManager.readNewsFile("news-top.html"); } else if (elementsEqualIsh(property, news_sideProperty)) { - value = ConfigurationManager.readNewsFile("news-side.html"); + value = NewsManager.readNewsFile("news-side.html"); } else if (elementsEqualIsh(property, default_licenseProperty)) { - value = ConfigurationManager.getDefaultSubmissionLicense(); + value = LicenseManager.getDefaultSubmissionLicense(); } else { @@ -186,7 +188,7 @@ class DAVSite extends DAVResource throw new DAVStatusException(HttpServletResponse.SC_FORBIDDEN, "Not authorized to modify this property."); } - ConfigurationManager.writeNewsFile("news-top.html", newValue); + NewsManager.writeNewsFile("news-top.html", newValue); } else if (elementsEqualIsh(prop, news_sideProperty)) { @@ -195,7 +197,7 @@ class DAVSite extends DAVResource throw new DAVStatusException(HttpServletResponse.SC_FORBIDDEN, "Not authorized to modify this property."); } - ConfigurationManager.writeNewsFile("news-side.html", newValue); + NewsManager.writeNewsFile("news-side.html", newValue); } else if (elementsEqualIsh(prop, displaynameProperty)) { diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/SendFeedbackAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/SendFeedbackAction.java index 02ca38d3eb..dbf37e7be3 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/SendFeedbackAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/SendFeedbackAction.java @@ -128,7 +128,7 @@ public class SendFeedbackAction extends AbstractAction } // All data is there, send the email - Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback")); + Email email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback")); email.addRecipient(ConfigurationManager .getProperty("feedback.recipient"));