[DS-1390] stage 1: move license, email texts, news out of Configuration Manager.

This commit is contained in:
Mark H. Wood
2013-04-20 19:18:49 -04:00
parent 96cc0d5bd4
commit ed9149608d
24 changed files with 1182 additions and 1187 deletions

View File

@@ -74,7 +74,7 @@ import org.dspace.handle.HandleManager;
* <P> * <P>
* Modified by David Little, UCSD Libraries 12/21/04 to allow the registration * Modified by David Little, UCSD Libraries 12/21/04 to allow the registration
* of files (bitstreams) into DSpace. * of files (bitstreams) into DSpace.
* *
* @author David Little * @author David Little
* @author Jay Paz * @author Jay Paz
*/ */
@@ -86,12 +86,12 @@ public class ItemExport
* used for export download * used for export download
*/ */
public static final String COMPRESSED_EXPORT_MIME_TYPE = "application/zip"; public static final String COMPRESSED_EXPORT_MIME_TYPE = "application/zip";
/** log4j logger */ /** log4j logger */
private static Logger log = Logger.getLogger(ItemExport.class); private static Logger log = Logger.getLogger(ItemExport.class);
/* /*
* *
*/ */
public static void main(String[] argv) throws Exception 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 * Discover the different schemas in use and output a separate metadata XML
* file for each schema. * file for each schema.
* *
* @param c * @param c
* @param i * @param i
* @param destDir * @param destDir
@@ -561,7 +561,7 @@ public class ItemExport
* were originally registered will be marked in the contents file as such. * were originally registered will be marked in the contents file as such.
* However, the export directory will contain actual copies of the content * However, the export directory will contain actual copies of the content
* files being exported. * files being exported.
* *
* @param c * @param c
* the DSpace context * the DSpace context
* @param i * @param i
@@ -720,7 +720,7 @@ public class ItemExport
/** /**
* Convenience methot to create export a single Community, Collection, or * Convenience methot to create export a single Community, Collection, or
* Item * Item
* *
* @param dso * @param dso
* - the dspace object to export * - the dspace object to export
* @param context * @param context
@@ -740,7 +740,7 @@ public class ItemExport
/** /**
* Convenience method to export a List of dspace objects (Community, * Convenience method to export a List of dspace objects (Community,
* Collection or Item) * Collection or Item)
* *
* @param dsObjects * @param dsObjects
* - List containing dspace objects * - List containing dspace objects
* @param context * @param context
@@ -758,7 +758,7 @@ public class ItemExport
/** /**
* Convenience methot to create export a single Community, Collection, or * Convenience methot to create export a single Community, Collection, or
* Item * Item
* *
* @param dso * @param dso
* - the dspace object to export * - the dspace object to export
* @param context * @param context
@@ -778,7 +778,7 @@ public class ItemExport
/** /**
* Convenience method to export a List of dspace objects (Community, * Convenience method to export a List of dspace objects (Community,
* Collection or Item) * Collection or Item)
* *
* @param dsObjects * @param dsObjects
* - List containing dspace objects * - List containing dspace objects
* @param context * @param context
@@ -797,7 +797,7 @@ public class ItemExport
* Does the work creating a List with all the Items in the Community or * 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 * Collection It then kicks off a new Thread to export the items, zip the
* export directory and send confirmation email * export directory and send confirmation email
* *
* @param dsObjects * @param dsObjects
* - List of dspace objects to process * - List of dspace objects to process
* @param context * @param context
@@ -1008,7 +1008,7 @@ public class ItemExport
{ {
iitems.close(); iitems.close();
} }
// Make sure the database connection gets closed in all conditions. // Make sure the database connection gets closed in all conditions.
try { try {
context.complete(); context.complete();
@@ -1027,7 +1027,7 @@ public class ItemExport
/** /**
* Create a file name based on the date and eperson * Create a file name based on the date and eperson
* *
* @param eperson * @param eperson
* - eperson who requested export and will be able to download it * - eperson who requested export and will be able to download it
* @param date * @param date
@@ -1061,7 +1061,7 @@ public class ItemExport
/** /**
* Use config file entry for org.dspace.app.itemexport.download.dir and id * Use config file entry for org.dspace.app.itemexport.download.dir and id
* of the eperson to create a download directory name * of the eperson to create a download directory name
* *
* @param ePersonID * @param ePersonID
* - id of the eperson who requested export archive * - id of the eperson who requested export archive
* @return String representing a directory in the form of * @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 * Returns config file entry for org.dspace.app.itemexport.work.dir
* *
* @return String representing config file entry for * @return String representing config file entry for
* org.dspace.app.itemexport.work.dir * org.dspace.app.itemexport.work.dir
* @throws Exception * @throws Exception
@@ -1104,7 +1104,7 @@ public class ItemExport
/** /**
* Used to read the export archived. Inteded for download. * Used to read the export archived. Inteded for download.
* *
* @param fileName * @param fileName
* the name of the file to download * the name of the file to download
* @param eperson * @param eperson
@@ -1129,7 +1129,7 @@ public class ItemExport
/** /**
* Get the file size of the export archive represented by the file name. * Get the file size of the export archive represented by the file name.
* *
* @param fileName * @param fileName
* name of the file to get the size. * name of the file to get the size.
* @throws Exception * @throws Exception
@@ -1175,7 +1175,7 @@ public class ItemExport
* The file name of the export archive contains the eperson id of the person * 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 * who created it When requested for download this method can check if the
* person requesting it is the same one that created it * person requesting it is the same one that created it
* *
* @param context * @param context
* dspace context * dspace context
* @param fileName * @param fileName
@@ -1208,7 +1208,7 @@ public class ItemExport
/** /**
* Reads the download directory for the eperson to see if any export * Reads the download directory for the eperson to see if any export
* archives are available * archives are available
* *
* @param eperson * @param eperson
* @return a list of file names representing export archives that have been * @return a list of file names representing export archives that have been
* processed * processed
@@ -1245,7 +1245,7 @@ public class ItemExport
* A clean up method that is ran before a new export archive is created. It * 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 * uses the config file entry 'org.dspace.app.itemexport.life.span.hours' to
* determine if the current exports are too old and need pruging * determine if the current exports are too old and need pruging
* *
* @param epersonID * @param epersonID
* - the id of the eperson to clean up * - the id of the eperson to clean up
* @throws Exception * @throws Exception
@@ -1328,7 +1328,7 @@ public class ItemExport
* with calling method about success or failure. We accomplis this * with calling method about success or failure. We accomplis this
* communication with email instead. Send a success email once the export * communication with email instead. Send a success email once the export
* archive is complete and ready for download * archive is complete and ready for download
* *
* @param context * @param context
* - the current Context * - the current Context
* @param eperson * @param eperson
@@ -1344,7 +1344,7 @@ public class ItemExport
try try
{ {
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson); 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.addRecipient(eperson.getEmail());
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/exportdownload/" + fileName); email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/exportdownload/" + fileName);
email.addArgument(ConfigurationManager.getProperty("org.dspace.app.itemexport.life.span.hours")); 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 * with calling method about success or failure. We accomplis this
* communication with email instead. Send an error email if the export * communication with email instead. Send an error email if the export
* archive fails * archive fails
* *
* @param eperson * @param eperson
* - EPerson to send the error message to * - EPerson to send the error message to
* @param error * @param error
@@ -1376,7 +1376,7 @@ public class ItemExport
try try
{ {
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson); 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.addRecipient(eperson.getEmail());
email.addArgument(error); email.addArgument(error);
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/feedback"); email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/feedback");
@@ -1461,7 +1461,7 @@ public class ItemExport
// byte[] b = new byte[ (int)(cpFile.length()) ]; // byte[] b = new byte[ (int)(cpFile.length()) ];
cpFileInputStream = new FileInputStream(cpFile); cpFileInputStream = new FileInputStream(cpFile);
ZipEntry cpZipEntry = new ZipEntry(strZipEntryName); ZipEntry cpZipEntry = new ZipEntry(strZipEntryName);
cpZipOutputStream.putNextEntry(cpZipEntry); cpZipOutputStream.putNextEntry(cpZipEntry);

View File

@@ -31,6 +31,7 @@ import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.I18nUtil; import org.dspace.core.I18nUtil;
import org.dspace.core.LicenseManager;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.eperson.Group; import org.dspace.eperson.Group;
import org.dspace.event.Event; import org.dspace.event.Event;
@@ -52,7 +53,7 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
* database after calling <code>update</code>. The default group of * database after calling <code>update</code>. The default group of
* submitters is slightly different - creating or removing this has instant * submitters is slightly different - creating or removing this has instant
* effect. * effect.
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$ * @version $Revision$
*/ */
@@ -96,7 +97,7 @@ public class Collection extends DSpaceObject
/** /**
* Construct a collection with the given table row * Construct a collection with the given table row
* *
* @param context * @param context
* the context this object exists in * the context this object exists in
* @param row * @param row
@@ -139,7 +140,7 @@ public class Collection extends DSpaceObject
submitters = groupFromColumn("submitter"); submitters = groupFromColumn("submitter");
admins = groupFromColumn("admin"); admins = groupFromColumn("admin");
// Get our Handle if any // Get our Handle if any
handle = HandleManager.findHandle(context, this); handle = HandleManager.findHandle(context, this);
@@ -153,12 +154,12 @@ public class Collection extends DSpaceObject
/** /**
* Get a collection from the database. Loads in the metadata * Get a collection from the database. Loads in the metadata
* *
* @param context * @param context
* DSpace context object * DSpace context object
* @param id * @param id
* ID of the collection * ID of the collection
* *
* @return the collection, or null if the ID is invalid. * @return the collection, or null if the ID is invalid.
* @throws SQLException * @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 * Create a new collection, with a new ID. This method is not public, and
* does not check authorisation. * does not check authorisation.
* *
* @param context * @param context
* DSpace context object * DSpace context object
* *
* @return the newly created collection * @return the newly created collection
* @throws SQLException * @throws SQLException
* @throws AuthorizeException * @throws AuthorizeException
@@ -288,10 +289,10 @@ public class Collection extends DSpaceObject
/** /**
* Get all collections in the system. These are alphabetically sorted by * Get all collections in the system. These are alphabetically sorted by
* collection name. * collection name.
* *
* @param context * @param context
* DSpace context object * DSpace context object
* *
* @return the collections in the system * @return the collections in the system
* @throws SQLException * @throws SQLException
*/ */
@@ -339,7 +340,7 @@ public class Collection extends DSpaceObject
/** /**
* Get the in_archive items in this collection. The order is indeterminate. * Get the in_archive items in this collection. The order is indeterminate.
* *
* @return an iterator over the items in the collection. * @return an iterator over the items in the collection.
* @throws SQLException * @throws SQLException
*/ */
@@ -358,7 +359,7 @@ public class Collection extends DSpaceObject
/** /**
* Get all the items in this collection. The order is indeterminate. * Get all the items in this collection. The order is indeterminate.
* *
* @return an iterator over the items in the collection. * @return an iterator over the items in the collection.
* @throws SQLException * @throws SQLException
*/ */
@@ -376,7 +377,7 @@ public class Collection extends DSpaceObject
/** /**
* Get the internal ID of this collection * Get the internal ID of this collection
* *
* @return the internal identifier * @return the internal identifier
*/ */
public int getID() public int getID()
@@ -402,36 +403,36 @@ public class Collection extends DSpaceObject
/** /**
* Get the value of a metadata field * Get the value of a metadata field
* *
* @param field * @param field
* the name of the metadata field to get * the name of the metadata field to get
* *
* @return the value of the metadata field * @return the value of the metadata field
* *
* @exception IllegalArgumentException * @exception IllegalArgumentException
* if the requested metadata field doesn't exist * if the requested metadata field doesn't exist
*/ */
public String getMetadata(String field) public String getMetadata(String field)
{ {
String metadata = collectionRow.getStringColumn(field); String metadata = collectionRow.getStringColumn(field);
return (metadata == null) ? "" : metadata; return (metadata == null) ? "" : metadata;
} }
/** /**
* Set a metadata value * Set a metadata value
* *
* @param field * @param field
* the name of the metadata field to get * the name of the metadata field to get
* @param value * @param value
* value to set the field to * value to set the field to
* *
* @exception IllegalArgumentException * @exception IllegalArgumentException
* if the requested metadata field doesn't exist * if the requested metadata field doesn't exist
* @exception MissingResourceException * @exception MissingResourceException
*/ */
public void setMetadata(String field, String value) throws 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(""))) && (value == null || value.trim().equals("")))
{ {
try try
@@ -443,9 +444,9 @@ public class Collection extends DSpaceObject
value = "Untitled"; value = "Untitled";
} }
} }
/* /*
* Set metadata field to null if null * Set metadata field to null if null
* and trim strings to eliminate excess * and trim strings to eliminate excess
* whitespace. * whitespace.
*/ */
@@ -457,7 +458,7 @@ public class Collection extends DSpaceObject
{ {
collectionRow.setColumn(field, value.trim()); collectionRow.setColumn(field, value.trim());
} }
modifiedMetadata = true; modifiedMetadata = true;
addDetails(field); addDetails(field);
} }
@@ -470,7 +471,7 @@ public class Collection extends DSpaceObject
/** /**
* Get the logo for the collection. <code>null</code> is returned if the * Get the logo for the collection. <code>null</code> is returned if the
* collection does not have a logo. * collection does not have a logo.
* *
* @return the logo of the collection, or <code>null</code> * @return the logo of the collection, or <code>null</code>
*/ */
public Bitstream getLogo() 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 * Note that while the new group is created in the database, the association
* between the group and the collection is not written until * between the group and the collection is not written until
* <code>update</code> is called. * <code>update</code> is called.
* *
* @param step * @param step
* the step (1-3) of the workflow to create or get the group for * the step (1-3) of the workflow to create or get the group for
* *
* @return the workflow group associated with this collection * @return the workflow group associated with this collection
* @throws SQLException * @throws SQLException
* @throws AuthorizeException * @throws AuthorizeException
@@ -581,7 +582,7 @@ public class Collection extends DSpaceObject
* Set the workflow group corresponding to a particular workflow step. * Set the workflow group corresponding to a particular workflow step.
* <code>null</code> can be passed in if there should be no associated * <code>null</code> can be passed in if there should be no associated
* group for that workflow step; any existing group is NOT deleted. * group for that workflow step; any existing group is NOT deleted.
* *
* @param step * @param step
* the workflow step (1-3) * the workflow step (1-3)
* @param g * @param g
@@ -606,10 +607,10 @@ public class Collection extends DSpaceObject
* Get the the workflow group corresponding to a particular workflow step. * Get the the workflow group corresponding to a particular workflow step.
* This returns <code>null</code> if there is no group associated with * This returns <code>null</code> if there is no group associated with
* this collection for the given step. * this collection for the given step.
* *
* @param step * @param step
* the workflow step (1-3) * the workflow step (1-3)
* *
* @return the group of reviewers or <code>null</code> * @return the group of reviewers or <code>null</code>
*/ */
public Group getWorkflowGroup(int step) 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 * 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 * other groups may also be allowed to submit to this collection by the
* authorization system. * authorization system.
* *
* @return the default group of submitters associated with this collection * @return the default group of submitters associated with this collection
* @throws SQLException * @throws SQLException
* @throws AuthorizeException * @throws AuthorizeException
@@ -645,7 +646,7 @@ public class Collection extends DSpaceObject
// register this as the submitter group // register this as the submitter group
collectionRow.setColumn("submitter", submitters.getID()); collectionRow.setColumn("submitter", submitters.getID());
AuthorizeManager.addPolicy(ourContext, this, Constants.ADD, submitters); AuthorizeManager.addPolicy(ourContext, this, Constants.ADD, submitters);
modified = true; modified = true;
@@ -653,9 +654,9 @@ public class Collection extends DSpaceObject
} }
/** /**
* Remove the submitters group, if no group has already been created * Remove the submitters group, if no group has already been created
* then return without error. This will merely dereference the current * then return without error. This will merely dereference the current
* submitters group from the collection so that it may be deleted * submitters group from the collection so that it may be deleted
* without violating database constraints. * without violating database constraints.
*/ */
public void removeSubmitters() throws SQLException, AuthorizeException public void removeSubmitters() throws SQLException, AuthorizeException
@@ -672,11 +673,11 @@ public class Collection extends DSpaceObject
// Remove the link to the collection table. // Remove the link to the collection table.
collectionRow.setColumnNull("submitter"); collectionRow.setColumnNull("submitter");
submitters = null; submitters = null;
modified = true; modified = true;
} }
/** /**
* Get the default group of submitters, if there is one. Note that the * Get the default group of submitters, if there is one. Note that the
* authorization system may allow others to submit to the collection, so * authorization system may allow others to submit to the collection, so
@@ -684,7 +685,7 @@ public class Collection extends DSpaceObject
* <P> * <P>
* The default group of submitters for collection 100 is the one called * The default group of submitters for collection 100 is the one called
* <code>collection_100_submit</code>. * <code>collection_100_submit</code>.
* *
* @return the default group of submitters, or <code>null</code> if there * @return the default group of submitters, or <code>null</code> if there
* is no default group. * is no default group.
*/ */
@@ -697,7 +698,7 @@ public class Collection extends DSpaceObject
* Create a default administrators group if one does not already exist. * Create a default administrators group if one does not already exist.
* Returns either the newly created group or the previously existing one. * Returns either the newly created group or the previously existing one.
* Note that other groups may also be administrators. * Note that other groups may also be administrators.
* *
* @return the default group of editors associated with this collection * @return the default group of editors associated with this collection
* @throws SQLException * @throws SQLException
* @throws AuthorizeException * @throws AuthorizeException
@@ -713,7 +714,7 @@ public class Collection extends DSpaceObject
ourContext.turnOffAuthorisationSystem(); ourContext.turnOffAuthorisationSystem();
admins = Group.create(ourContext); admins = Group.create(ourContext);
ourContext.restoreAuthSystemState(); ourContext.restoreAuthSystemState();
admins.setName("COLLECTION_" + getID() + "_ADMIN"); admins.setName("COLLECTION_" + getID() + "_ADMIN");
admins.update(); admins.update();
} }
@@ -723,15 +724,15 @@ public class Collection extends DSpaceObject
// register this as the admin group // register this as the admin group
collectionRow.setColumn("admin", admins.getID()); collectionRow.setColumn("admin", admins.getID());
modified = true; modified = true;
return admins; return admins;
} }
/** /**
* Remove the administrators group, if no group has already been created * Remove the administrators group, if no group has already been created
* then return without error. This will merely dereference the current * then return without error. This will merely dereference the current
* administrators group from the collection so that it may be deleted * administrators group from the collection so that it may be deleted
* without violating database constraints. * without violating database constraints.
*/ */
public void removeAdministrators() throws SQLException, AuthorizeException public void removeAdministrators() throws SQLException, AuthorizeException
@@ -748,7 +749,7 @@ public class Collection extends DSpaceObject
// Remove the link to the collection table. // Remove the link to the collection table.
collectionRow.setColumnNull("admin"); collectionRow.setColumnNull("admin");
admins = null; admins = null;
modified = true; modified = true;
} }
@@ -759,7 +760,7 @@ public class Collection extends DSpaceObject
* <P> * <P>
* The default group of administrators for collection 100 is the one called * The default group of administrators for collection 100 is the one called
* <code>collection_100_admin</code>. * <code>collection_100_admin</code>.
* *
* @return group of administrators, or <code>null</code> if there is no * @return group of administrators, or <code>null</code> if there is no
* default group. * default group.
*/ */
@@ -772,7 +773,7 @@ public class Collection extends DSpaceObject
* Get the license that users must grant before submitting to this * Get the license that users must grant before submitting to this
* collection. If the collection does not have a specific license, the * collection. If the collection does not have a specific license, the
* site-wide default is returned. * site-wide default is returned.
* *
* @return the license for this collection * @return the license for this collection
*/ */
public String getLicense() public String getLicense()
@@ -782,7 +783,7 @@ public class Collection extends DSpaceObject
if (license == null || license.trim().equals("")) if (license == null || license.trim().equals(""))
{ {
// Fallback to site-wide default // Fallback to site-wide default
license = ConfigurationManager.getDefaultSubmissionLicense(); license = LicenseManager.getDefaultSubmissionLicense();
} }
return license; return license;
@@ -790,8 +791,8 @@ public class Collection extends DSpaceObject
/** /**
* Get the license that users must grant before submitting to this * Get the license that users must grant before submitting to this
* collection. * collection.
* *
* @return the license for this collection * @return the license for this collection
*/ */
public String getLicenseCollection() public String getLicenseCollection()
@@ -801,7 +802,7 @@ public class Collection extends DSpaceObject
/** /**
* Find out if the collection has a custom license * Find out if the collection has a custom license
* *
* @return <code>true</code> if the collection has a custom license * @return <code>true</code> if the collection has a custom license
*/ */
public boolean hasCustomLicense() public boolean hasCustomLicense()
@@ -814,7 +815,7 @@ public class Collection extends DSpaceObject
/** /**
* Set the license for this collection. Passing in <code>null</code> means * Set the license for this collection. Passing in <code>null</code> means
* that the site-wide default will be used. * that the site-wide default will be used.
* *
* @param license * @param license
* the license, or <code>null</code> * the license, or <code>null</code>
*/ */
@@ -828,7 +829,7 @@ public class Collection extends DSpaceObject
* returned if the collection does not have a template. Submission * returned if the collection does not have a template. Submission
* mechanisms may copy this template to provide a convenient starting point * mechanisms may copy this template to provide a convenient starting point
* for a submission. * for a submission.
* *
* @return the item template, or <code>null</code> * @return the item template, or <code>null</code>
*/ */
public Item getTemplateItem() throws SQLException public Item getTemplateItem() throws SQLException
@@ -841,7 +842,7 @@ public class Collection extends DSpaceObject
* no action is taken. Caution: Make sure you call <code>update</code> on * no action is taken. Caution: Make sure you call <code>update</code> on
* the collection after doing this, or the item will have been created but * the collection after doing this, or the item will have been created but
* the collection record will not refer to it. * the collection record will not refer to it.
* *
* @throws SQLException * @throws SQLException
* @throws AuthorizeException * @throws AuthorizeException
*/ */
@@ -868,7 +869,7 @@ public class Collection extends DSpaceObject
* record in the database, the collection record will be changed, including * record in the database, the collection record will be changed, including
* any other changes made; in other words, this method does an * any other changes made; in other words, this method does an
* <code>update</code>. * <code>update</code>.
* *
* @throws SQLException * @throws SQLException
* @throws AuthorizeException * @throws AuthorizeException
* @throws IOException * @throws IOException
@@ -881,7 +882,7 @@ public class Collection extends DSpaceObject
collectionRow.setColumnNull("template_item_id"); collectionRow.setColumnNull("template_item_id");
DatabaseManager.update(ourContext, collectionRow); DatabaseManager.update(ourContext, collectionRow);
if (template != null) if (template != null)
{ {
log.info(LogManager.getHeader(ourContext, "remove_template_item", log.info(LogManager.getHeader(ourContext, "remove_template_item",
@@ -894,7 +895,7 @@ public class Collection extends DSpaceObject
ourContext.restoreAuthSystemState(); ourContext.restoreAuthSystemState();
template = null; template = null;
} }
ourContext.addEvent(new Event(Event.MODIFY, Constants.COLLECTION, getID(), "remove_template_item")); 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, * the item and the collection - it does nothing like set an issue date,
* remove a personal workspace item etc. This has instant effect; * remove a personal workspace item etc. This has instant effect;
* <code>update</code> need not be called. * <code>update</code> need not be called.
* *
* @param item * @param item
* item to add * item to add
* @throws SQLException * @throws SQLException
@@ -930,7 +931,7 @@ public class Collection extends DSpaceObject
/** /**
* Remove an item. If the item is then orphaned, it is deleted. * Remove an item. If the item is then orphaned, it is deleted.
* *
* @param item * @param item
* item to remove * item to remove
* @throws SQLException * @throws SQLException
@@ -956,20 +957,20 @@ public class Collection extends DSpaceObject
} }
log.info(LogManager.getHeader(ourContext, "remove_item", log.info(LogManager.getHeader(ourContext, "remove_item",
"collection_id=" + getID() + ",item_id=" + item.getID())); "collection_id=" + getID() + ",item_id=" + item.getID()));
DatabaseManager.updateQuery(ourContext, DatabaseManager.updateQuery(ourContext,
"DELETE FROM collection2item WHERE collection_id= ? "+ "DELETE FROM collection2item WHERE collection_id= ? "+
"AND item_id= ? ", "AND item_id= ? ",
getID(), item.getID()); getID(), item.getID());
DatabaseManager.setConstraintImmediate(ourContext, "coll2item_item_fk"); DatabaseManager.setConstraintImmediate(ourContext, "coll2item_item_fk");
ourContext.addEvent(new Event(Event.REMOVE, Constants.COLLECTION, getID(), Constants.ITEM, item.getID(), item.getHandle())); 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 * Update the collection metadata (including logo and workflow groups) to
* the database. Inserts if this is a new collection. * the database. Inserts if this is a new collection.
* *
* @throws SQLException * @throws SQLException
* @throws IOException * @throws IOException
* @throws AuthorizeException * @throws AuthorizeException
@@ -996,7 +997,7 @@ public class Collection extends DSpaceObject
clearDetails(); clearDetails();
} }
} }
public boolean canEditBoolean() throws java.sql.SQLException public boolean canEditBoolean() throws java.sql.SQLException
{ {
return canEditBoolean(true); return canEditBoolean(true);
@@ -1020,7 +1021,7 @@ public class Collection extends DSpaceObject
{ {
canEdit(true); canEdit(true);
} }
public void canEdit(boolean useInheritance) throws AuthorizeException, SQLException public void canEdit(boolean useInheritance) throws AuthorizeException, SQLException
{ {
Community[] parents = getCommunities(); Community[] parents = getCommunities();
@@ -1047,7 +1048,7 @@ public class Collection extends DSpaceObject
* Delete the collection, including the metadata and logo. Items that are * Delete the collection, including the metadata and logo. Items that are
* then orphans are deleted. Groups associated with this collection * then orphans are deleted. Groups associated with this collection
* (workflow participants and submitters) are NOT deleted. * (workflow participants and submitters) are NOT deleted.
* *
* @throws SQLException * @throws SQLException
* @throws AuthorizeException * @throws AuthorizeException
* @throws IOException * @throws IOException
@@ -1064,12 +1065,12 @@ public class Collection extends DSpaceObject
// remove subscriptions - hmm, should this be in Subscription.java? // remove subscriptions - hmm, should this be in Subscription.java?
DatabaseManager.updateQuery(ourContext, DatabaseManager.updateQuery(ourContext,
"DELETE FROM subscription WHERE collection_id= ? ", "DELETE FROM subscription WHERE collection_id= ? ",
getID()); getID());
// Remove Template Item // Remove Template Item
removeTemplateItem(); removeTemplateItem();
// Remove items // Remove items
ItemIterator items = getAllItems(); ItemIterator items = getAllItems();
@@ -1079,7 +1080,7 @@ public class Collection extends DSpaceObject
{ {
Item item = items.next(); Item item = items.next();
IndexBrowse ib = new IndexBrowse(ourContext); IndexBrowse ib = new IndexBrowse(ourContext);
if (item.isOwningCollection(this)) if (item.isOwningCollection(this))
{ {
// the collection to be deleted is the owning collection, thus remove // the collection to be deleted is the owning collection, thus remove
@@ -1092,12 +1093,12 @@ public class Collection extends DSpaceObject
// Browse.itemRemoved(ourContext, itemId); // Browse.itemRemoved(ourContext, itemId);
collections[i].removeItem(item); collections[i].removeItem(item);
} }
} }
// the item was only mapped to this collection, so just remove it // the item was only mapped to this collection, so just remove it
else else
{ {
//notify Browse of removing item mapping. //notify Browse of removing item mapping.
ib.indexItem(item); ib.indexItem(item);
// Browse.itemChanged(ourContext, item); // Browse.itemChanged(ourContext, item);
removeItem(item); removeItem(item);
@@ -1226,7 +1227,7 @@ public class Collection extends DSpaceObject
/** /**
* Get the communities this collection appears in * Get the communities this collection appears in
* *
* @return array of <code>Community</code> objects * @return array of <code>Community</code> objects
* @throws SQLException * @throws SQLException
*/ */
@@ -1282,10 +1283,10 @@ public class Collection extends DSpaceObject
/** /**
* Return <code>true</code> if <code>other</code> is the same Collection * Return <code>true</code> if <code>other</code> is the same Collection
* as this object, <code>false</code> otherwise * as this object, <code>false</code> otherwise
* *
* @param other * @param other
* object to compare to * object to compare to
* *
* @return <code>true</code> if object passed in represents the same * @return <code>true</code> if object passed in represents the same
* collection as this object * 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 * Utility method for reading in a group from a group ID in a column. If the
* column is null, null is returned. * column is null, null is returned.
* *
* @param col * @param col
* the column name to read * the column name to read
* @return the group referred to by that column, or null * @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 type found in Constants
* *
* @return int Constants.COLLECTION * @return int Constants.COLLECTION
*/ */
public int getType() public int getType()
@@ -1351,13 +1352,13 @@ public class Collection extends DSpaceObject
* return an array of collections that user has a given permission on * return an array of collections that user has a given permission on
* (useful for trimming 'select to collection' list) or figuring out which * (useful for trimming 'select to collection' list) or figuring out which
* collections a person is an editor for. * collections a person is an editor for.
* *
* @param context * @param context
* @param comm * @param comm
* (optional) restrict search to a community, else null * (optional) restrict search to a community, else null
* @param actionID * @param actionID
* of the action * of the action
* *
* @return Collection [] of collections with matching permissions * @return Collection [] of collections with matching permissions
* @throws SQLException * @throws SQLException
*/ */
@@ -1437,7 +1438,7 @@ public class Collection extends DSpaceObject
return itemcount; return itemcount;
} }
public DSpaceObject getAdminObject(int action) throws SQLException public DSpaceObject getAdminObject(int action) throws SQLException
{ {
DSpaceObject adminObject = null; DSpaceObject adminObject = null;
@@ -1473,7 +1474,7 @@ public class Collection extends DSpaceObject
} }
return adminObject; return adminObject;
} }
@Override @Override
public DSpaceObject getParentObject() throws SQLException public DSpaceObject getParentObject() throws SQLException
{ {

View File

@@ -43,7 +43,7 @@ import org.apache.log4j.helpers.OptionConverter;
* of the DSpace installation directory (specified as the property * of the DSpace installation directory (specified as the property
* <code>dspace.dir</code> in the main configuration file.) * <code>dspace.dir</code> in the main configuration file.)
* *
* *
* @author Robert Tansley * @author Robert Tansley
* @author Larry Stone - Interpolated values. * @author Larry Stone - Interpolated values.
* @author Mark Diggory - General Improvements to detection, logging and loading. * @author Mark Diggory - General Improvements to detection, logging and loading.
@@ -56,20 +56,17 @@ public class ConfigurationManager
/** The configuration properties */ /** The configuration properties */
private static Properties properties = null; private static Properties properties = null;
/** module configuration properties */ /** module configuration properties */
private static Map<String, Properties> moduleProps = new HashMap<String, Properties>(); private static Map<String, Properties> moduleProps = new HashMap<String, Properties>();
/** The default license */
private static String license;
// limit of recursive depth of property variable interpolation in // limit of recursive depth of property variable interpolation in
// configuration; anything greater than this is very likely to be a loop. // configuration; anything greater than this is very likely to be a loop.
private static final int RECURSION_LIMIT = 9; private static final int RECURSION_LIMIT = 9;
protected ConfigurationManager() protected ConfigurationManager()
{ {
} }
/** /**
@@ -80,7 +77,7 @@ public class ConfigurationManager
{ {
return properties != null; return properties != null;
} }
public static boolean isConfigured(String module) public static boolean isConfigured(String module)
{ {
return moduleProps.get(module) != null; return moduleProps.get(module) != null;
@@ -97,24 +94,24 @@ public class ConfigurationManager
// { // {
// properties = null; // properties = null;
// } // }
/** /**
* REMOVED - Flushing the properties could be dangerous in the current DSpace state * REMOVED - Flushing the properties could be dangerous in the current DSpace state
* Need to consider how it will affect in-flight processes * Need to consider how it will affect in-flight processes
* *
* Discard properties for a module - will force a reload from disk * Discard properties for a module - will force a reload from disk
* when any of module's properties are requested * when any of module's properties are requested
* *
* @param module the module name * @param module the module name
*/ */
// public static void flush(String module) // public static void flush(String module)
// { // {
// moduleProps.remove(module); // moduleProps.remove(module);
// } // }
/** /**
* Returns all properties in main configuration * Returns all properties in main configuration
* *
* @return properties - all non-modular properties * @return properties - all non-modular properties
*/ */
public static Properties getProperties() public static Properties getProperties()
@@ -135,7 +132,7 @@ public class ConfigurationManager
/** /**
* Returns all properties for a given module * Returns all properties for a given module
* *
* @param module * @param module
* the name of the module * the name of the module
* @return properties - all module's properties * @return properties - all module's properties
@@ -163,10 +160,10 @@ public class ConfigurationManager
/** /**
* Get a configuration property * Get a configuration property
* *
* @param property * @param property
* the name of the property * the name of the property
* *
* @return the value of the property, or <code>null</code> if the property * @return the value of the property, or <code>null</code> if the property
* does not exist. * does not exist.
*/ */
@@ -176,11 +173,11 @@ public class ConfigurationManager
String value = props == null ? null : props.getProperty(property); String value = props == null ? null : props.getProperty(property);
return (value != null) ? value.trim() : null; return (value != null) ? value.trim() : null;
} }
/** /**
* Get a module configuration property value. * Get a module configuration property value.
* *
* @param module * @param module
* the name of the module, or <code>null</code> for regular configuration * the name of the module, or <code>null</code> for regular configuration
* property * property
* @param property * @param property
@@ -195,7 +192,7 @@ public class ConfigurationManager
{ {
return getProperty(property); return getProperty(property);
} }
String value = null; String value = null;
Properties modProps = getMutableProperties(module); Properties modProps = getMutableProperties(module);
@@ -215,10 +212,10 @@ public class ConfigurationManager
/** /**
* Get a configuration property as an integer * Get a configuration property as an integer
* *
* @param property * @param property
* the name of the property * the name of the property
* *
* @return the value of the property. <code>0</code> is returned if the * @return the value of the property. <code>0</code> is returned if the
* property does not exist. To differentiate between this case and * property does not exist. To differentiate between this case and
* when the property actually is zero, use <code>getProperty</code>. * when the property actually is zero, use <code>getProperty</code>.
@@ -227,16 +224,16 @@ public class ConfigurationManager
{ {
return getIntProperty(property, 0); return getIntProperty(property, 0);
} }
/** /**
* Get a module configuration property as an integer * Get a module configuration property as an integer
* *
* @param module * @param module
* the name of the module * the name of the module
* *
* @param property * @param property
* the name of the property * the name of the property
* *
* @return the value of the property. <code>0</code> is returned if the * @return the value of the property. <code>0</code> is returned if the
* property does not exist. To differentiate between this case and * property does not exist. To differentiate between this case and
* when the property actually is zero, use <code>getProperty</code>. * when the property actually is zero, use <code>getProperty</code>.
@@ -248,10 +245,10 @@ public class ConfigurationManager
/** /**
* Get a configuration property as an integer, with default * Get a configuration property as an integer, with default
* *
* @param property * @param property
* the name of the property * the name of the property
* *
* @param defaultValue * @param defaultValue
* value to return if property is not found or is not an Integer. * 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); return getIntProperty(null, property, defaultValue);
} }
/** /**
* Get a module configuration property as an integer, with default * Get a module configuration property as an integer, with default
* *
* @param module * @param module
* the name of the module * the name of the module
* *
* @param property * @param property
* the name of the property * the name of the property
* *
* @param defaultValue * @param defaultValue
* value to return if property is not found or is not an Integer. * value to return if property is not found or is not an Integer.
* *
@@ -316,12 +313,12 @@ public class ConfigurationManager
{ {
return getLongProperty(property, 0); return getLongProperty(property, 0);
} }
/** /**
* Get a module configuration property as a long * Get a module configuration property as a long
* *
* @param module * @param module
* the name of the module * the name of the module
* @param property * @param property
* the name of the property * the name of the property
* *
@@ -333,10 +330,10 @@ public class ConfigurationManager
{ {
return getLongProperty(module, property, 0); return getLongProperty(module, property, 0);
} }
/** /**
* Get a configuration property as an long, with default * Get a configuration property as an long, with default
* *
* *
* @param property * @param property
* the name of the property * the name of the property
@@ -356,7 +353,7 @@ public class ConfigurationManager
/** /**
* Get a configuration property as an long, with default * Get a configuration property as an long, with default
* *
* @param module the module, or <code>null</code> for regular property * @param module the module, or <code>null</code> for regular property
* *
* @param property * @param property
@@ -390,91 +387,14 @@ public class ConfigurationManager
return longValue; 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 * Get a configuration property as a boolean. True is indicated if the value
* of the property is <code>TRUE</code> or <code>YES</code> (case * of the property is <code>TRUE</code> or <code>YES</code> (case
* insensitive.) * insensitive.)
* *
* @param property * @param property
* the name of the property * the name of the property
* *
* @return the value of the property. <code>false</code> is returned if * @return the value of the property. <code>false</code> is returned if
* the property does not exist. To differentiate between this case * the property does not exist. To differentiate between this case
* and when the property actually is false, use * and when the property actually is false, use
@@ -484,17 +404,17 @@ public class ConfigurationManager
{ {
return getBooleanProperty(property, false); 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 <code>TRUE</code> or <code>YES</code> (case * the value of the property is <code>TRUE</code> or <code>YES</code> (case
* insensitive.) * insensitive.)
* *
* @param module the module, or <code>null</code> for regular property * @param module the module, or <code>null</code> for regular property
* *
* @param property * @param property
* the name of the property * the name of the property
* *
* @return the value of the property. <code>false</code> is returned if * @return the value of the property. <code>false</code> is returned if
* the property does not exist. To differentiate between this case * the property does not exist. To differentiate between this case
* and when the property actually is false, use * and when the property actually is false, use
@@ -504,7 +424,7 @@ public class ConfigurationManager
{ {
return getBooleanProperty(module, property, false); return getBooleanProperty(module, property, false);
} }
/** /**
* Get a configuration property as a boolean, with default. * Get a configuration property as a boolean, with default.
* True is indicated if the value * True is indicated if the value
@@ -532,8 +452,8 @@ public class ConfigurationManager
* True is indicated if the value * True is indicated if the value
* of the property is <code>TRUE</code> or <code>YES</code> (case * of the property is <code>TRUE</code> or <code>YES</code> (case
* insensitive.) * insensitive.)
* *
* @param module module, or <code>null</code> for regular property * @param module module, or <code>null</code> for regular property
* *
* @param property * @param property
* the name of the property * the name of the property
@@ -564,19 +484,19 @@ public class ConfigurationManager
/** /**
* Returns an enumeration of all the keys in the DSpace configuration * Returns an enumeration of all the keys in the DSpace configuration
* *
* @return 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() public static Enumeration<?> propertyNames()
{ {
return propertyNames(null); return propertyNames(null);
} }
/** /**
* Returns an enumeration of all the keys in a module configuration * Returns an enumeration of all the keys in a module configuration
* *
* @param module module, or <code>null</code> for regular property * @param module module, or <code>null</code> for regular property
* *
* @return an enumeration of all the keys in the module configuration, * @return an enumeration of all the keys in the module configuration,
* or <code>null</code> if the module does not exist. * or <code>null</code> if the module does not exist.
*/ */
@@ -586,235 +506,13 @@ public class ConfigurationManager
return props == null ? null : props.propertyNames(); return props == null ? null : props.propertyNames();
} }
/** /** The configuration that was loaded. */
* Get the template for an email message. The message is suitable for
* inserting values using <code>java.text.MessageFormat</code>.
*
* @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;
}
private static File loadedFile = null; private static File loadedFile = null;
/** /**
* Return the file that configuration was actually loaded from. Only returns * Return the file that configuration was actually loaded from. Only returns
* a valid File after configuration has been loaded. * a valid File after configuration has been loaded.
* *
* @deprecated Please remove all direct usage of the configuration file. * @deprecated Please remove all direct usage of the configuration file.
* @return File naming configuration data file, or null if not loaded yet. * @return File naming configuration data file, or null if not loaded yet.
*/ */
@@ -883,17 +581,16 @@ public class ConfigurationManager
} }
catch (IOException ioE) catch (IOException ioE)
{ {
fatal("Can't load configuration: " + (modFile == null ? "<unknown>" : modFile.getAbsolutePath()), ioE); fatal("Can't load configuration: " +
(modFile == null ? "<unknown>" : modFile.getAbsolutePath()), ioE);
} }
return;
} }
/** /**
* Load the DSpace configuration properties. Only does anything if * Load the DSpace configuration properties. Only does anything if
* properties are not already loaded. Properties are loaded in from the * properties are not already loaded. Properties are loaded in from the
* specified file, or default locations. * specified file, or default locations.
* *
* @param configFile * @param configFile
* The <code>dspace.cfg</code> configuration file to use, or * The <code>dspace.cfg</code> configuration file to use, or
* <code>null</code> to try default locations * <code>null</code> to try default locations
@@ -906,7 +603,7 @@ public class ConfigurationManager
} }
URL url = null; URL url = null;
InputStream is = null; InputStream is = null;
InputStreamReader reader = null; InputStreamReader reader = null;
try try
@@ -922,27 +619,27 @@ public class ConfigurationManager
// This isn't really a fatal error though, so catch and ignore // This isn't really a fatal error though, so catch and ignore
log.warn("Unable to access system properties, ignoring.", se); log.warn("Unable to access system properties, ignoring.", se);
} }
// should only occur after a flush() // should only occur after a flush()
if (loadedFile != null) if (loadedFile != null)
{ {
info("Reloading current config file: " + loadedFile.getAbsolutePath()); info("Reloading current config file: " + loadedFile.getAbsolutePath());
url = loadedFile.toURI().toURL(); url = loadedFile.toURI().toURL();
} }
else if (configFile != null) else if (configFile != null)
{ {
info("Loading provided config file: " + configFile); info("Loading provided config file: " + configFile);
loadedFile = new File(configFile); loadedFile = new File(configFile);
url = loadedFile.toURI().toURL(); url = loadedFile.toURI().toURL();
} }
// Has the default configuration location been overridden? // Has the default configuration location been overridden?
else if (configProperty != null) else if (configProperty != null)
{ {
info("Loading system provided config property (-Ddspace.configuration): " + configProperty); info("Loading system provided config property (-Ddspace.configuration): " + configProperty);
// Load the overriding configuration // Load the overriding configuration
loadedFile = new File(configProperty); loadedFile = new File(configProperty);
url = loadedFile.toURI().toURL(); url = loadedFile.toURI().toURL();
@@ -954,11 +651,11 @@ public class ConfigurationManager
if (url != null) if (url != null)
{ {
info("Loading from classloader: " + url); info("Loading from classloader: " + url);
loadedFile = new File(url.getPath()); loadedFile = new File(url.getPath());
} }
} }
if (url == null) if (url == null)
{ {
fatal("Cannot find dspace.cfg"); fatal("Cannot find dspace.cfg");
@@ -988,8 +685,8 @@ public class ConfigurationManager
{ {
fatal("Can't load configuration: " + url, e); fatal("Can't load configuration: " + url, e);
// FIXME: Maybe something more graceful here, but with the // FIXME: Maybe something more graceful here, but without a
// configuration we can't do anything // configuration we can't do anything.
throw new IllegalStateException("Cannot load configuration: " + url, e); throw new IllegalStateException("Cannot load configuration: " + url, e);
} }
finally finally
@@ -1006,131 +703,61 @@ public class ConfigurationManager
if (is != null) if (is != null)
{ {
try try
{ {
is.close(); is.close();
} }
catch (IOException ioe) 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 try
{ {
/* /*
* Initialize Logging once ConfigurationManager is initialized. * 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 * 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: * Property format is:
* *
* log.init.config = ${dspace.dir}/config/log4j.properties * log.init.config = ${dspace.dir}/config/log4j.properties
* or * or
* log.init.config = ${dspace.dir}/config/log4j.xml * log.init.config = ${dspace.dir}/config/log4j.xml
* *
* See default log4j initialization documentation here: * See default log4j initialization documentation here:
* http://logging.apache.org/log4j/docs/manual.html * http://logging.apache.org/log4j/docs/manual.html
* *
* If there is a problem with the file referred to in * 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. * so do not instantiate another Logging configuration.
* *
*/ */
String dsLogConfiguration = ConfigurationManager.getProperty("log.init.config"); 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" * 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 * system property set. Leave it upto log4j to properly init its logging
* via classpath or system properties. * via classpath or system properties.
*/ */
info("Using default log4j provided log configuration," + info("Using default log4j provided log configuration." +
"if unintended, check your dspace.cfg for (log.init.config)"); " If unintended, check your dspace.cfg for (log.init.config)");
} }
else else
{ {
info("Using dspace provided log configuration (log.init.config)"); info("Using dspace provided log configuration (log.init.config)");
File logConfigFile = new File(dsLogConfiguration); File logConfigFile = new File(dsLogConfiguration);
if(logConfigFile.exists()) if(logConfigFile.exists())
{ {
info("Loading: " + dsLogConfiguration); info("Loading: " + dsLogConfiguration);
OptionConverter.selectAndConfigure(logConfigFile.toURI() OptionConverter.selectAndConfigure(logConfigFile.toURI()
.toURL(), null, org.apache.log4j.LogManager .toURL(), null, org.apache.log4j.LogManager
.getLoggerRepository()); .getLoggerRepository());
@@ -1147,7 +774,7 @@ public class ConfigurationManager
fatal("Can't load dspace provided log4j configuration", e); fatal("Can't load dspace provided log4j configuration", e);
throw new IllegalStateException("Cannot load dspace provided log4j configuration",e); throw new IllegalStateException("Cannot load dspace provided log4j configuration",e);
} }
} }
/** /**
@@ -1224,7 +851,7 @@ public class ConfigurationManager
* <code>name</code> from <code>dspace.cfg</code> to the standard * <code>name</code> from <code>dspace.cfg</code> to the standard
* output. If the property does not exist, nothing is written.</li> * output. If the property does not exist, nothing is written.</li>
* </ul> * </ul>
* *
* @param argv * @param argv
* command-line arguments * command-line arguments
*/ */
@@ -1246,7 +873,7 @@ public class ConfigurationManager
System.exit(0); System.exit(0);
} }
else if ((argv.length == 4) && argv[0].equals("-module") && else if ((argv.length == 4) && argv[0].equals("-module") &&
argv[2].equals("-property")) argv[2].equals("-property"))
{ {
String val = getProperty(argv[1], argv[3]); String val = getProperty(argv[1], argv[3]);
@@ -1269,7 +896,7 @@ public class ConfigurationManager
System.exit(1); System.exit(1);
} }
private static void info(String string) private static void info(String string)
{ {
if (!isLog4jConfigured()) if (!isLog4jConfigured())
@@ -1320,8 +947,8 @@ public class ConfigurationManager
} }
/* /*
* Only current solution available to detect * Only current solution available to detect
* if log4j is truly configured. * if log4j is truly configured.
*/ */
private static boolean isLog4jConfigured() private static boolean isLog4jConfigured()
{ {

View File

@@ -7,9 +7,12 @@
*/ */
package org.dspace.core; package org.dspace.core;
import java.io.BufferedReader;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.File; import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; 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 * starts with "Subject:" the text on the right of the colon is used for the
* subject line. For example: * subject line. For example:
* <P> * <P>
* *
* <pre> * <pre>
* *
* # This is a comment line which is stripped * # This is a comment line which is stripped
* # * #
* # Parameters: {0} is a person's name * # Parameters: {0} is a person's name
* # {1} is the name of a submission * # {1} is the name of a submission
* # * #
* Subject: Example e-mail * Subject: Example e-mail
* *
* Dear {0}, * Dear {0},
* *
* Thank you for sending us your submission &quot;{1}&quot;. * Thank you for sending us your submission &quot;{1}&quot;.
* *
* </pre> * </pre>
* *
* <P> * <P>
* If the example code above was used to send this mail, the resulting mail * If the example code above was used to send this mail, the resulting mail
* would have the subject <code>Example e-mail</code> and the body would be: * would have the subject <code>Example e-mail</code> and the body would be:
* <P> * <P>
* *
* <pre> * <pre>
* *
* *
* Dear John, * Dear John,
* *
* Thank you for sending us your submission &quot;On the Testing of DSpace&quot;. * Thank you for sending us your submission &quot;On the Testing of DSpace&quot;.
* *
* </pre> * </pre>
* *
* <P> * <P>
* Note that parameters like <code>{0}</code> cannot be placed in the subject * Note that parameters like <code>{0}</code> cannot be placed in the subject
* of the e-mail; they won't get filled out. * of the e-mail; they won't get filled out.
* *
* *
* @author Robert Tansley * @author Robert Tansley
* @author Jim Downing - added attachment handling code * @author Jim Downing - added attachment handling code
* @version $Revision$ * @version $Revision$
*/ */
public class Email 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 */ /** The content of the message */
private String content; private String content;
@@ -143,7 +136,7 @@ public class Email
/** /**
* Add a recipient * Add a recipient
* *
* @param email * @param email
* the recipient's email address * the recipient's email address
*/ */
@@ -156,7 +149,7 @@ public class Email
* Set the content of the message. Setting this "resets" the message * Set the content of the message. Setting this "resets" the message
* formatting -<code>addArgument</code> will start. Comments and any * formatting -<code>addArgument</code> will start. Comments and any
* "Subject:" line must be stripped. * "Subject:" line must be stripped.
* *
* @param cnt * @param cnt
* the content of the message * the content of the message
*/ */
@@ -168,7 +161,7 @@ public class Email
/** /**
* Set the subject of the message * Set the subject of the message
* *
* @param s * @param s
* the subject of the message * the subject of the message
*/ */
@@ -179,7 +172,7 @@ public class Email
/** /**
* Set the reply-to email address * Set the reply-to email address
* *
* @param email * @param email
* the reply-to email address * the reply-to email address
*/ */
@@ -190,7 +183,7 @@ public class Email
/** /**
* Fill out the next argument in the template * Fill out the next argument in the template
* *
* @param arg * @param arg
* the value for the next argument * the value for the next argument
*/ */
@@ -224,7 +217,7 @@ public class Email
/** /**
* Sends the email. * Sends the email.
* *
* @throws MessagingException * @throws MessagingException
* if there was a problem sending the mail. * 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 no character set specified, attempt to retrieve a default
if (charset == null) if (charset == null)
{ {
charset = ConfigurationManager.getProperty("mail.charset"); charset = ConfigurationManager.getProperty("mail.charset");
} }
// Get session // Get session
Session session; Session session;
// Get the SMTP server authentication information // Get the SMTP server authentication information
String username = ConfigurationManager.getProperty("mail.server.username"); String username = ConfigurationManager.getProperty("mail.server.username");
String password = ConfigurationManager.getProperty("mail.server.password"); String password = ConfigurationManager.getProperty("mail.server.password");
if (username != null) if (username != null)
{ {
props.put("mail.smtp.auth", "true"); props.put("mail.smtp.auth", "true");
@@ -321,7 +314,7 @@ public class Email
{ {
message.setSubject(fullSubject); message.setSubject(fullSubject);
} }
// Add attachments // Add attachments
if (attachments.isEmpty()) if (attachments.isEmpty())
{ {
@@ -366,6 +359,78 @@ public class Email
Transport.send(message); Transport.send(message);
} }
/**
* Get the template for an email message. The message is suitable for
* inserting values using <code>java.text.MessageFormat</code>.
*
* @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 * 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. * Utility struct class for handling file attachments.
* *
* @author ojd20 * @author ojd20
* *
*/ */
private static class FileAttachment private static class FileAttachment
{ {
@@ -418,7 +483,7 @@ public class Email
String name; String name;
} }
/** /**
* Inner Class for SMTP authentication information * Inner Class for SMTP authentication information
*/ */
@@ -426,16 +491,16 @@ public class Email
{ {
// User name // User name
private String name; private String name;
// Password // Password
private String password; private String password;
public SMTPAuthenticator(String n, String p) public SMTPAuthenticator(String n, String p)
{ {
name = n; name = n;
password = p; password = p;
} }
protected PasswordAuthentication getPasswordAuthentication() protected PasswordAuthentication getPasswordAuthentication()
{ {
return new PasswordAuthentication(name, password); return new PasswordAuthentication(name, password);

View File

@@ -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)
{
}
}
}
}
}

View File

@@ -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;
}
}

View File

@@ -78,9 +78,9 @@ public class SolrServiceImpl implements SearchService, IndexingService {
public static final String FILTER_SEPARATOR = "\n|||\n"; public static final String FILTER_SEPARATOR = "\n|||\n";
public static final String AUTHORITY_SEPARATOR = "###"; public static final String AUTHORITY_SEPARATOR = "###";
public static final String STORE_SEPARATOR = "\n|||\n"; public static final String STORE_SEPARATOR = "\n|||\n";
public static final String VARIANTS_STORE_SEPARATOR = "###"; public static final String VARIANTS_STORE_SEPARATOR = "###";
/** /**
@@ -326,7 +326,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
try { try {
ItemIterator items = null; ItemIterator items = null;
try { try {
for (items = Item.findAllUnfiltered(context); items.hasNext();) for (items = Item.findAllUnfiltered(context); items.hasNext();)
{ {
Item item = items.next(); Item item = items.next();
indexContent(context, item, force); indexContent(context, item, force);
@@ -461,7 +461,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
if (recipient != null) if (recipient != null)
{ {
Email email = ConfigurationManager Email email = Email
.getEmail(I18nUtil.getEmailFilename( .getEmail(I18nUtil.getEmailFilename(
Locale.getDefault(), "internal_error")); Locale.getDefault(), "internal_error"));
email.addRecipient(recipient); email.addRecipient(recipient);
@@ -754,7 +754,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
SolrInputDocument doc = buildDocument(Constants.ITEM, item.getID(), handle, SolrInputDocument doc = buildDocument(Constants.ITEM, item.getID(), handle,
locations); locations);
log.debug("Building Item: " + handle); log.debug("Building Item: " + handle);
doc.addField("withdrawn", item.isWithdrawn()); doc.addField("withdrawn", item.isWithdrawn());
@@ -839,7 +839,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
toProjectionFields.add(projectionFieldsString); toProjectionFields.add(projectionFieldsString);
} }
} }
DCValue[] mydc = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); DCValue[] mydc = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (DCValue meta : mydc) for (DCValue meta : mydc)
{ {
@@ -848,7 +848,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
String value = meta.value; String value = meta.value;
if (value == null) if (value == null)
{ {
continue; continue;
} }
@@ -864,7 +864,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
{ {
continue; continue;
} }
String authority = null; String authority = null;
String preferedLabel = null; String preferedLabel = null;
List<String> variants = null; List<String> variants = null;
@@ -878,7 +878,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
meta.schema, meta.schema,
meta.element, meta.element,
meta.qualifier):Choices.CF_ACCEPTED; meta.qualifier):Choices.CF_ACCEPTED;
if (isAuthorityControlled && meta.authority != null if (isAuthorityControlled && meta.authority != null
&& meta.confidence >= minConfidence) && meta.confidence >= minConfidence)
{ {
@@ -965,7 +965,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} }
doc.addField(searchFilter.getIndexFieldName(), value); doc.addField(searchFilter.getIndexFieldName(), value);
doc.addField(searchFilter.getIndexFieldName() + "_keyword", value); doc.addField(searchFilter.getIndexFieldName() + "_keyword", value);
if (authority != null && preferedLabel == null) if (authority != null && preferedLabel == null)
{ {
doc.addField(searchFilter.getIndexFieldName() doc.addField(searchFilter.getIndexFieldName()
@@ -1006,7 +1006,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
+ AUTHORITY_SEPARATOR + authority); + AUTHORITY_SEPARATOR + authority);
} }
} }
//Add a dynamic fields for auto complete in search //Add a dynamic fields for auto complete in search
doc.addField(searchFilter.getIndexFieldName() + "_ac", doc.addField(searchFilter.getIndexFieldName() + "_ac",
value.toLowerCase() + separator + value); value.toLowerCase() + separator + value);
@@ -1024,7 +1024,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
+ "_ac", var.toLowerCase() + separator + "_ac", var.toLowerCase() + separator
+ var); + var);
} }
} }
if(searchFilter.getFilterType().equals(DiscoverySearchFilterFacet.FILTER_TYPE_FACET)) 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(VARIANTS_STORE_SEPARATOR);
variantsToStore.append(var); variantsToStore.append(var);
} }
} }
doc.addField( doc.addField(
field + "_stored", field + "_stored",
value + STORE_SEPARATOR + preferedLabel value + STORE_SEPARATOR + preferedLabel
@@ -1152,7 +1152,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
+ STORE_SEPARATOR + authority + STORE_SEPARATOR + authority
+ STORE_SEPARATOR + meta.language); + STORE_SEPARATOR + meta.language);
} }
if (meta.language != null && !meta.language.trim().equals("")) if (meta.language != null && !meta.language.trim().equals(""))
{ {
String langField = field + "." + meta.language; String langField = field + "." + meta.language;
@@ -1179,9 +1179,9 @@ public class SolrServiceImpl implements SearchService, IndexingService {
{ {
handlePrefix = "http://hdl.handle.net/"; handlePrefix = "http://hdl.handle.net/";
} }
doc.addField("publication_grp",values[0].value.replaceFirst(handlePrefix,"") ); doc.addField("publication_grp",values[0].value.replaceFirst(handlePrefix,"") );
} }
else else
{ {
@@ -1272,7 +1272,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} catch (RuntimeException e) } catch (RuntimeException e)
{ {
log.error("Error while writing item to discovery index: " + handle + " message:"+ e.getMessage(), 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); return search(context, dso, query, false);
} }
public DiscoverResult search(Context context, DSpaceObject dso, DiscoverQuery discoveryQuery, boolean includeWithdrawn) throws SearchServiceException { public DiscoverResult search(Context context, DSpaceObject dso, DiscoverQuery discoveryQuery, boolean includeWithdrawn) throws SearchServiceException {
if(dso != null) if(dso != null)
{ {
@@ -1460,7 +1460,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} }
solrQuery.setQuery(query); solrQuery.setQuery(query);
if (!includeWithdrawn) if (!includeWithdrawn)
{ {
solrQuery.addFilterQuery("NOT(withdrawn:true)"); solrQuery.addFilterQuery("NOT(withdrawn:true)");
@@ -1615,7 +1615,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} }
return null; return null;
} }
protected DiscoverResult retrieveResult(Context context, DiscoverQuery query, QueryResponse solrQueryResponse) throws SQLException { protected DiscoverResult retrieveResult(Context context, DiscoverQuery query, QueryResponse solrQueryResponse) throws SQLException {
DiscoverResult result = new DiscoverResult(); DiscoverResult result = new DiscoverResult();
@@ -1722,7 +1722,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
name = name.substring(0, name.lastIndexOf(']')).replaceAll("TO", "-"); name = name.substring(0, name.lastIndexOf(']')).replaceAll("TO", "-");
String filter = facetQuery.substring(facetQuery.indexOf('[')); String filter = facetQuery.substring(facetQuery.indexOf('['));
filter = filter.substring(0, filter.lastIndexOf(']') + 1); filter = filter.substring(0, filter.lastIndexOf(']') + 1);
Integer count = sortedFacetQueries.get(facetQuery); Integer count = sortedFacetQueries.get(facetQuery);
//No need to show empty years //No need to show empty years
@@ -1821,7 +1821,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
return new ArrayList<DSpaceObject>(0); return new ArrayList<DSpaceObject>(0);
} }
} }
public DiscoverFilterQuery toFilterQuery(Context context, String field, String operator, String value) throws SQLException{ public DiscoverFilterQuery toFilterQuery(Context context, String field, String operator, String value) throws SQLException{
DiscoverFilterQuery result = new DiscoverFilterQuery(); DiscoverFilterQuery result = new DiscoverFilterQuery();
@@ -1925,7 +1925,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} }
return results; return results;
} }
@Override @Override
public String toSortFieldIndex(String metadataField, String type) public String toSortFieldIndex(String metadataField, String type)
{ {
@@ -2020,7 +2020,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} }
return value; return value;
} }
protected String transformAuthorityValue(Context context, String field, String value) throws SQLException { protected String transformAuthorityValue(Context context, String field, String value) throws SQLException {
if (field.endsWith("_filter") || field.endsWith("_ac") if (field.endsWith("_filter") || field.endsWith("_ac")
|| field.endsWith("_acid")) || field.endsWith("_acid"))
@@ -2051,7 +2051,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} }
return null; return null;
} }
protected String transformSortValue(Context context, String field, String value) throws SQLException { protected String transformSortValue(Context context, String field, String value) throws SQLException {
if(field.equals("location.comm") || field.equals("location.coll")) if(field.equals("location.comm") || field.equals("location.coll"))
{ {

View File

@@ -31,9 +31,9 @@ import org.dspace.storage.rdbms.TableRow;
* randomly generated and thus hard to guess. When the user presents the token * 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 * back to the system, the AccountManager can use the token to determine the
* identity of the eperson. * identity of the eperson.
* *
* *NEW* now ignores expiration dates so that tokens never expire * *NEW* now ignores expiration dates so that tokens never expire
* *
* @author Peter Breton * @author Peter Breton
* @version $Revision$ * @version $Revision$
*/ */
@@ -49,12 +49,12 @@ public class AccountManager
/** /**
* Email registration info to the given email address. * Email registration info to the given email address.
* *
* Potential error conditions: Cannot create registration data in database * Potential error conditions: Cannot create registration data in database
* (throws SQLException) Error sending email (throws MessagingException) * (throws SQLException) Error sending email (throws MessagingException)
* Error reading email template (throws IOException) Authorization error * Error reading email template (throws IOException) Authorization error
* (throws AuthorizeException) * (throws AuthorizeException)
* *
* @param context * @param context
* DSpace context * DSpace context
* @param email * @param email
@@ -69,12 +69,12 @@ public class AccountManager
/** /**
* Email forgot password info to the given email address. * Email forgot password info to the given email address.
* *
* Potential error conditions: No EPerson with that email (returns null) * Potential error conditions: No EPerson with that email (returns null)
* Cannot create registration data in database (throws SQLException) Error * Cannot create registration data in database (throws SQLException) Error
* sending email (throws MessagingException) Error reading email template * sending email (throws MessagingException) Error reading email template
* (throws IOException) Authorization error (throws AuthorizeException) * (throws IOException) Authorization error (throws AuthorizeException)
* *
* @param context * @param context
* DSpace context * DSpace context
* @param email * @param email
@@ -93,11 +93,11 @@ public class AccountManager
* person by either the sendRegistrationInfo or sendForgotPasswordInfo * person by either the sendRegistrationInfo or sendForgotPasswordInfo
* methods. * methods.
* </p> * </p>
* *
* <p> * <p>
* If the token is not found return null. * If the token is not found return null.
* </p> * </p>
* *
* @param context * @param context
* DSpace context * DSpace context
* @param token * @param token
@@ -125,7 +125,7 @@ public class AccountManager
/** /**
* Return the e-mail address referred to by a token, or null if email * Return the e-mail address referred to by a token, or null if email
* address can't be found ignores expiration of token * address can't be found ignores expiration of token
* *
* @param context * @param context
* DSpace context * DSpace context
* @param token * @param token
@@ -153,7 +153,7 @@ public class AccountManager
/** /**
* Delete token. * Delete token.
* *
* @param context * @param context
* DSpace context * DSpace context
* @param token * @param token
@@ -171,16 +171,16 @@ public class AccountManager
/* /*
* THIS IS AN INTERNAL METHOD. THE SEND PARAMETER ALLOWS IT TO BE USED FOR * THIS IS AN INTERNAL METHOD. THE SEND PARAMETER ALLOWS IT TO BE USED FOR
* TESTING PURPOSES. * TESTING PURPOSES.
* *
* Send an info to the EPerson with the given email address. If isRegister * Send an info to the EPerson with the given email address. If isRegister
* is TRUE, this is registration email; otherwise, it is forgot-password * is TRUE, this is registration email; otherwise, it is forgot-password
* email. If send is TRUE, the email is sent; otherwise it is skipped. * email. If send is TRUE, the email is sent; otherwise it is skipped.
* *
* Potential error conditions: No EPerson with that email (returns null) * Potential error conditions: No EPerson with that email (returns null)
* Cannot create registration data in database (throws SQLException) Error * Cannot create registration data in database (throws SQLException) Error
* sending email (throws MessagingException) Error reading email template * sending email (throws MessagingException) Error reading email template
* (throws IOException) Authorization error (throws AuthorizeException) * (throws IOException) Authorization error (throws AuthorizeException)
* *
* @param context DSpace context @param email Email address to send the * @param context DSpace context @param email Email address to send the
* forgot-password email to @param isRegister If true, this is for * forgot-password email to @param isRegister If true, this is for
* registration; otherwise, it is for forgot-password @param send If true, * 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. * Send a DSpace message to the given email address.
* *
* If isRegister is <code>true</code>, this is registration email; * If isRegister is <code>true</code>, this is registration email;
* otherwise, it is a forgot-password email. * otherwise, it is a forgot-password email.
* *
* @param email * @param email
* The email address to mail to * The email address to mail to
* @param isRegister * @param isRegister
@@ -255,7 +255,7 @@ public class AccountManager
.append("token=").append(rd.getStringColumn("token")) .append("token=").append(rd.getStringColumn("token"))
.toString(); .toString();
Locale locale = context.getCurrentLocale(); Locale locale = context.getCurrentLocale();
Email bean = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, isRegister ? "register" Email bean = Email.getEmail(I18nUtil.getEmailFilename(locale, isRegister ? "register"
: "change_password")); : "change_password"));
bean.addRecipient(email); bean.addRecipient(email);
bean.addArgument(specialLink); bean.addArgument(specialLink);

View File

@@ -72,7 +72,7 @@ public class EPersonConsumer implements Consumer
try try
{ {
EPerson eperson = EPerson.find(context, id); 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.addRecipient(notifyRecipient);
adminEmail.addArgument(ConfigurationManager.getProperty("dspace.name")); 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.getFirstName() + " " + eperson.getLastName()); // Name
adminEmail.addArgument(eperson.getEmail()); adminEmail.addArgument(eperson.getEmail());
adminEmail.addArgument(new Date()); adminEmail.addArgument(new Date());
adminEmail.setReplyTo(eperson.getEmail()); adminEmail.setReplyTo(eperson.getEmail());
adminEmail.send(); adminEmail.send();

View File

@@ -48,7 +48,7 @@ import org.dspace.storage.rdbms.TableRowIterator;
/** /**
* Class defining methods for sending new item e-mail alerts to users * Class defining methods for sending new item e-mail alerts to users
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$ * @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 * Subscribe an e-person to a collection. An e-mail will be sent every day a
* new item appears in the collection. * new item appears in the collection.
* *
* @param context * @param context
* DSpace context * DSpace context
* @param eperson * @param eperson
@@ -76,10 +76,10 @@ public class Subscribe
|| ((context.getCurrentUser() != null) && (context || ((context.getCurrentUser() != null) && (context
.getCurrentUser().getID() == eperson.getID()))) .getCurrentUser().getID() == eperson.getID())))
{ {
// already subscribed? // already subscribed?
TableRowIterator r = DatabaseManager.query(context, TableRowIterator r = DatabaseManager.query(context,
"SELECT * FROM subscription WHERE eperson_id= ? " + "SELECT * FROM subscription WHERE eperson_id= ? " +
" AND collection_id= ? ", " AND collection_id= ? ",
eperson.getID(),collection.getID()); eperson.getID(),collection.getID());
try try
@@ -117,7 +117,7 @@ public class Subscribe
* Unsubscribe an e-person to a collection. Passing in <code>null</code> * Unsubscribe an e-person to a collection. Passing in <code>null</code>
* for the collection unsubscribes the e-person from all collections they * for the collection unsubscribes the e-person from all collections they
* are subscribed to. * are subscribed to.
* *
* @param context * @param context
* DSpace context * DSpace context
* @param eperson * @param eperson
@@ -141,10 +141,10 @@ public class Subscribe
eperson.getID()); eperson.getID());
} }
else else
{ {
DatabaseManager.updateQuery(context, DatabaseManager.updateQuery(context,
"DELETE FROM subscription WHERE eperson_id= ? " + "DELETE FROM subscription WHERE eperson_id= ? " +
"AND collection_id= ? ", "AND collection_id= ? ",
eperson.getID(),collection.getID()); eperson.getID(),collection.getID());
log.info(LogManager.getHeader(context, "unsubscribe", log.info(LogManager.getHeader(context, "unsubscribe",
@@ -161,7 +161,7 @@ public class Subscribe
/** /**
* Find out which collections an e-person is subscribed to * Find out which collections an e-person is subscribed to
* *
* @param context * @param context
* DSpace context * DSpace context
* @param eperson * @param eperson
@@ -195,7 +195,7 @@ public class Subscribe
tri.close(); tri.close();
} }
} }
Collection[] collArray = new Collection[collections.size()]; Collection[] collArray = new Collection[collections.size()];
return (Collection[]) collections.toArray(collArray); return (Collection[]) collections.toArray(collArray);
@@ -203,7 +203,7 @@ public class Subscribe
/** /**
* Is that e-person subscribed to that collection? * Is that e-person subscribed to that collection?
* *
* @param context * @param context
* DSpace context * DSpace context
* @param eperson * @param eperson
@@ -217,7 +217,7 @@ public class Subscribe
{ {
TableRowIterator tri = DatabaseManager.query(context, TableRowIterator tri = DatabaseManager.query(context,
"SELECT * FROM subscription WHERE eperson_id= ? " + "SELECT * FROM subscription WHERE eperson_id= ? " +
"AND collection_id= ? ", "AND collection_id= ? ",
eperson.getID(),collection.getID()); eperson.getID(),collection.getID());
try try
@@ -246,10 +246,10 @@ public class Subscribe
* <P> * <P>
* For example, if today's date is 2002-10-10 (in UTC) items made available * For example, if today's date is 2002-10-10 (in UTC) items made available
* during 2002-10-09 (UTC) will be included. * during 2002-10-09 (UTC) will be included.
* *
* @param context * @param context
* DSpace context object * DSpace context object
* @param test * @param test
*/ */
public static void processDaily(Context context, boolean test) throws SQLException, public static void processDaily(Context context, boolean test) throws SQLException,
IOException IOException
@@ -306,7 +306,7 @@ public class Subscribe
tri.close(); tri.close();
} }
} }
// Process the last person // Process the last person
if (currentEPerson != null) 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 * 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 * given collections, items that appeared yesterday. No e-mail is sent if
* there aren't any new items in any of the collections. * there aren't any new items in any of the collections.
* *
* @param context * @param context
* DSpace context object * DSpace context object
* @param eperson * @param eperson
* eperson to send to * eperson to send to
* @param collections * @param collections
* List of collection IDs (Integers) * List of collection IDs (Integers)
* @param test * @param test
*/ */
public static void sendEmail(Context context, EPerson eperson, public static void sendEmail(Context context, EPerson eperson,
List<Collection> collections, boolean test) throws IOException, MessagingException, List<Collection> collections, boolean test) throws IOException, MessagingException,
SQLException SQLException
{ {
// Get a resource bundle according to the eperson language preferences // 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); ResourceBundle labels = ResourceBundle.getBundle("Messages", supportedLocale);
// Get the start and end dates for yesterday // 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. // in truncation and roll to an earlier date than intended.
Calendar cal = Calendar.getInstance(TimeZone.getDefault()); Calendar cal = Calendar.getInstance(TimeZone.getDefault());
cal.setTime(new Date()); cal.setTime(new Date());
// What we actually want to pass to Harvest is "Midnight of yesterday in my current timezone" // 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, // 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". // at least in CDT, "7pm, the day before yesterday, in my current timezone".
cal.add(Calendar.HOUR, -24); cal.add(Calendar.HOUR, -24);
Date thisTimeYesterday = cal.getTime(); Date thisTimeYesterday = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0); cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0); cal.set(Calendar.SECOND, 0);
@@ -374,7 +374,7 @@ public class Subscribe
try { try {
boolean includeAll = ConfigurationManager.getBooleanProperty("harvest.includerestricted.subscription", true); boolean includeAll = ConfigurationManager.getBooleanProperty("harvest.includerestricted.subscription", true);
// we harvest all the changed item from yesterday until now // we harvest all the changed item from yesterday until now
List<HarvestedItemInfo> itemInfos = Harvest.harvest(context, c, new DCDate(midnightYesterday).toString(), null, 0, // Limit List<HarvestedItemInfo> itemInfos = Harvest.harvest(context, c, new DCDate(midnightYesterday).toString(), null, 0, // Limit
// and // and
@@ -386,7 +386,7 @@ public class Subscribe
false, // But not containers false, // But not containers
false, // Or withdrawals false, // Or withdrawals
includeAll); includeAll);
if (ConfigurationManager.getBooleanProperty("eperson.subscription.onlynew", false)) if (ConfigurationManager.getBooleanProperty("eperson.subscription.onlynew", false))
{ {
// get only the items archived yesterday // get only the items archived yesterday
@@ -394,7 +394,7 @@ public class Subscribe
} }
else else
{ {
// strip out the item archived today or // strip out the item archived today or
// not archived yesterday and modified today // not archived yesterday and modified today
itemInfos = filterOutToday(itemInfos); itemInfos = filterOutToday(itemInfos);
} }
@@ -411,19 +411,19 @@ public class Subscribe
{ {
isFirst = false; isFirst = false;
} }
emailText.append(labels.getString("org.dspace.eperson.Subscribe.new-items")).append(" ").append( emailText.append(labels.getString("org.dspace.eperson.Subscribe.new-items")).append(" ").append(
c.getMetadata("name")).append(": ").append( c.getMetadata("name")).append(": ").append(
itemInfos.size()).append("\n\n"); itemInfos.size()).append("\n\n");
for (int j = 0; j < itemInfos.size(); j++) for (int j = 0; j < itemInfos.size(); j++)
{ {
HarvestedItemInfo hii = (HarvestedItemInfo) itemInfos HarvestedItemInfo hii = (HarvestedItemInfo) itemInfos
.get(j); .get(j);
DCValue[] titles = hii.item.getDC("title", null, Item.ANY); DCValue[] titles = hii.item.getDC("title", null, Item.ANY);
emailText.append(" ").append(labels.getString("org.dspace.eperson.Subscribe.title")).append(" "); emailText.append(" ").append(labels.getString("org.dspace.eperson.Subscribe.title")).append(" ");
if (titles.length > 0) if (titles.length > 0)
{ {
emailText.append(titles[0].value); emailText.append(titles[0].value);
@@ -432,22 +432,22 @@ public class Subscribe
{ {
emailText.append(labels.getString("org.dspace.eperson.Subscribe.untitled")); emailText.append(labels.getString("org.dspace.eperson.Subscribe.untitled"));
} }
DCValue[] authors = hii.item.getDC("contributor", Item.ANY, DCValue[] authors = hii.item.getDC("contributor", Item.ANY,
Item.ANY); Item.ANY);
if (authors.length > 0) if (authors.length > 0)
{ {
emailText.append("\n ").append(labels.getString("org.dspace.eperson.Subscribe.authors")).append(" ").append( emailText.append("\n ").append(labels.getString("org.dspace.eperson.Subscribe.authors")).append(" ").append(
authors[0].value); authors[0].value);
for (int k = 1; k < authors.length; k++) for (int k = 1; k < authors.length; k++)
{ {
emailText.append("\n ").append( emailText.append("\n ").append(
authors[k].value); authors[k].value);
} }
} }
emailText.append("\n ").append(labels.getString("org.dspace.eperson.Subscribe.id")).append(" ").append( emailText.append("\n ").append(labels.getString("org.dspace.eperson.Subscribe.id")).append(" ").append(
HandleManager.getCanonicalForm(hii.handle)).append( HandleManager.getCanonicalForm(hii.handle)).append(
"\n\n"); "\n\n");
@@ -463,47 +463,47 @@ public class Subscribe
// Send an e-mail if there were any new items // Send an e-mail if there were any new items
if (emailText.length() > 0) if (emailText.length() > 0)
{ {
if(test) if(test)
{ {
log.info(LogManager.getHeader(context, "subscription:", "eperson=" + eperson.getEmail() )); log.info(LogManager.getHeader(context, "subscription:", "eperson=" + eperson.getEmail() ));
log.info(LogManager.getHeader(context, "subscription:", "text=" + emailText.toString() )); log.info(LogManager.getHeader(context, "subscription:", "text=" + emailText.toString() ));
} else { } else {
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "subscription")); Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "subscription"));
email.addRecipient(eperson.getEmail()); email.addRecipient(eperson.getEmail());
email.addArgument(emailText.toString()); email.addArgument(emailText.toString());
email.send(); email.send();
log.info(LogManager.getHeader(context, "sent_subscription", "eperson_id=" + eperson.getID() )); log.info(LogManager.getHeader(context, "sent_subscription", "eperson_id=" + eperson.getID() ));
} }
} }
} }
/** /**
* Method for invoking subscriptions via the command line * Method for invoking subscriptions via the command line
* *
* @param argv * @param argv
* command-line arguments, none used yet * 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."; String usage = "org.dspace.eperson.Subscribe [-t] or nothing to send out subscriptions.";
Options options = new Options(); Options options = new Options();
HelpFormatter formatter = new HelpFormatter(); HelpFormatter formatter = new HelpFormatter();
CommandLine line = null; CommandLine line = null;
{ {
Option opt = new Option("t", "test", false, "Run test session"); Option opt = new Option("t", "test", false, "Run test session");
opt.setRequired(false); opt.setRequired(false);
options.addOption(opt); options.addOption(opt);
} }
{ {
Option opt = new Option("h", "help", false, "Print this help message"); Option opt = new Option("h", "help", false, "Print this help message");
opt.setRequired(false); opt.setRequired(false);
@@ -527,14 +527,14 @@ public class Subscribe
formatter.printHelp(usage, options); formatter.printHelp(usage, options);
System.exit(1); System.exit(1);
} }
boolean test = line.hasOption("t"); boolean test = line.hasOption("t");
if(test) if(test)
{ {
log.setLevel(Level.DEBUG); log.setLevel(Level.DEBUG);
} }
Context context = null; Context context = null;
try try
@@ -556,7 +556,7 @@ public class Subscribe
} }
} }
} }
private static List<HarvestedItemInfo> filterOutToday(List<HarvestedItemInfo> completeList) private static List<HarvestedItemInfo> filterOutToday(List<HarvestedItemInfo> completeList)
{ {
log.debug("Filtering out all today item to leave new items list size=" log.debug("Filtering out all today item to leave new items list size="
@@ -614,7 +614,7 @@ public class Subscribe
} }
else else
{ {
// the item has been modified yesterday... // the item has been modified yesterday...
filteredList.add(infoObject); filteredList.add(infoObject);
} }
} }
@@ -632,11 +632,11 @@ public class Subscribe
Date thisTimeYesterday = new Date(System.currentTimeMillis() Date thisTimeYesterday = new Date(System.currentTimeMillis()
- (24 * 60 * 60 * 1000)); - (24 * 60 * 60 * 1000));
String yesterday = sdf.format(thisTimeYesterday); String yesterday = sdf.format(thisTimeYesterday);
for (HarvestedItemInfo infoObject : completeList) for (HarvestedItemInfo infoObject : completeList)
{ {
DCValue[] dateAccArr = infoObject.item.getMetadata("dc", "date", "accessioned", Item.ANY); DCValue[] dateAccArr = infoObject.item.getMetadata("dc", "date", "accessioned", Item.ANY);
if (dateAccArr != null && dateAccArr.length > 0) if (dateAccArr != null && dateAccArr.length > 0)
{ {
for(DCValue date : dateAccArr) for(DCValue date : dateAccArr)
@@ -656,9 +656,9 @@ public class Subscribe
} }
} }
} }
} }
else else
{ {

File diff suppressed because it is too large Load Diff

View File

@@ -74,18 +74,18 @@ import org.dspace.app.util.Util;
* collections, communities, etc. It is meant to either be invoked from the * collections, communities, etc. It is meant to either be invoked from the
* command line (see dspace/bin/index-all) or via the indexContent() methods * command line (see dspace/bin/index-all) or via the indexContent() methods
* within DSpace. * within DSpace.
* *
* As of 1.4.2 this class has new incremental update of index functionality * 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. * 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 * 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) * 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 attain the lock before giving up and logging the failure to log4j and
* to the DSpace administrator email account. * to the DSpace administrator email account.
* *
* The Administrator can choose to run DSIndexer in a cron that * 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 * repeats regularly, a failed attempt to index from the UI will be "caught" up
* on in that cron. * on in that cron.
* *
* @author Mark Diggory * @author Mark Diggory
* @author Graham Triggs * @author Graham Triggs
*/ */
@@ -127,11 +127,11 @@ public class DSIndexer
this.type = type; this.type = type;
} }
} }
private static String indexDirectory = ConfigurationManager.getProperty("search.dir"); private static String indexDirectory = ConfigurationManager.getProperty("search.dir");
private static int maxfieldlength = -1; private static int maxfieldlength = -1;
// TODO: Support for analyzers per language, or multiple indices // TODO: Support for analyzers per language, or multiple indices
/** The analyzer for this DSpace instance */ /** The analyzer for this DSpace instance */
private static volatile Analyzer analyzer = null; private static volatile Analyzer analyzer = null;
@@ -154,13 +154,13 @@ public class DSIndexer
}; };
static { static {
// calculate maxfieldlength // calculate maxfieldlength
if (ConfigurationManager.getProperty("search.maxfieldlength") != null) if (ConfigurationManager.getProperty("search.maxfieldlength") != null)
{ {
maxfieldlength = ConfigurationManager.getIntProperty("search.maxfieldlength"); maxfieldlength = ConfigurationManager.getIntProperty("search.maxfieldlength");
} }
// read in indexes from the config // read in indexes from the config
ArrayList<String> indexConfigList = new ArrayList<String>(); ArrayList<String> indexConfigList = new ArrayList<String>();
@@ -169,24 +169,24 @@ public class DSIndexer
{ {
indexConfigList.add(ConfigurationManager.getProperty("search.index." + i)); indexConfigList.add(ConfigurationManager.getProperty("search.index." + i));
} }
if (indexConfigList.size() > 0) if (indexConfigList.size() > 0)
{ {
indexConfigArr = new IndexConfig[indexConfigList.size()]; indexConfigArr = new IndexConfig[indexConfigList.size()];
for (int i = 0; i < indexConfigList.size(); i++) for (int i = 0; i < indexConfigList.size(); i++)
{ {
indexConfigArr[i] = new IndexConfig(); indexConfigArr[i] = new IndexConfig();
String index = indexConfigList.get(i); String index = indexConfigList.get(i);
String[] configLine = index.split(":"); String[] configLine = index.split(":");
indexConfigArr[i].indexName = configLine[0]; indexConfigArr[i].indexName = configLine[0];
// Get the schema, element and qualifier for the index // Get the schema, element and qualifier for the index
// TODO: Should check valid schema, element, qualifier? // TODO: Should check valid schema, element, qualifier?
String[] parts = configLine[1].split("\\."); String[] parts = configLine[1].split("\\.");
switch (parts.length) switch (parts.length)
{ {
case 3: case 3:
@@ -208,7 +208,7 @@ public class DSIndexer
} }
} }
} }
/* /*
* Increase the default write lock so that Indexing can be interrupted. * 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 * If the handle for the "dso" already exists in the index, and
* the "dso" has a lastModified timestamp that is newer than * the "dso" has a lastModified timestamp that is newer than
* the document in the index then it is updated, otherwise a * the document in the index then it is updated, otherwise a
* new document is added. * new document is added.
* *
* @param context Users Context * @param context Users Context
* @param dso DSpace Object (Item, Collection or Community * @param dso DSpace Object (Item, Collection or Community
* @throws SQLException * @throws SQLException
@@ -261,10 +261,10 @@ public class DSIndexer
} }
/** /**
* If the handle for the "dso" already exists in the index, and * If the handle for the "dso" already exists in the index, and
* the "dso" has a lastModified timestamp that is newer than * the "dso" has a lastModified timestamp that is newer than
* the document in the index then it is updated, otherwise a * the document in the index then it is updated, otherwise a
* new document is added. * new document is added.
* *
* @param context Users Context * @param context Users Context
* @param dso DSpace Object (Item, Collection or Community * @param dso DSpace Object (Item, Collection or Community
* @param force Force update even if not stale. * @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 * unIndex removes an Item, Collection, or Community only works if the
* DSpaceObject has a handle (uses the handle for its unique ID) * DSpaceObject has a handle (uses the handle for its unique ID)
* *
* @param context DSpace context * @param context DSpace context
* @param dso DSpace Object, can be Community, Item, or Collection * @param dso DSpace Object, can be Community, Item, or Collection
* @throws SQLException * @throws SQLException
@@ -311,9 +311,9 @@ public class DSIndexer
/** /**
* Unindex a Document in the Lucene Index. * Unindex a Document in the Lucene Index.
* *
* @param context * @param context
* @param handle * @param handle
* @throws SQLException * @throws SQLException
* @throws IOException * @throws IOException
*/ */
@@ -336,7 +336,7 @@ public class DSIndexer
// handle!"); // handle!");
} }
} }
/** /**
* reIndexContent removes something from the index, then re-indexes it * reIndexContent removes something from the index, then re-indexes it
* *
@@ -356,10 +356,10 @@ public class DSIndexer
emailException(exception); emailException(exception);
} }
} }
/** /**
* create full index - wiping old index * create full index - wiping old index
* *
* @param c context to use * @param c context to use
*/ */
public static void createIndex(Context c) throws SQLException, IOException public static void createIndex(Context c) throws SQLException, IOException
@@ -367,15 +367,15 @@ public class DSIndexer
/* Create a new index, blowing away the old. */ /* Create a new index, blowing away the old. */
openIndex(true).close(); openIndex(true).close();
/* Reindex all content preemptively. */ /* Reindex all content preemptively. */
DSIndexer.updateIndex(c, true); 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! * filehandle usage and keep performance fast!
* *
* @param c Users Context * @param c Users Context
* @throws SQLException * @throws SQLException
* @throws IOException * @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 * content from the whole index
* *
* @param args * @param args
* the command-line arguments, none used * the command-line arguments, none used
* @throws IOException * @throws IOException
* @throws SQLException * @throws SQLException
*/ */
public static void main(String[] args) throws SQLException, IOException 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 * Iterates over all Items, Collections and Communities. And updates
* them in the index. Uses decaching to control memory footprint. * them in the index. Uses decaching to control memory footprint.
* Uses indexContent and isStale ot check state of item in index. * Uses indexContent and isStale ot check state of item in index.
* *
* @param context * @param context
*/ */
public static void updateIndex(Context context) { public static void updateIndex(Context context) {
updateIndex(context,false); updateIndex(context,false);
} }
/** /**
* Iterates over all Items, Collections and Communities. And updates * Iterates over all Items, Collections and Communities. And updates
* them in the index. Uses decaching to control memory footprint. * them in the index. Uses decaching to control memory footprint.
* Uses indexContent and isStale to check state of item in index. * Uses indexContent and isStale to check state of item in index.
* *
* At first it may appear counterintuitive to have an IndexWriter/Reader * At first it may appear counterintuitive to have an IndexWriter/Reader
* opened and closed on each DSO. But this allows the UI processes * 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 * to step in and attain a lock and write to the index even if other
* processes/jvms are running a reindex. * processes/jvms are running a reindex.
* *
* @param context * @param context
* @param force * @param force
*/ */
public static void updateIndex(Context context, boolean force) { public static void updateIndex(Context context, boolean force) {
try try
@@ -568,19 +568,19 @@ public class DSIndexer
log.error(e.getMessage(), e); 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. * are in database, if not, they are removed.
* *
* @param context * @param context
* @throws IOException * @throws IOException
* @throws SQLException * @throws SQLException
*/ */
public static void cleanIndex(Context context) throws IOException, SQLException { public static void cleanIndex(Context context) throws IOException, SQLException {
IndexReader reader = DSQuery.getIndexReader(); IndexReader reader = DSQuery.getIndexReader();
for(int i = 0 ; i < reader.numDocs(); i++) for(int i = 0 ; i < reader.numDocs(); i++)
{ {
if(!reader.isDeleted(i)) if(!reader.isDeleted(i))
@@ -610,7 +610,7 @@ public class DSIndexer
} }
} }
} }
/** /**
* Get the Lucene analyzer to use according to current configuration (or * Get the Lucene analyzer to use according to current configuration (or
* default). TODO: Should have multiple analyzers (and maybe indices?) for * default). TODO: Should have multiple analyzers (and maybe indices?) for
@@ -844,7 +844,7 @@ public class DSIndexer
.getProperty("alert.recipient"); .getProperty("alert.recipient");
if (recipient != null) { 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.addRecipient(recipient);
email.addArgument(ConfigurationManager email.addArgument(ConfigurationManager
.getProperty("dspace.url")); .getProperty("dspace.url"));
@@ -871,11 +871,11 @@ public class DSIndexer
} }
} }
/** /**
* Is stale checks the lastModified time stamp in the database and the index * Is stale checks the lastModified time stamp in the database and the index
* to determine if the index is stale. * to determine if the index is stale.
* *
* @param lastModified * @param lastModified
* @throws SQLException * @throws SQLException
* @throws IOException * @throws IOException
@@ -883,14 +883,14 @@ public class DSIndexer
private static boolean requiresIndexing(Term t, Date lastModified) private static boolean requiresIndexing(Term t, Date lastModified)
throws SQLException, IOException throws SQLException, IOException
{ {
boolean reindexItem = false; boolean reindexItem = false;
boolean inIndex = false; boolean inIndex = false;
IndexReader ir = DSQuery.getIndexReader(); IndexReader ir = DSQuery.getIndexReader();
TermDocs docs = ir.termDocs(t); TermDocs docs = ir.termDocs(t);
while(docs.next()) while(docs.next())
{ {
inIndex = true; inIndex = true;
@@ -899,7 +899,7 @@ public class DSIndexer
Field lastIndexed = doc.getField(LAST_INDEXED_FIELD); Field lastIndexed = doc.getField(LAST_INDEXED_FIELD);
if (lastIndexed == null || Long.parseLong(lastIndexed.stringValue()) < if (lastIndexed == null || Long.parseLong(lastIndexed.stringValue()) <
lastModified.getTime()) { lastModified.getTime()) {
reindexItem = true; reindexItem = true;
} }
@@ -933,7 +933,7 @@ public class DSIndexer
{ {
writer.setMaxFieldLength(maxfieldlength); writer.setMaxFieldLength(maxfieldlength);
} }
return writer; return writer;
} }
@@ -1069,7 +1069,7 @@ public class DSIndexer
mydc = item.getMetadata(indexConfigArr[i].schema, indexConfigArr[i].element, indexConfigArr[i].qualifier, Item.ANY); 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) //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)){ if ("inputform".equalsIgnoreCase(indexConfigArr[i].type)){
@@ -1110,7 +1110,7 @@ public class DSIndexer
} }
for (j = 0; j < mydc.length; j++) for (j = 0; j < mydc.length; j++)
{ {
if (!StringUtils.isEmpty(mydc[j].value)) 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 * Helper function to retrieve a date using a best guess of the potential date encodings on a field
* *
* @param t * @param t
* @return * @return
*/ */
@@ -1441,7 +1441,7 @@ public class DSIndexer
log.error("Unable to parse date format", pe); log.error("Unable to parse date format", pe);
} }
} }
return null; return null;
} }

View File

@@ -46,26 +46,26 @@ import org.dspace.utils.DSpace;
/** /**
* Workflow state machine * Workflow state machine
* *
* Notes: * Notes:
* *
* Determining item status from the database: * Determining item status from the database:
* *
* When an item has not been submitted yet, it is in the user's personal * 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.) * 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 * 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 * WorkflowItem table pointing to it. The state of the workflow can be
* determined by looking at WorkflowItem.getState() * determined by looking at WorkflowItem.getState()
* *
* When a submission is complete, the WorkflowItem pointing to the item is * 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 * destroyed and the archive() method is called, which hooks the item up to the
* archive. * archive.
* *
* Notification: When an item enters a state that requires notification, * Notification: When an item enters a state that requires notification,
* (WFSTATE_STEP1POOL, WFSTATE_STEP2POOL, WFSTATE_STEP3POOL,) the workflow needs * (WFSTATE_STEP1POOL, WFSTATE_STEP2POOL, WFSTATE_STEP3POOL,) the workflow needs
* to notify the appropriate groups that they have a pending task to claim. * 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 * Revealing lists of approvers, editors, and reviewers. A method could be added
* to do this, but it isn't strictly necessary. (say public List * to do this, but it isn't strictly necessary. (say public List
* getStateEPeople( WorkflowItem wi, int state ) could return people affected by * 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 * startWorkflow() begins a workflow - in a single transaction do away with
* the PersonalWorkspace entry and turn it into a WorkflowItem. * the PersonalWorkspace entry and turn it into a WorkflowItem.
* *
* @param c * @param c
* Context * Context
* @param wsi * @param wsi
@@ -176,7 +176,7 @@ public class WorkflowManager
// now get the workflow started // now get the workflow started
wfi.setState(WFSTATE_SUBMIT); wfi.setState(WFSTATE_SUBMIT);
advance(c, wfi, null); advance(c, wfi, null);
// Return the workflow item // Return the workflow item
return wfi; return wfi;
@@ -201,7 +201,7 @@ public class WorkflowManager
* getOwnedTasks() returns a List of WorkflowItems containing the tasks * getOwnedTasks() returns a List of WorkflowItems containing the tasks
* claimed and owned by an EPerson. The GUI displays this info on the * claimed and owned by an EPerson. The GUI displays this info on the
* MyDSpace page. * MyDSpace page.
* *
* @param e * @param e
* The EPerson we want to fetch owned tasks for. * The EPerson we want to fetch owned tasks for.
*/ */
@@ -212,7 +212,7 @@ public class WorkflowManager
String myquery = "SELECT * FROM WorkflowItem WHERE owner= ? "; String myquery = "SELECT * FROM WorkflowItem WHERE owner= ? ";
TableRowIterator tri = DatabaseManager.queryTable(c, TableRowIterator tri = DatabaseManager.queryTable(c,
"workflowitem", myquery,e.getID()); "workflowitem", myquery,e.getID());
try try
@@ -236,7 +236,7 @@ public class WorkflowManager
/** /**
* getPooledTasks() returns a List of WorkflowItems an EPerson could claim * getPooledTasks() returns a List of WorkflowItems an EPerson could claim
* (as a reviewer, etc.) for display on a user's MyDSpace page. * (as a reviewer, etc.) for display on a user's MyDSpace page.
* *
* @param e * @param e
* The Eperson we want to fetch the pooled tasks for. * The Eperson we want to fetch the pooled tasks for.
*/ */
@@ -265,13 +265,13 @@ public class WorkflowManager
tri.close(); tri.close();
} }
} }
return mylist; return mylist;
} }
/** /**
* claim() claims a workflow task for an EPerson * claim() claims a workflow task for an EPerson
* *
* @param wi * @param wi
* WorkflowItem to do the claim on * WorkflowItem to do the claim on
* @param e * @param e
@@ -322,7 +322,7 @@ public class WorkflowManager
* the item arrives at the submit state, then remove the WorkflowItem and * 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 * call the archive() method to put it in the archive, and email notify the
* submitter of a successful submission * submitter of a successful submission
* *
* @param c * @param c
* Context * Context
* @param wi * @param wi
@@ -335,26 +335,26 @@ public class WorkflowManager
{ {
advance(c, wi, e, true, true); advance(c, wi, e, true, true);
} }
/** /**
* advance() sends an item forward in the workflow (reviewers, * advance() sends an item forward in the workflow (reviewers,
* approvers, and editors all do an 'approve' to move the item forward) if * 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 * 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 * call the archive() method to put it in the archive, and email notify the
* submitter of a successful submission * submitter of a successful submission
* *
* @param c * @param c
* Context * Context
* @param wi * @param wi
* WorkflowItem do do the approval on * WorkflowItem do do the approval on
* @param e * @param e
* EPerson doing the approval * EPerson doing the approval
* *
* @param curate * @param curate
* boolean indicating whether curation tasks should be done * boolean indicating whether curation tasks should be done
* *
* @param record * @param record
* boolean indicating whether to record action * boolean indicating whether to record action
*/ */
public static boolean advance(Context c, WorkflowItem wi, EPerson e, public static boolean advance(Context c, WorkflowItem wi, EPerson e,
boolean curate, boolean record) boolean curate, boolean record)
@@ -362,7 +362,7 @@ public class WorkflowManager
{ {
int taskstate = wi.getState(); int taskstate = wi.getState();
boolean archived = false; boolean archived = false;
// perform curation tasks if needed // perform curation tasks if needed
if (curate && WorkflowCurator.needsCuration(wi)) if (curate && WorkflowCurator.needsCuration(wi))
{ {
@@ -381,9 +381,9 @@ public class WorkflowManager
{ {
case WFSTATE_SUBMIT: case WFSTATE_SUBMIT:
archived = doState(c, wi, WFSTATE_STEP1POOL, e); archived = doState(c, wi, WFSTATE_STEP1POOL, e);
break; break;
case WFSTATE_STEP1: case WFSTATE_STEP1:
// authorize DSpaceActions.SUBMIT_REVIEW // authorize DSpaceActions.SUBMIT_REVIEW
@@ -430,7 +430,7 @@ public class WorkflowManager
/** /**
* unclaim() returns an owned task/item to the pool * unclaim() returns an owned task/item to the pool
* *
* @param c * @param c
* Context * Context
* @param wi * @param wi
@@ -481,7 +481,7 @@ public class WorkflowManager
* abort() aborts a workflow, completely deleting it (administrator do this) * 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 * (it will basically do a reject from any state - the item ends up back in
* the user's PersonalWorkspace * the user's PersonalWorkspace
* *
* @param c * @param c
* Context * Context
* @param wi * @param wi
@@ -540,7 +540,7 @@ public class WorkflowManager
{ {
// get a list of all epeople in group (or any subgroups) // get a list of all epeople in group (or any subgroups)
EPerson[] epa = Group.allMembers(c, mygroup); EPerson[] epa = Group.allMembers(c, mygroup);
// there were reviewers, change the state // there were reviewers, change the state
// and add them to the list // and add them to the list
createTasks(c, wi, epa); createTasks(c, wi, epa);
@@ -582,7 +582,7 @@ public class WorkflowManager
{ {
//get a list of all epeople in group (or any subgroups) //get a list of all epeople in group (or any subgroups)
EPerson[] epa = Group.allMembers(c, mygroup); EPerson[] epa = Group.allMembers(c, mygroup);
// there were approvers, change the state // there were approvers, change the state
// timestamp, and add them to the list // timestamp, and add them to the list
createTasks(c, wi, epa); createTasks(c, wi, epa);
@@ -619,7 +619,7 @@ public class WorkflowManager
{ {
// get a list of all epeople in group (or any subgroups) // get a list of all epeople in group (or any subgroups)
EPerson[] epa = Group.allMembers(c, mygroup); EPerson[] epa = Group.allMembers(c, mygroup);
// there were editors, change the state // there were editors, change the state
// timestamp, and add them to the list // timestamp, and add them to the list
createTasks(c, wi, epa); createTasks(c, wi, epa);
@@ -707,7 +707,7 @@ public class WorkflowManager
* Commit the contained item to the main archive. The item is associated * Commit the contained item to the main archive. The item is associated
* with the relevant collection, added to the search index, and any other * with the relevant collection, added to the search index, and any other
* tasks such as assigning dates are performed. * tasks such as assigning dates are performed.
* *
* @return the fully archived item. * @return the fully archived item.
*/ */
private static Item archive(Context c, WorkflowItem wfi) private static Item archive(Context c, WorkflowItem wfi)
@@ -742,8 +742,8 @@ public class WorkflowManager
EPerson ep = i.getSubmitter(); EPerson ep = i.getSubmitter();
// Get the Locale // Get the Locale
Locale supportedLocale = I18nUtil.getEPersonLocale(ep); 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 // Get the item handle to email to user
String handle = HandleManager.findHandle(c, i); 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 * Return the workflow item to the workspace of the submitter. The workflow
* item is removed, and a workspace item created. * item is removed, and a workspace item created.
* *
* @param c * @param c
* Context * Context
* @param wfi * @param wfi
@@ -825,7 +825,7 @@ public class WorkflowManager
* rejects an item - rejection means undoing a submit - WorkspaceItem is * rejects an item - rejection means undoing a submit - WorkspaceItem is
* created, and the WorkflowItem is removed, user is emailed * created, and the WorkflowItem is removed, user is emailed
* rejection_message. * rejection_message.
* *
* @param c * @param c
* Context * Context
* @param wi * @param wi
@@ -899,10 +899,10 @@ public class WorkflowManager
static void deleteTasks(Context c, WorkflowItem wi) throws SQLException static void deleteTasks(Context c, WorkflowItem wi) throws SQLException
{ {
String myrequest = "DELETE FROM TaskListItem WHERE workflow_id= ? "; String myrequest = "DELETE FROM TaskListItem WHERE workflow_id= ? ";
DatabaseManager.updateQuery(c, myrequest, wi.getID()); DatabaseManager.updateQuery(c, myrequest, wi.getID());
} }
// send notices of curation activity // send notices of curation activity
public static void notifyOfCuration(Context c, WorkflowItem wi, EPerson[] epa, public static void notifyOfCuration(Context c, WorkflowItem wi, EPerson[] epa,
String taskName, String action, String message) throws SQLException, IOException String taskName, String action, String message) throws SQLException, IOException
@@ -921,7 +921,7 @@ public class WorkflowManager
for (int i = 0; i < epa.length; i++) for (int i = 0; i < epa.length; i++)
{ {
Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]); Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale,
"flowtask_notify")); "flowtask_notify"));
email.addArgument(title); email.addArgument(title);
email.addArgument(coll.getMetadata("name")); email.addArgument(coll.getMetadata("name"));
@@ -935,7 +935,7 @@ public class WorkflowManager
} }
catch (MessagingException e) 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())); " of workflow_item_id" + wi.getID()));
} }
} }
@@ -971,7 +971,7 @@ public class WorkflowManager
for (int i = 0; i < epa.length; i++) for (int i = 0; i < epa.length; i++)
{ {
Locale supportedLocale = I18nUtil.getEPersonLocale(epa[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(title);
email.addArgument(coll.getMetadata("name")); email.addArgument(coll.getMetadata("name"));
email.addArgument(submitter); email.addArgument(submitter);
@@ -981,17 +981,17 @@ public class WorkflowManager
{ {
case WFSTATE_STEP1POOL: case WFSTATE_STEP1POOL:
message = messages.getString("org.dspace.workflow.WorkflowManager.step1"); message = messages.getString("org.dspace.workflow.WorkflowManager.step1");
break; break;
case WFSTATE_STEP2POOL: case WFSTATE_STEP2POOL:
message = messages.getString("org.dspace.workflow.WorkflowManager.step2"); message = messages.getString("org.dspace.workflow.WorkflowManager.step2");
break; break;
case WFSTATE_STEP3POOL: case WFSTATE_STEP3POOL:
message = messages.getString("org.dspace.workflow.WorkflowManager.step3"); message = messages.getString("org.dspace.workflow.WorkflowManager.step3");
break; break;
} }
email.addArgument(message); email.addArgument(message);
@@ -1030,7 +1030,7 @@ public class WorkflowManager
// Get rejector's name // Get rejector's name
String rejector = getEPersonName(e); String rejector = getEPersonName(e);
Locale supportedLocale = I18nUtil.getEPersonLocale(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.addRecipient(getSubmitterEPerson(wi).getEmail());
email.addArgument(title); email.addArgument(title);
@@ -1072,7 +1072,7 @@ public class WorkflowManager
/** /**
* get the title of the item in this workflow * get the title of the item in this workflow
* *
* @param wi the workflow item object * @param wi the workflow item object
*/ */
public static String getItemTitle(WorkflowItem wi) throws SQLException 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 * get the name of the eperson who started this workflow
* *
* @param wi the workflow item * @param wi the workflow item
*/ */
public static String getSubmitterName(WorkflowItem wi) throws SQLException public static String getSubmitterName(WorkflowItem wi) throws SQLException

View File

@@ -156,7 +156,7 @@ public class WorkflowUtils extends Util{
if (recipient != null) 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.addRecipient(recipient);
email.addArgument(ConfigurationManager email.addArgument(ConfigurationManager

View File

@@ -107,7 +107,7 @@ public class XmlWorkflowManager {
// suppress email, and delete key // suppress email, and delete key
noEMail.remove(wfi.getItem().getID()); noEMail.remove(wfi.getItem().getID());
} else { } else {
Email mail = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), emailTemplate)); Email mail = Email.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), emailTemplate));
for (String argument : arguments) { for (String argument : arguments) {
mail.addArgument(argument); mail.addArgument(argument);
} }
@@ -396,7 +396,7 @@ public class XmlWorkflowManager {
EPerson ep = i.getSubmitter(); EPerson ep = i.getSubmitter();
// Get the Locale // Get the Locale
Locale supportedLocale = I18nUtil.getEPersonLocale(ep); 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 // Get the item handle to email to user
String handle = HandleManager.findHandle(c, i); String handle = HandleManager.findHandle(c, i);
@@ -856,7 +856,7 @@ public class XmlWorkflowManager {
// Get rejector's name // Get rejector's name
String rejector = getEPersonName(e); String rejector = getEPersonName(e);
Locale supportedLocale = I18nUtil.getEPersonLocale(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.addRecipient(wi.getSubmitter().getEmail());
email.addArgument(title); email.addArgument(title);

View File

@@ -20,8 +20,8 @@ import static org.hamcrest.CoreMatchers.*;
import mockit.*; import mockit.*;
import org.dspace.app.util.AuthorizeUtil; import org.dspace.app.util.AuthorizeUtil;
import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.LicenseManager;
/** /**
* Unit Tests for class Collection * Unit Tests for class Collection
@@ -198,7 +198,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
*/ */
@Test @Test
@Override @Override
public void testGetID() public void testGetID()
{ {
assertTrue("testGetID 0", c.getID() >= 1); assertTrue("testGetID 0", c.getID() >= 1);
} }
@@ -208,7 +208,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
*/ */
@Test @Test
@Override @Override
public void testGetHandle() public void testGetHandle()
{ {
//default instance has a random handle //default instance has a random handle
assertTrue("testGetHandle 0", c.getHandle().contains("123456789/")); assertTrue("testGetHandle 0", c.getHandle().contains("123456789/"));
@@ -662,17 +662,17 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of getLicense method, of class Collection. * Test of getLicense method, of class Collection.
*/ */
@Test @Test
public void testGetLicense() public void testGetLicense()
{ {
assertThat("testGetLicense 0", c.getLicense(), notNullValue()); 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 of getLicenseCollection method, of class Collection.
*/ */
@Test @Test
public void testGetLicenseCollection() public void testGetLicenseCollection()
{ {
assertThat("testGetLicenseCollection 0", c.getLicenseCollection(), notNullValue()); assertThat("testGetLicenseCollection 0", c.getLicenseCollection(), notNullValue());
assertThat("testGetLicenseCollection 1", c.getLicenseCollection(), equalTo("")); assertThat("testGetLicenseCollection 1", c.getLicenseCollection(), equalTo(""));
@@ -682,7 +682,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of hasCustomLicense method, of class Collection. * Test of hasCustomLicense method, of class Collection.
*/ */
@Test @Test
public void testHasCustomLicense() public void testHasCustomLicense()
{ {
assertFalse("testHasCustomLicense 0", c.hasCustomLicense()); assertFalse("testHasCustomLicense 0", c.hasCustomLicense());
} }
@@ -691,7 +691,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of setLicense method, of class Collection. * Test of setLicense method, of class Collection.
*/ */
@Test @Test
public void testSetLicense() public void testSetLicense()
{ {
String license = "license for test"; String license = "license for test";
c.setLicense(license); c.setLicense(license);
@@ -705,7 +705,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of getTemplateItem method, of class Collection. * Test of getTemplateItem method, of class Collection.
*/ */
@Test @Test
public void testGetTemplateItem() throws Exception public void testGetTemplateItem() throws Exception
{ {
assertThat("testGetTemplateItem 0", c.getTemplateItem(), nullValue()); assertThat("testGetTemplateItem 0", c.getTemplateItem(), nullValue());
} }
@@ -1336,7 +1336,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
assertFalse("testCanEditBooleanNoAuth_boolean 0",c.canEditBoolean(false)); assertFalse("testCanEditBooleanNoAuth_boolean 0",c.canEditBoolean(false));
} }
/** /**
* Test of canEditBoolean method, of class Collection. * Test of canEditBoolean method, of class Collection.
*/ */
@@ -1789,7 +1789,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
*/ */
@Test @Test
@Override @Override
public void testGetType() public void testGetType()
{ {
assertThat("testGetType 0", c.getType(), equalTo(Constants.COLLECTION)); 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 of findAuthorized method, of class Collection.
*/ */
@Test @Test
public void testFindAuthorized() throws Exception public void testFindAuthorized() throws Exception
{ {
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
Community com = Community.create(null, context); Community com = Community.create(null, context);

View File

@@ -13,13 +13,13 @@ import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.core.ConfigurationManager;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.core.LicenseManager;
import org.junit.*; import org.junit.*;
import static org.junit.Assert.* ; import static org.junit.Assert.* ;
import static org.hamcrest.CoreMatchers.*; 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 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 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 templateLongResult = "Template license: first name last name test@email.com arg1 arg2 arg3 arg4";
String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); String defaultLicense = LicenseManager.getDefaultSubmissionLicense();
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
//TODO: the tested method doesn't verify the input, will throw NPE if any parameter is null //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<String, Object>(); additionalInfo = new LinkedHashMap<String, Object>();
additionalInfo.put("arg1", "arg1"); additionalInfo.put("arg1", "arg1");
additionalInfo.put("arg2", "arg2"); additionalInfo.put("arg2", "arg2");
additionalInfo.put("arg3", "arg3"); additionalInfo.put("arg3", "arg3");
additionalInfo.put("arg4", "arg4"); additionalInfo.put("arg4", "arg4");
assertThat("testGetLicenseText_5args 5", LicenseUtils.getLicenseText(locale, collection, item, person, additionalInfo), equalTo(templateLongResult)); assertThat("testGetLicenseText_5args 5", LicenseUtils.getLicenseText(locale, collection, item, person, additionalInfo), equalTo(templateLongResult));
context.restoreAuthSystemState(); 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 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 templateResult = "Template license: first name last name test@email.com ";
String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); String defaultLicense = LicenseManager.getDefaultSubmissionLicense();
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
//TODO: the tested method doesn't verify the input, will throw NPE if any parameter is null //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 = EPerson.create(context);
person.setFirstName("first name"); person.setFirstName("first name");
person.setLastName("last 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)); assertThat("testGetLicenseText_5args 3", LicenseUtils.getLicenseText(locale, collection, item, person), equalTo(templateResult));
locale = Locale.GERMAN; locale = Locale.GERMAN;
@@ -227,11 +227,11 @@ public class LicenseUtilsTest extends AbstractUnitTest
* Test of grantLicense method, of class LicenseUtils. * Test of grantLicense method, of class LicenseUtils.
*/ */
@Test @Test
public void testGrantLicense() throws Exception public void testGrantLicense() throws Exception
{ {
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
Item item = Item.create(context); Item item = Item.create(context);
String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); String defaultLicense = LicenseManager.getDefaultSubmissionLicense();
LicenseUtils.grantLicense(context, item, defaultLicense); LicenseUtils.grantLicense(context, item, defaultLicense);

View File

@@ -109,7 +109,7 @@ public class FeedbackServlet extends DSpaceServlet
// All data is there, send the email // All data is there, send the email
try try
{ {
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback")); Email email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback"));
email.addRecipient(ConfigurationManager email.addRecipient(ConfigurationManager
.getProperty("feedback.recipient")); .getProperty("feedback.recipient"));

View File

@@ -77,7 +77,7 @@ public class SuggestServlet extends DSpaceServlet
// Obtain information from request // Obtain information from request
String handle = request.getParameter("handle"); String handle = request.getParameter("handle");
// Lookup Item title & collection // Lookup Item title & collection
String title = null; String title = null;
String collName = null; String collName = null;
@@ -85,7 +85,7 @@ public class SuggestServlet extends DSpaceServlet
{ {
Item item = (Item) HandleManager.resolveToObject(context, handle); Item item = (Item) HandleManager.resolveToObject(context, handle);
if (item != null) if (item != null)
{ {
DCValue[] titleDC = item.getDC("title", null, Item.ANY); DCValue[] titleDC = item.getDC("title", null, Item.ANY);
if (titleDC != null && titleDC.length > 0) if (titleDC != null && titleDC.length > 0)
{ {
@@ -111,18 +111,18 @@ public class SuggestServlet extends DSpaceServlet
collName = ""; collName = "";
} }
request.setAttribute("suggest.title", title); request.setAttribute("suggest.title", title);
// User email from context // User email from context
EPerson currentUser = context.getCurrentUser(); EPerson currentUser = context.getCurrentUser();
String authEmail = null; String authEmail = null;
String userName = null; String userName = null;
if (currentUser != null) if (currentUser != null)
{ {
authEmail = currentUser.getEmail(); authEmail = currentUser.getEmail();
userName = currentUser.getFullName(); userName = currentUser.getFullName();
} }
if (request.getParameter("submit") != null) if (request.getParameter("submit") != null)
{ {
String recipAddr = request.getParameter("recip_email"); String recipAddr = request.getParameter("recip_email");
@@ -177,13 +177,13 @@ public class SuggestServlet extends DSpaceServlet
} }
String itemUri = HandleManager.getCanonicalForm(handle); String itemUri = HandleManager.getCanonicalForm(handle);
String itemUrl = HandleManager.resolveToURL(context,handle); String itemUrl = HandleManager.resolveToURL(context,handle);
String message = request.getParameter("message"); String message = request.getParameter("message");
String siteName = ConfigurationManager.getProperty("dspace.name"); String siteName = ConfigurationManager.getProperty("dspace.name");
// All data is there, send the email // All data is there, send the email
try 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.addRecipient(recipAddr); // recipient address
email.addArgument(recipName); // 1st arg - recipient name email.addArgument(recipName); // 1st arg - recipient name
email.addArgument(senderName); // 2nd arg - sender 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(itemUri); // 5th arg - item handle URI
email.addArgument(itemUrl); // 6th arg - item local URL email.addArgument(itemUrl); // 6th arg - item local URL
email.addArgument(collName); // 7th arg - collection name 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 // Set sender's address as 'reply-to' address if supplied
if ( senderAddr != null && ! "".equals(senderAddr)) if ( senderAddr != null && ! "".equals(senderAddr))
{ {
email.setReplyTo(senderAddr); email.setReplyTo(senderAddr);
} }
// Only actually send the email if feature is enabled // Only actually send the email if feature is enabled
if (ConfigurationManager.getBooleanProperty("webui.suggest.enable", false)) 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")); log.info(LogManager.getHeader(context, "show_suggest_form", "problem=false"));
request.setAttribute("authenticated.email", authEmail); request.setAttribute("authenticated.email", authEmail);
request.setAttribute("eperson.name", userName); 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 // Treat as a GET
doDSGet(context, request, response); doDSGet(context, request, response);
} }
} }

View File

@@ -20,18 +20,19 @@ import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; 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 * Servlet for editing the default license
* *
* @author Stuart Lewis * @author Stuart Lewis
*/ */
public class LicenseEditServlet extends DSpaceServlet public class LicenseEditServlet extends DSpaceServlet
{ {
/** /**
* Handle GET requests. This does nothing but forwards * 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, protected void doDSGet(Context c, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException, HttpServletResponse response) throws ServletException, IOException,
@@ -59,7 +60,7 @@ public class LicenseEditServlet extends DSpaceServlet
else if (!button.equals("submit_save")) else if (!button.equals("submit_save"))
{ {
// Get the existing text from the ConfigurationManager // 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 // Pass the existing license back to the JSP
request.setAttribute("license", license); request.setAttribute("license", license);
@@ -76,11 +77,11 @@ public class LicenseEditServlet extends DSpaceServlet
if (license.trim().equals("")) if (license.trim().equals(""))
{ {
// Get the existing text from the ConfigurationManager // 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 // Pass the existing license back to the JSP
request.setAttribute("license", license); request.setAttribute("license", license);
// Pass the 'empty' message back // Pass the 'empty' message back
request.setAttribute("empty", "true"); request.setAttribute("empty", "true");
@@ -90,14 +91,14 @@ public class LicenseEditServlet extends DSpaceServlet
else else
{ {
// Write the string out to file // 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 // Pass the existing license back to the JSP
request.setAttribute("license", license); request.setAttribute("license", license);
// Pass the 'edited' message back // Pass the 'edited' message back
request.setAttribute("edited", "true"); request.setAttribute("edited", "true");
// Show edit page // Show edit page
JSPManager.showJSP(request, response, "/dspace-admin/license-edit.jsp"); JSPManager.showJSP(request, response, "/dspace-admin/license-edit.jsp");
} }

View File

@@ -20,10 +20,11 @@ import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.NewsManager;
/** /**
* Servlet for editing the front page news * Servlet for editing the front page news
* *
* @author gcarpent * @author gcarpent
*/ */
public class NewsEditServlet extends DSpaceServlet public class NewsEditServlet extends DSpaceServlet
@@ -47,11 +48,11 @@ public class NewsEditServlet extends DSpaceServlet
//Are we editing the top news or the sidebar news? //Are we editing the top news or the sidebar news?
String position = request.getParameter("position"); String position = request.getParameter("position");
if (button.equals("submit_edit")) if (button.equals("submit_edit"))
{ {
//get the existing text from the file //get the existing text from the file
news = ConfigurationManager.readNewsFile(position); news = NewsManager.readNewsFile(position);
//pass the position back to the JSP //pass the position back to the JSP
request.setAttribute("position", position); request.setAttribute("position", position);
@@ -69,7 +70,7 @@ public class NewsEditServlet extends DSpaceServlet
news = (String) request.getParameter("news"); news = (String) request.getParameter("news");
//write the string out to file //write the string out to file
ConfigurationManager.writeNewsFile(position, news); NewsManager.writeNewsFile(position, news);
JSPManager JSPManager
.showJSP(request, response, "/dspace-admin/news-main.jsp"); .showJSP(request, response, "/dspace-admin/news-main.jsp");

View File

@@ -40,7 +40,7 @@ import org.dspace.eperson.EPerson;
/** /**
* Miscellaneous UI utility methods * Miscellaneous UI utility methods
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$ * @version $Revision$
*/ */
@@ -51,7 +51,7 @@ public class UIUtil extends Util
/** log4j category */ /** log4j category */
public static final Logger log = Logger.getLogger(UIUtil.class); public static final Logger log = Logger.getLogger(UIUtil.class);
/** /**
* Pattern used to get file.ext from filename (which can be a path) * 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 * 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 * has authenticated with the system, the current user of the context is set
* appropriately. * appropriately.
* *
* @param request * @param request
* the HTTP request * the HTTP request
* *
* @return a context object * @return a context object
*/ */
public static Context obtainContext(HttpServletRequest request) public static Context obtainContext(HttpServletRequest request)
throws SQLException throws SQLException
{ {
//Set encoding to UTF-8, if not set yet //Set encoding to UTF-8, if not set yet
//This avoids problems of using the HttpServletRequest //This avoids problems of using the HttpServletRequest
//in the getSpecialGroups() for an AuthenticationMethod, //in the getSpecialGroups() for an AuthenticationMethod,
//which causes the HttpServletRequest to default to //which causes the HttpServletRequest to default to
//non-UTF-8 encoding. //non-UTF-8 encoding.
try try
{ {
@@ -88,9 +88,9 @@ public class UIUtil extends Util
{ {
log.error("Unable to set encoding to UTF-8.", e); log.error("Unable to set encoding to UTF-8.", e);
} }
Context c = (Context) request.getAttribute("dspace.context"); Context c = (Context) request.getAttribute("dspace.context");
if (c == null) if (c == null)
{ {
@@ -149,7 +149,7 @@ public class UIUtil extends Util
// Store the context in the request // Store the context in the request
request.setAttribute("dspace.context", c); request.setAttribute("dspace.context", c);
} }
// Set the locale to be used // Set the locale to be used
Locale sessionLocale = getSessionLocale(request); Locale sessionLocale = getSessionLocale(request);
Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale); 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 * Get the current community location, that is, where the user "is". This
* returns <code>null</code> if there is no location, i.e. "all of DSpace" * returns <code>null</code> if there is no location, i.e. "all of DSpace"
* is the location. * is the location.
* *
* @param request * @param request
* current HTTP request * current HTTP request
* *
* @return the current community location, or null * @return the current community location, or null
*/ */
public static Community getCommunityLocation(HttpServletRequest request) 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 * 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 * returns null if there is no collection location, i.e. the location is
* "all of DSpace" or a community. * "all of DSpace" or a community.
* *
* @param request * @param request
* current HTTP request * current HTTP request
* *
* @return the current collection location, or null * @return the current collection location, or null
*/ */
public static Collection getCollectionLocation(HttpServletRequest request) 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 * later use. This is necessary because forwarding a request removes this
* information. The attribute is only written if it hasn't been before; thus * information. The attribute is only written if it hasn't been before; thus
* it can be called after a forward safely. * it can be called after a forward safely.
* *
* @param request * @param request
* the HTTP request * the HTTP request
*/ */
@@ -216,10 +216,10 @@ public class UIUtil extends Util
/** /**
* Get the original request URL. * Get the original request URL.
* *
* @param request * @param request
* the HTTP request * the HTTP request
* *
* @return the original request URL * @return the original request URL
*/ */
public static String getOriginalURL(HttpServletRequest request) public static String getOriginalURL(HttpServletRequest request)
@@ -232,7 +232,7 @@ public class UIUtil extends Util
/** /**
* Write a human-readable version of a DCDate. * Write a human-readable version of a DCDate.
* *
* @param d * @param d
* the date * the date
* @param time * @param time
@@ -240,8 +240,8 @@ public class UIUtil extends Util
* @param localTime * @param localTime
* if true, adjust for local timezone, otherwise GMT * if true, adjust for local timezone, otherwise GMT
* @param request * @param request
* the servlet request * the servlet request
* *
* @return the date in a human-readable form. * @return the date in a human-readable form.
*/ */
public static String displayDate(DCDate d, boolean time, boolean localTime, HttpServletRequest request) 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 * Return a string for logging, containing useful information about the
* current request - the URL, the method and parameters. * current request - the URL, the method and parameters.
* *
* @param request * @param request
* the request object. * the request object.
* @return a multi-line string containing information about the request. * @return a multi-line string containing information about the request.
@@ -288,15 +288,15 @@ public class UIUtil extends Util
return report.toString(); return report.toString();
} }
/** /**
* Get the Locale for a session according to the user's language selection or language preferences. * Get the Locale for a session according to the user's language selection or language preferences.
* Order of selection * Order of selection
* - language selected via UI * - language selected via UI
* - language as set by application * - language as set by application
* - language browser default * - language browser default
* *
* @param request * @param request
* the request Object * the request Object
* @return supportedLocale * @return supportedLocale
@@ -314,8 +314,8 @@ public class UIUtil extends Util
/* get session locale according to user selection */ /* get session locale according to user selection */
sessionLocale = new Locale(paramLocale); sessionLocale = new Locale(paramLocale);
} }
if (sessionLocale == null) if (sessionLocale == null)
{ {
/* get session locale set by application */ /* get session locale set by application */
@@ -331,17 +331,17 @@ public class UIUtil extends Util
{ {
sessionLocale = request.getLocale(); sessionLocale = request.getLocale();
} }
if (sessionLocale == null) if (sessionLocale == null)
{ {
sessionLocale = I18nUtil.DEFAULTLOCALE; sessionLocale = I18nUtil.DEFAULTLOCALE;
} }
supportedLocale = I18nUtil.getSupportedLocale(sessionLocale); supportedLocale = I18nUtil.getSupportedLocale(sessionLocale);
return supportedLocale;
}
return supportedLocale;
}
/** /**
* Send an alert to the designated "alert recipient" - that is, when a * 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 * 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 * 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 * logged. This is because this method will usually be invoked as part of an
* error handling routine anyway. * error handling routine anyway.
* *
* @param request * @param request
* the HTTP request leading to the error * the HTTP request leading to the error
* @param exception * @param exception
@@ -374,7 +374,7 @@ public class UIUtil extends Util
if (recipient != null) 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.addRecipient(recipient);
email.addArgument(ConfigurationManager email.addArgument(ConfigurationManager
.getProperty("dspace.url")); .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."); log.warn("No context, the database might be down or the connection pool exhausted.");
} }
if (user != null) if (user != null)
{ {
email.addArgument(user.getFullName() + " (" + user.getEmail() + ")"); email.addArgument(user.getFullName() + " (" + user.getEmail() + ")");
@@ -425,10 +425,10 @@ public class UIUtil extends Util
log.warn("Unable to send email alert", e); log.warn("Unable to send email alert", e);
} }
} }
/** /**
* Evaluate filename and client and encode appropriate disposition * Evaluate filename and client and encode appropriate disposition
* *
* @param filename * @param filename
* @param request * @param request
* @param response * @param response
@@ -437,31 +437,31 @@ public class UIUtil extends Util
public static void setBitstreamDisposition(String filename, HttpServletRequest request, public static void setBitstreamDisposition(String filename, HttpServletRequest request,
HttpServletResponse response) HttpServletResponse response)
{ {
String name = filename; String name = filename;
Matcher m = p.matcher(name); Matcher m = p.matcher(name);
if (m.find() && !m.group().equals("")) if (m.find() && !m.group().equals(""))
{ {
name = m.group(); name = m.group();
} }
try try
{ {
String agent = request.getHeader("USER-AGENT"); 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"); 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"); name = MimeUtility.encodeText(name, "UTF8", "B");
} }
} }
catch (UnsupportedEncodingException e) catch (UnsupportedEncodingException e)
{ {
log.error(e.getMessage(),e); log.error(e.getMessage(),e);
} }

View File

@@ -20,6 +20,8 @@ import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Community; import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LicenseManager;
import org.dspace.core.NewsManager;
import org.jdom.Element; import org.jdom.Element;
@@ -61,7 +63,7 @@ class DAVSite extends DAVResource
/** /**
* Instantiates a new DAV site. * Instantiates a new DAV site.
* *
* @param context the context * @param context the context
* @param request the request * @param request the request
* @param response the response * @param response the response
@@ -76,14 +78,14 @@ class DAVSite extends DAVResource
/** /**
* Match resource URI. * Match resource URI.
* *
* @param context the context * @param context the context
* @param request the request * @param request the request
* @param response the response * @param response the response
* @param pathElt the path elt * @param pathElt the path elt
* *
* @return the DAV resource * @return the DAV resource
* *
* @throws DAVStatusException the DAV status exception * @throws DAVStatusException the DAV status exception
* @throws SQLException the SQL exception * @throws SQLException the SQL exception
*/ */
@@ -143,15 +145,15 @@ class DAVSite extends DAVResource
} }
else if (elementsEqualIsh(property, news_topProperty)) else if (elementsEqualIsh(property, news_topProperty))
{ {
value = ConfigurationManager.readNewsFile("news-top.html"); value = NewsManager.readNewsFile("news-top.html");
} }
else if (elementsEqualIsh(property, news_sideProperty)) else if (elementsEqualIsh(property, news_sideProperty))
{ {
value = ConfigurationManager.readNewsFile("news-side.html"); value = NewsManager.readNewsFile("news-side.html");
} }
else if (elementsEqualIsh(property, default_licenseProperty)) else if (elementsEqualIsh(property, default_licenseProperty))
{ {
value = ConfigurationManager.getDefaultSubmissionLicense(); value = LicenseManager.getDefaultSubmissionLicense();
} }
else else
{ {
@@ -186,7 +188,7 @@ class DAVSite extends DAVResource
throw new DAVStatusException(HttpServletResponse.SC_FORBIDDEN, throw new DAVStatusException(HttpServletResponse.SC_FORBIDDEN,
"Not authorized to modify this property."); "Not authorized to modify this property.");
} }
ConfigurationManager.writeNewsFile("news-top.html", newValue); NewsManager.writeNewsFile("news-top.html", newValue);
} }
else if (elementsEqualIsh(prop, news_sideProperty)) else if (elementsEqualIsh(prop, news_sideProperty))
{ {
@@ -195,7 +197,7 @@ class DAVSite extends DAVResource
throw new DAVStatusException(HttpServletResponse.SC_FORBIDDEN, throw new DAVStatusException(HttpServletResponse.SC_FORBIDDEN,
"Not authorized to modify this property."); "Not authorized to modify this property.");
} }
ConfigurationManager.writeNewsFile("news-side.html", newValue); NewsManager.writeNewsFile("news-side.html", newValue);
} }
else if (elementsEqualIsh(prop, displaynameProperty)) else if (elementsEqualIsh(prop, displaynameProperty))
{ {

View File

@@ -128,7 +128,7 @@ public class SendFeedbackAction extends AbstractAction
} }
// All data is there, send the email // 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 email.addRecipient(ConfigurationManager
.getProperty("feedback.recipient")); .getProperty("feedback.recipient"));