javadoc (doclint) and whitespace fixes

includes whitespace fixes as per Coding Conventions
This commit is contained in:
Ivan Masár
2016-10-31 14:34:27 +01:00
parent db1641cfa9
commit 269af71afb
384 changed files with 24482 additions and 20843 deletions

View File

@@ -71,11 +71,11 @@ public interface ExtractingParams {
/**
* Restrict the extracted parts of a document to be indexed
* by passing in an XPath expression. All content that satisfies the XPath expr.
* will be passed to the {@link SolrContentHandler}.
* by passing in an XPath expression. All content that satisfies the XPath expr.
* will be passed to the {@link org.apache.solr.handler.extraction.SolrContentHandler}.
* <p>
* See Tika's docs for what the extracted document looks like.
* <p>
*
* @see #CAPTURE_ELEMENTS
*/
public static final String XPATH_EXPRESSION = "xpath";
@@ -105,7 +105,7 @@ public interface ExtractingParams {
* Capture the specified fields (and everything included below it that isn't capture by some other capture field) separately from the default. This is different
* then the case of passing in an XPath expression.
* <p>
* The Capture field is based on the localName returned to the {@link SolrContentHandler}
* The Capture field is based on the localName returned to the {@link org.apache.solr.handler.extraction.SolrContentHandler}
* by Tika, not to be confused by the mapped field. The field name can then
* be mapped into the index schema.
* <p>

View File

@@ -48,7 +48,7 @@ public class CommunityFiliator
/**
*
* @param argv arguments
* @param argv the command line arguments given
* @throws Exception if error
*/
public static void main(String[] argv) throws Exception

View File

@@ -47,8 +47,8 @@ import org.dspace.eperson.service.GroupService;
*/
public final class CreateAdministrator
{
/** DSpace Context object */
private final Context context;
/** DSpace Context object */
private final Context context;
protected EPersonService ePersonService;
protected GroupService groupService;
@@ -57,37 +57,36 @@ public final class CreateAdministrator
* For invoking via the command line. If called with no command line arguments,
* it will negotiate with the user for the administrator details
*
* @param argv
* command-line arguments
* @param argv the command line arguments given
* @throws Exception if error
*/
public static void main(String[] argv)
throws Exception
throws Exception
{
CommandLineParser parser = new PosixParser();
Options options = new Options();
CreateAdministrator ca = new CreateAdministrator();
options.addOption("e", "email", true, "administrator email address");
options.addOption("f", "first", true, "administrator first name");
options.addOption("l", "last", true, "administrator last name");
options.addOption("c", "language", true, "administrator language");
options.addOption("p", "password", true, "administrator password");
CommandLine line = parser.parse(options, argv);
if (line.hasOption("e") && line.hasOption("f") && line.hasOption("l") &&
line.hasOption("c") && line.hasOption("p"))
{
ca.createAdministrator(line.getOptionValue("e"),
line.getOptionValue("f"), line.getOptionValue("l"),
line.getOptionValue("c"), line.getOptionValue("p"));
}
else
{
ca.negotiateAdministratorDetails();
}
CommandLineParser parser = new PosixParser();
Options options = new Options();
CreateAdministrator ca = new CreateAdministrator();
options.addOption("e", "email", true, "administrator email address");
options.addOption("f", "first", true, "administrator first name");
options.addOption("l", "last", true, "administrator last name");
options.addOption("c", "language", true, "administrator language");
options.addOption("p", "password", true, "administrator password");
CommandLine line = parser.parse(options, argv);
if (line.hasOption("e") && line.hasOption("f") && line.hasOption("l") &&
line.hasOption("c") && line.hasOption("p"))
{
ca.createAdministrator(line.getOptionValue("e"),
line.getOptionValue("f"), line.getOptionValue("l"),
line.getOptionValue("c"), line.getOptionValue("p"));
}
else
{
ca.negotiateAdministratorDetails();
}
}
/**
@@ -96,9 +95,9 @@ public final class CreateAdministrator
* @throws Exception if error
*/
protected CreateAdministrator()
throws Exception
throws Exception
{
context = new Context();
context = new Context();
groupService = EPersonServiceFactory.getInstance().getGroupService();
ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
}
@@ -110,27 +109,27 @@ public final class CreateAdministrator
* @throws Exception if error
*/
protected void negotiateAdministratorDetails()
throws Exception
throws Exception
{
Console console = System.console();
System.out.println("Creating an initial administrator account");
boolean dataOK = false;
String email = null;
String firstName = null;
String lastName = null;
System.out.println("Creating an initial administrator account");
boolean dataOK = false;
String email = null;
String firstName = null;
String lastName = null;
char[] password1 = null;
char[] password2 = null;
String language = I18nUtil.DEFAULTLOCALE.getLanguage();
while (!dataOK)
{
System.out.print("E-mail address: ");
System.out.flush();
email = console.readLine();
String language = I18nUtil.DEFAULTLOCALE.getLanguage();
while (!dataOK)
{
System.out.print("E-mail address: ");
System.out.flush();
email = console.readLine();
if (!StringUtils.isBlank(email))
{
email = email.trim();
@@ -140,34 +139,34 @@ public final class CreateAdministrator
System.out.println("Please provide an email address.");
continue;
}
System.out.print("First name: ");
System.out.flush();
firstName = console.readLine();
System.out.print("First name: ");
System.out.flush();
firstName = console.readLine();
if (firstName != null)
{
firstName = firstName.trim();
}
System.out.print("Last name: ");
System.out.flush();
lastName = console.readLine();
System.out.print("Last name: ");
System.out.flush();
lastName = console.readLine();
if (lastName != null)
{
lastName = lastName.trim();
}
if (ConfigurationManager.getProperty("webui.supported.locales") != null)
{
System.out.println("Select one of the following languages: " + ConfigurationManager.getProperty("webui.supported.locales"));
System.out.print("Language: ");
System.out.flush();
language = console.readLine();
language = console.readLine();
if (language != null)
{
@@ -176,25 +175,25 @@ public final class CreateAdministrator
}
}
System.out.println("Password will not display on screen.");
System.out.print("Password: ");
System.out.flush();
System.out.println("Password will not display on screen.");
System.out.print("Password: ");
System.out.flush();
password1 = console.readPassword();
System.out.print("Again to confirm: ");
System.out.flush();
password2 = console.readPassword();
password1 = console.readPassword();
System.out.print("Again to confirm: ");
System.out.flush();
password2 = console.readPassword();
//TODO real password validation
if (password1.length > 1 && Arrays.equals(password1, password2))
{
// password OK
System.out.print("Is the above data correct? (y or n): ");
System.out.flush();
String s = console.readLine();
{
// password OK
System.out.print("Is the above data correct? (y or n): ");
System.out.flush();
String s = console.readLine();
if (s != null)
{
@@ -204,15 +203,15 @@ public final class CreateAdministrator
dataOK = true;
}
}
}
else
{
System.out.println("Passwords don't match");
}
}
// if we make it to here, we are ready to create an administrator
createAdministrator(email, firstName, lastName, language, String.valueOf(password1));
}
else
{
System.out.println("Passwords don't match");
}
}
// if we make it to here, we are ready to create an administrator
createAdministrator(email, firstName, lastName, language, String.valueOf(password1));
//Cleaning arrays that held password
Arrays.fill(password1, ' ');
@@ -223,31 +222,31 @@ public final class CreateAdministrator
* Create the administrator with the given details. If the user
* already exists then they are simply upped to administrator status
*
* @param email the email for the user
* @param first user's first name
* @param last user's last name
* @param email the email for the user
* @param first user's first name
* @param last user's last name
* @param language preferred language
* @param pw desired password
* @param pw desired password
*
* @throws Exception if error
*/
protected void createAdministrator(String email, String first, String last,
String language, String pw)
throws Exception
String language, String pw)
throws Exception
{
// Of course we aren't an administrator yet so we need to
// circumvent authorisation
context.turnOffAuthorisationSystem();
// Find administrator group
Group admins = groupService.findByName(context, Group.ADMIN);
if (admins == null)
{
throw new IllegalStateException("Error, no admin group (group 1) found");
}
// Create the administrator e-person
// Of course we aren't an administrator yet so we need to
// circumvent authorisation
context.turnOffAuthorisationSystem();
// Find administrator group
Group admins = groupService.findByName(context, Group.ADMIN);
if (admins == null)
{
throw new IllegalStateException("Error, no admin group (group 1) found");
}
// Create the administrator e-person
EPerson eperson = ePersonService.findByEmail(context,email);
// check if the email belongs to a registered user,
@@ -260,18 +259,18 @@ public final class CreateAdministrator
eperson.setRequireCertificate(false);
eperson.setSelfRegistered(false);
}
eperson.setLastName(context, last);
eperson.setFirstName(context, first);
eperson.setLanguage(context, language);
eperson.setLastName(context, last);
eperson.setFirstName(context, first);
eperson.setLanguage(context, language);
ePersonService.setPassword(eperson, pw);
ePersonService.update(context, eperson);
groupService.addMember(context, admins, eperson);
groupService.addMember(context, admins, eperson);
groupService.update(context, admins);
context.complete();
System.out.println("Administrator account created");
context.complete();
System.out.println("Administrator account created");
}
}

View File

@@ -71,7 +71,8 @@ public class MetadataImporter
/**
* main method for reading user input from the command line
* @param args arguments
*
* @param args the command line arguments given
* @throws ParseException if parse error
* @throws SQLException if database error
* @throws IOException if IO error
@@ -83,9 +84,9 @@ public class MetadataImporter
* @throws RegistryImportException if import fails
**/
public static void main(String[] args)
throws ParseException, SQLException, IOException, TransformerException,
ParserConfigurationException, AuthorizeException, SAXException,
NonUniqueMetadataException, RegistryImportException
throws ParseException, SQLException, IOException, TransformerException,
ParserConfigurationException, AuthorizeException, SAXException,
NonUniqueMetadataException, RegistryImportException
{
boolean forceUpdate = false;
@@ -114,7 +115,7 @@ public class MetadataImporter
/**
* Load the data from the specified file path into the database
*
* @param file the file path containing the source data
* @param file the file path containing the source data
* @param forceUpdate whether to force update
* @throws SQLException if database error
* @throws IOException if IO error
@@ -126,8 +127,8 @@ public class MetadataImporter
* @throws RegistryImportException if import fails
*/
public static void loadRegistry(String file, boolean forceUpdate)
throws SQLException, IOException, TransformerException, ParserConfigurationException,
AuthorizeException, SAXException, NonUniqueMetadataException, RegistryImportException
throws SQLException, IOException, TransformerException, ParserConfigurationException,
AuthorizeException, SAXException, NonUniqueMetadataException, RegistryImportException
{
Context context = null;
@@ -301,8 +302,8 @@ public class MetadataImporter
public static void usage()
{
String usage = "Use this class with the following option:\n" +
" -f <xml source file> : specify which xml source file " +
"contains the DC fields to import.\n";
" -f <xml source file> : specify which xml source file " +
"contains the DC fields to import.\n";
System.out.println(usage);
}
}

View File

@@ -54,8 +54,7 @@ public class RegistryLoader
/**
* For invoking via the command line
*
* @param argv
* command-line arguments
* @param argv the command line arguments given
* @throws Exception if error
*/
public static void main(String[] argv) throws Exception

View File

@@ -92,47 +92,48 @@ public class StructBuilder
*
* The output file will contain exactly the same as the source xml document, but
* with the handle for each imported item added as an attribute.
* @param argv commandline arguments
*
* @param argv the command line arguments given
* @throws Exception if an error occurs
*/
public static void main(String[] argv)
throws Exception
throws Exception
{
CommandLineParser parser = new PosixParser();
Options options = new Options();
Options options = new Options();
options.addOption( "f", "file", true, "file");
options.addOption( "e", "eperson", true, "eperson");
options.addOption("o", "output", true, "output");
CommandLine line = parser.parse( options, argv );
String file = null;
String eperson = null;
String output = null;
if (line.hasOption('f'))
{
file = line.getOptionValue('f');
}
if (line.hasOption('e'))
{
eperson = line.getOptionValue('e');
}
if (line.hasOption('o'))
{
output = line.getOptionValue('o');
}
if (output == null || eperson == null || file == null)
{
usage();
System.exit(0);
}
options.addOption( "f", "file", true, "file");
options.addOption( "e", "eperson", true, "eperson");
options.addOption("o", "output", true, "output");
CommandLine line = parser.parse( options, argv );
String file = null;
String eperson = null;
String output = null;
if (line.hasOption('f'))
{
file = line.getOptionValue('f');
}
if (line.hasOption('e'))
{
eperson = line.getOptionValue('e');
}
if (line.hasOption('o'))
{
output = line.getOptionValue('o');
}
if (output == null || eperson == null || file == null)
{
usage();
System.exit(0);
}
// create a context
Context context = new Context();
@@ -204,12 +205,12 @@ public class StructBuilder
* Validate the XML document. This method does not return, but if validation
* fails it generates an error and ceases execution
*
* @param document the XML document object
* @param document the XML document object
* @throws TransformerException if transformer error
*
*/
private static void validate(org.w3c.dom.Document document)
throws TransformerException
throws TransformerException
{
StringBuffer err = new StringBuffer();
boolean trip = false;
@@ -245,13 +246,13 @@ public class StructBuilder
*
* @param communities the NodeList of communities to validate
* @param level the level in the XML document that we are at, for the purposes
* of error reporting
* of error reporting
*
* @return the errors that need to be generated by the calling method, or null if
* no errors.
* no errors.
*/
private static String validateCommunities(NodeList communities, int level)
throws TransformerException
throws TransformerException
{
StringBuffer err = new StringBuffer();
boolean trip = false;
@@ -260,32 +261,32 @@ public class StructBuilder
for (int i = 0; i < communities.getLength(); i++)
{
Node n = communities.item(i);
NodeList name = XPathAPI.selectNodeList(n, "name");
if (name.getLength() != 1)
{
String pos = Integer.toString(i + 1);
err.append("-The level " + level + " community in position " + pos);
err.append(" does not contain exactly one name field\n");
trip = true;
}
// validate sub communities
NodeList subCommunities = XPathAPI.selectNodeList(n, "community");
String comErrs = validateCommunities(subCommunities, level + 1);
if (comErrs != null)
{
err.append(comErrs);
trip = true;
}
// validate collections
NodeList collections = XPathAPI.selectNodeList(n, "collection");
String colErrs = validateCollections(collections, level + 1);
if (colErrs != null)
{
err.append(colErrs);
trip = true;
}
NodeList name = XPathAPI.selectNodeList(n, "name");
if (name.getLength() != 1)
{
String pos = Integer.toString(i + 1);
err.append("-The level " + level + " community in position " + pos);
err.append(" does not contain exactly one name field\n");
trip = true;
}
// validate sub communities
NodeList subCommunities = XPathAPI.selectNodeList(n, "community");
String comErrs = validateCommunities(subCommunities, level + 1);
if (comErrs != null)
{
err.append(comErrs);
trip = true;
}
// validate collections
NodeList collections = XPathAPI.selectNodeList(n, "collection");
String colErrs = validateCollections(collections, level + 1);
if (colErrs != null)
{
err.append(colErrs);
trip = true;
}
}
if (trip)
@@ -306,7 +307,7 @@ public class StructBuilder
* @return the errors to be generated by the calling method, or null if none
*/
private static String validateCollections(NodeList collections, int level)
throws TransformerException
throws TransformerException
{
StringBuffer err = new StringBuffer();
boolean trip = false;
@@ -315,14 +316,14 @@ public class StructBuilder
for (int i = 0; i < collections.getLength(); i++)
{
Node n = collections.item(i);
NodeList name = XPathAPI.selectNodeList(n, "name");
if (name.getLength() != 1)
{
String pos = Integer.toString(i + 1);
err.append("-The level " + level + " collection in position " + pos);
err.append(" does not contain exactly one name field\n");
trip = true;
}
NodeList name = XPathAPI.selectNodeList(n, "name");
if (name.getLength() != 1)
{
String pos = Integer.toString(i + 1);
err.append("-The level " + level + " collection in position " + pos);
err.append(" does not contain exactly one name field\n");
trip = true;
}
}
if (trip)
@@ -342,7 +343,7 @@ public class StructBuilder
* @return the DOM representation of the XML file
*/
private static org.w3c.dom.Document loadXML(String filename)
throws IOException, ParserConfigurationException, SAXException
throws IOException, ParserConfigurationException, SAXException
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
@@ -385,10 +386,10 @@ public class StructBuilder
* @param parent the parent community of the nodelist of communities to create
*
* @return an element array containing additional information regarding the
* created communities (e.g. the handles they have been assigned)
* created communities (e.g. the handles they have been assigned)
*/
private static Element[] handleCommunities(Context context, NodeList communities, Community parent)
throws TransformerException, SQLException, Exception
throws TransformerException, SQLException, Exception
{
Element[] elements = new Element[communities.getLength()];
@@ -506,10 +507,10 @@ public class StructBuilder
* @param parent the parent community to whom the collections belong
*
* @return an Element array containing additional information about the
* created collections (e.g. the handle)
* created collections (e.g. the handle)
*/
private static Element[] handleCollections(Context context, NodeList collections, Community parent)
throws TransformerException, SQLException, AuthorizeException, IOException, Exception
throws TransformerException, SQLException, AuthorizeException, IOException, Exception
{
Element[] elements = new Element[collections.getLength()];

View File

@@ -53,25 +53,25 @@ public final class ChecksumChecker
/**
* Command line access to the checksum package.
*
* @param args
* <dl>
* <dt>-h</dt>
* <dd>Print help on command line options</dd>
* <dt>-l</dt>
* <dd>loop through bitstreams once</dd>
* <dt>-L</dt>
* <dd>loop continuously through bitstreams</dd>
* <dt>-d</dt>
* <dd>specify duration of process run</dd>
* <dt>-b</dt>
* <dd>specify bitstream IDs</dd>
* <dt>-a [handle_id]</dt>
* <dd>check anything by handle</dd>
* <dt>-e</dt>
* <dd>Report only errors in the logs</dd>
* <dt>-p</dt>
* <dd>Don't prune results before running checker</dd>
* </dl>
* <dl>
* <dt>-h</dt>
* <dd>Print help on command line options</dd>
* <dt>-l</dt>
* <dd>loop through bitstreams once</dd>
* <dt>-L</dt>
* <dd>loop continuously through bitstreams</dd>
* <dt>-d</dt>
* <dd>specify duration of process run</dd>
* <dt>-b</dt>
* <dd>specify bitstream IDs</dd>
* <dt>-a [handle_id]</dt>
* <dd>check anything by handle</dd>
* <dt>-e</dt>
* <dd>Report only errors in the logs</dd>
* <dt>-p</dt>
* <dd>Don't prune results before running checker</dd>
* </dl>
* @param args the command line arguments given
* @throws SQLException if error
*/
public static void main(String[] args) throws SQLException {
@@ -84,7 +84,7 @@ public final class ChecksumChecker
options.addOption("l", "looping", false, "Loop once through bitstreams");
options.addOption("L", "continuous", false,
"Loop continuously through bitstreams");
"Loop continuously through bitstreams");
options.addOption("h", "help", false, "Help");
options.addOption("d", "duration", true, "Checking duration");
options.addOption("c", "count", true, "Check count");
@@ -92,19 +92,18 @@ public final class ChecksumChecker
options.addOption("v", "verbose", false, "Report all processing");
OptionBuilder.withArgName("bitstream-ids").hasArgs().withDescription(
"Space separated list of bitstream ids");
"Space separated list of bitstream ids");
Option useBitstreamIds = OptionBuilder.create('b');
options.addOption(useBitstreamIds);
options.addOption("p", "prune", false, "Prune configuration file");
options
.addOption(OptionBuilder
.withArgName("prune")
.hasOptionalArgs(1)
.withDescription(
"Prune old results (optionally using specified properties file for configuration)")
.create('p'));
options.addOption(OptionBuilder
.withArgName("prune")
.hasOptionalArgs(1)
.withDescription(
"Prune old results (optionally using specified properties file for configuration)")
.create('p'));
try
{
@@ -233,7 +232,7 @@ public final class ChecksumChecker
context.complete();
context = null;
} finally {
if(context != null){
if (context != null) {
context.abort();
}
}
@@ -249,19 +248,15 @@ public final class ChecksumChecker
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("Checksum Checker\n", options);
System.out
.println("\nSpecify a duration for checker process, using s(seconds),"
+ "m(minutes), or h(hours): ChecksumChecker -d 30s"
+ " OR ChecksumChecker -d 30m"
+ " OR ChecksumChecker -d 2h");
System.out
.println("\nSpecify bitstream IDs: ChecksumChecker -b 13 15 17 20");
System.out.println("\nSpecify a duration for checker process, using s(seconds),"
+ "m(minutes), or h(hours): ChecksumChecker -d 30s"
+ " OR ChecksumChecker -d 30m"
+ " OR ChecksumChecker -d 2h");
System.out.println("\nSpecify bitstream IDs: ChecksumChecker -b 13 15 17 20");
System.out.println("\nLoop once through all bitstreams: "
+ "ChecksumChecker -l");
System.out
.println("\nLoop continuously through all bitstreams: ChecksumChecker -L");
System.out
.println("\nCheck a defined number of bitstreams: ChecksumChecker -c 10");
+ "ChecksumChecker -l");
System.out.println("\nLoop continuously through all bitstreams: ChecksumChecker -L");
System.out.println("\nCheck a defined number of bitstreams: ChecksumChecker -c 10");
System.out.println("\nReport all processing (verbose)(default reports only errors): ChecksumChecker -v");
System.out.println("\nDefault (no arguments) is equivalent to '-c 1'");
System.exit(0);

View File

@@ -67,12 +67,18 @@ public class Harvest
options.addOption("P", "purge", false, "purge all harvestable collections");
options.addOption("e", "eperson", true, "eperson");
options.addOption("c", "collection", true, "harvesting collection (handle or id)");
options.addOption("t", "type", true, "type of harvesting (0 for none)");
options.addOption("a", "address", true, "address of the OAI-PMH server");
options.addOption("i", "oai_set_id", true, "id of the PMH set representing the harvested collection");
options.addOption("m", "metadata_format", true, "the name of the desired metadata format for harvesting, resolved to namespace and crosswalk in dspace.cfg");
options.addOption("e", "eperson", true,
"eperson");
options.addOption("c", "collection", true,
"harvesting collection (handle or id)");
options.addOption("t", "type", true,
"type of harvesting (0 for none)");
options.addOption("a", "address", true,
"address of the OAI-PMH server");
options.addOption("i", "oai_set_id", true,
"id of the PMH set representing the harvested collection");
options.addOption("m", "metadata_format", true,
"the name of the desired metadata format for harvesting, resolved to namespace and crosswalk in dspace.cfg");
options.addOption("h", "help", false, "help");
@@ -90,22 +96,14 @@ public class Harvest
{
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("Harvest\n", options);
System.out
.println("\nPING OAI server: Harvest -g -s oai_source -i oai_set_id");
System.out
.println("RUNONCE harvest with arbitrary options: Harvest -o -e eperson -c collection -t harvest_type -a oai_source -i oai_set_id -m metadata_format");
System.out
.println("SETUP a collection for harvesting: Harvest -s -c collection -t harvest_type -a oai_source -i oai_set_id -m metadata_format");
System.out
.println("RUN harvest once: Harvest -r -e eperson -c collection");
System.out
.println("START harvest scheduler: Harvest -S");
System.out
.println("RESET all harvest status: Harvest -R");
System.out
.println("PURGE a collection of items and settings: Harvest -p -e eperson -c collection");
System.out
.println("PURGE all harvestable collections: Harvest -P -e eperson");
System.out.println("\nPING OAI server: Harvest -g -s oai_source -i oai_set_id");
System.out.println("RUNONCE harvest with arbitrary options: Harvest -o -e eperson -c collection -t harvest_type -a oai_source -i oai_set_id -m metadata_format");
System.out.println("SETUP a collection for harvesting: Harvest -s -c collection -t harvest_type -a oai_source -i oai_set_id -m metadata_format");
System.out.println("RUN harvest once: Harvest -r -e eperson -c collection");
System.out.println("START harvest scheduler: Harvest -S");
System.out.println("RESET all harvest status: Harvest -R");
System.out.println("PURGE a collection of items and settings: Harvest -p -e eperson -c collection");
System.out.println("PURGE all harvestable collections: Harvest -P -e eperson");
@@ -147,7 +145,7 @@ public class Harvest
if (line.hasOption('t')) {
harvestType = Integer.parseInt(line.getOptionValue('t'));
} else {
harvestType = 0;
harvestType = 0;
}
if (line.hasOption('a')) {
oaiSource = line.getOptionValue('a');
@@ -188,31 +186,31 @@ public class Harvest
// start the harvest loop
else if ("start".equals(command))
{
startHarvester();
startHarvester();
}
// reset harvesting status
else if ("reset".equals(command))
{
resetHarvesting();
resetHarvesting();
}
// purge all collections that are set up for harvesting (obviously for testing purposes only)
else if ("purgeAll".equals(command))
{
if (eperson == null)
if (eperson == null)
{
System.out
.println("Error - an eperson must be provided");
System.out.println(" (run with -h flag for details)");
System.exit(1);
}
List<HarvestedCollection> harvestedCollections = harvestedCollectionService.findAll(context);
for (HarvestedCollection harvestedCollection : harvestedCollections)
{
List<HarvestedCollection> harvestedCollections = harvestedCollectionService.findAll(context);
for (HarvestedCollection harvestedCollection : harvestedCollections)
{
System.out.println("Purging the following collections (deleting items and resetting harvest status): " + harvestedCollection.getCollection().getID().toString());
harvester.purgeCollection(harvestedCollection.getCollection().getID().toString(), eperson);
}
context.complete();
}
context.complete();
}
// Delete all items in a collection. Useful for testing fresh harvests.
else if ("purge".equals(command))
@@ -247,9 +245,9 @@ public class Harvest
}
if (metadataKey == null)
{
System.out.println("Error - a metadata key (commonly the prefix) must be specified for this collection");
System.out.println("Error - a metadata key (commonly the prefix) must be specified for this collection");
System.out.println(" (run with -h flag for details)");
System.exit(1);
System.exit(1);
}
harvester.configureCollection(collection, harvestType, oaiSource, oaiSetID, metadataKey);
@@ -272,13 +270,13 @@ public class Harvest
* the collection, if not, bail out.
*/
private Collection resolveCollection(String collectionID) {
DSpaceObject dso;
Collection targetCollection = null;
try {
// is the ID a handle?
if (collectionID != null)
DSpaceObject dso;
Collection targetCollection = null;
try {
// is the ID a handle?
if (collectionID != null)
{
if (collectionID.indexOf('/') != -1)
{
@@ -309,45 +307,45 @@ public class Harvest
System.out.println("Cannot resolve " + collectionID + " to collection");
System.exit(1);
}
}
catch (SQLException se) {
se.printStackTrace();
}
return targetCollection;
}
catch (SQLException se) {
se.printStackTrace();
}
return targetCollection;
}
private void configureCollection(String collectionID, int type, String oaiSource, String oaiSetId, String mdConfigId) {
System.out.println("Running: configure collection");
Collection collection = resolveCollection(collectionID);
System.out.println(collection.getID());
try {
HarvestedCollection hc = harvestedCollectionService.find(context, collection);
if (hc == null) {
hc = harvestedCollectionService.create(context, collection);
}
context.turnOffAuthorisationSystem();
hc.setHarvestParams(type, oaiSource, oaiSetId, mdConfigId);
hc.setHarvestStatus(HarvestedCollection.STATUS_READY);
System.out.println("Running: configure collection");
Collection collection = resolveCollection(collectionID);
System.out.println(collection.getID());
try {
HarvestedCollection hc = harvestedCollectionService.find(context, collection);
if (hc == null) {
hc = harvestedCollectionService.create(context, collection);
}
context.turnOffAuthorisationSystem();
hc.setHarvestParams(type, oaiSource, oaiSetId, mdConfigId);
hc.setHarvestStatus(HarvestedCollection.STATUS_READY);
harvestedCollectionService.update(context, hc);
context.restoreAuthSystemState();
context.complete();
}
catch (Exception e) {
System.out.println("Changes could not be committed");
e.printStackTrace();
System.exit(1);
}
finally {
context.restoreAuthSystemState();
context.complete();
}
catch (Exception e) {
System.out.println("Changes could not be committed");
e.printStackTrace();
System.exit(1);
}
finally {
if (context != null)
{
context.restoreAuthSystemState();
context.restoreAuthSystemState();
}
}
}
}
@@ -358,49 +356,49 @@ public class Harvest
* @param email
*/
private void purgeCollection(String collectionID, String email) {
System.out.println("Purging collection of all items and resetting last_harvested and harvest_message: " + collectionID);
Collection collection = resolveCollection(collectionID);
try
{
EPerson eperson = ePersonService.findByEmail(context, email);
context.setCurrentUser(eperson);
context.turnOffAuthorisationSystem();
System.out.println("Purging collection of all items and resetting last_harvested and harvest_message: " + collectionID);
Collection collection = resolveCollection(collectionID);
try
{
EPerson eperson = ePersonService.findByEmail(context, email);
context.setCurrentUser(eperson);
context.turnOffAuthorisationSystem();
ItemService itemService = ContentServiceFactory.getInstance().getItemService();
Iterator<Item> it = itemService.findByCollection(context, collection);
int i=0;
while (it.hasNext()) {
i++;
Item item = it.next();
System.out.println("Deleting: " + item.getHandle());
int i=0;
while (it.hasNext()) {
i++;
Item item = it.next();
System.out.println("Deleting: " + item.getHandle());
collectionService.removeItem(context, collection, item);
// Dispatch events every 50 items
if (i%50 == 0) {
context.dispatchEvents();
i=0;
}
}
HarvestedCollection hc = harvestedCollectionService.find(context, collection);
if (hc != null) {
hc.setLastHarvested(null);
// Dispatch events every 50 items
if (i%50 == 0) {
context.dispatchEvents();
i=0;
}
}
HarvestedCollection hc = harvestedCollectionService.find(context, collection);
if (hc != null) {
hc.setLastHarvested(null);
hc.setHarvestMessage("");
hc.setHarvestStatus(HarvestedCollection.STATUS_READY);
hc.setHarvestStartTime(null);
hc.setHarvestStatus(HarvestedCollection.STATUS_READY);
hc.setHarvestStartTime(null);
harvestedCollectionService.update(context, hc);
}
context.restoreAuthSystemState();
}
context.restoreAuthSystemState();
context.dispatchEvents();
}
catch (Exception e) {
System.out.println("Changes could not be committed");
e.printStackTrace();
System.exit(1);
}
finally {
context.restoreAuthSystemState();
}
}
catch (Exception e) {
System.out.println("Changes could not be committed");
e.printStackTrace();
System.exit(1);
}
finally {
context.restoreAuthSystemState();
}
}
@@ -408,34 +406,34 @@ public class Harvest
* Run a single harvest cycle on the specified collection under the authorization of the supplied EPerson
*/
private void runHarvest(String collectionID, String email) {
System.out.println("Running: a harvest cycle on " + collectionID);
System.out.print("Initializing the harvester... ");
OAIHarvester harvester = null;
try {
Collection collection = resolveCollection(collectionID);
HarvestedCollection hc = harvestedCollectionService.find(context, collection);
harvester = new OAIHarvester(context, collection, hc);
System.out.println("success. ");
}
catch (HarvestingException hex) {
System.out.print("failed. ");
System.out.println(hex.getMessage());
throw new IllegalStateException("Unable to harvest", hex);
} catch (SQLException se) {
System.out.println("Running: a harvest cycle on " + collectionID);
System.out.print("Initializing the harvester... ");
OAIHarvester harvester = null;
try {
Collection collection = resolveCollection(collectionID);
HarvestedCollection hc = harvestedCollectionService.find(context, collection);
harvester = new OAIHarvester(context, collection, hc);
System.out.println("success. ");
}
catch (HarvestingException hex) {
System.out.print("failed. ");
System.out.println(hex.getMessage());
throw new IllegalStateException("Unable to harvest", hex);
} catch (SQLException se) {
System.out.print("failed. ");
System.out.println(se.getMessage());
throw new IllegalStateException("Unable to access database", se);
}
try {
// Harvest will not work for an anonymous user
EPerson eperson = ePersonService.findByEmail(context, email);
System.out.println("Harvest started... ");
context.setCurrentUser(eperson);
harvester.runHarvest();
context.complete();
}
}
try {
// Harvest will not work for an anonymous user
EPerson eperson = ePersonService.findByEmail(context, email);
System.out.println("Harvest started... ");
context.setCurrentUser(eperson);
harvester.runHarvest();
context.complete();
}
catch (SQLException e) {
throw new IllegalStateException("Failed to run harvester", e);
}
@@ -453,10 +451,10 @@ public class Harvest
* Resets harvest_status and harvest_start_time flags for all collections that have a row in the harvested_collections table
*/
private static void resetHarvesting() {
System.out.print("Resetting harvest status flag on all collections... ");
System.out.print("Resetting harvest status flag on all collections... ");
try
{
try
{
List<HarvestedCollection> harvestedCollections = harvestedCollectionService.findAll(context);
for (HarvestedCollection harvestedCollection : harvestedCollections)
{
@@ -466,11 +464,11 @@ public class Harvest
harvestedCollectionService.update(context, harvestedCollection);
}
System.out.println("success. ");
}
catch (Exception ex) {
}
catch (Exception ex) {
System.out.println("failed. ");
ex.printStackTrace();
}
}
}
/**
@@ -483,10 +481,10 @@ public class Harvest
System.out.print("Starting harvest loop... ");
HarvestServiceFactory.getInstance().getHarvestSchedulingService().startNewScheduler();
System.out.println("running. ");
}
catch (Exception ex) {
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**

View File

@@ -16,38 +16,38 @@ import org.dspace.content.Bitstream;
*
*/
public class BitstreamFilterByFilename extends BitstreamFilter {
protected Pattern pattern;
protected Pattern pattern;
protected String filenameRegex;
public BitstreamFilterByFilename()
{
//empty
}
public BitstreamFilterByFilename()
{
//empty
}
/**
* Tests bitstream by matching the regular expression in the
* properties against the bitstream name
*
* @param bitstream Bitstream
* @return whether bitstream name matches the regular expression
* @exception BitstreamFilterException if filter error
*/
@Override
/**
* Tests bitstream by matching the regular expression in the
* properties against the bitstream name
*
* @param bitstream Bitstream
* @return whether bitstream name matches the regular expression
* @throws BitstreamFilterException if filter error
*/
@Override
public boolean accept(Bitstream bitstream) throws BitstreamFilterException
{
if (filenameRegex == null)
{
filenameRegex = props.getProperty("filename");
if (filenameRegex == null)
{
throw new BitstreamFilterException("BitstreamFilter property 'filename' not found.");
}
pattern = Pattern.compile(filenameRegex);
}
Matcher m = pattern.matcher(bitstream.getName());
return m.matches();
}
{
if (filenameRegex == null)
{
filenameRegex = props.getProperty("filename");
if (filenameRegex == null)
{
throw new BitstreamFilterException("BitstreamFilter property 'filename' not found.");
}
pattern = Pattern.compile(filenameRegex);
}
Matcher m = pattern.matcher(bitstream.getName());
return m.matches();
}
}

View File

@@ -34,7 +34,7 @@ import org.dspace.eperson.service.EPersonService;
/**
*
* Provides some batch editing capabilities for items in DSpace:
* Metadata fields - Add, Delete
* Metadata fields - Add, Delete
* Bitstreams - Add, Delete
*
* The design has been for compatibility with ItemImporter
@@ -62,33 +62,33 @@ import org.dspace.eperson.service.EPersonService;
*
*/
public class ItemUpdate {
public static final String SUPPRESS_UNDO_FILENAME = "suppress_undo";
public static final String SUPPRESS_UNDO_FILENAME = "suppress_undo";
public static final String CONTENTS_FILE = "contents";
public static final String DELETE_CONTENTS_FILE = "delete_contents";
public static final String CONTENTS_FILE = "contents";
public static final String DELETE_CONTENTS_FILE = "delete_contents";
public static String HANDLE_PREFIX = null;
public static final Map<String, String> filterAliases = new HashMap<String, String>();
public static boolean verbose = false;
public static String HANDLE_PREFIX = null;
public static final Map<String, String> filterAliases = new HashMap<String, String>();
public static boolean verbose = false;
protected static final EPersonService epersonService = EPersonServiceFactory.getInstance().getEPersonService();
protected static final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
static
{
filterAliases.put("ORIGINAL", "org.dspace.app.itemupdate.OriginalBitstreamFilter");
filterAliases.put("ORIGINAL_AND_DERIVATIVES", "org.dspace.app.itemupdate.OriginalWithDerivativesBitstreamFilter");
filterAliases.put("TEXT", "org.dspace.app.itemupdate.DerivativeTextBitstreamFilter");
filterAliases.put("THUMBNAIL", "org.dspace.app.itemupdate.ThumbnailBitstreamFilter");
}
static
{
filterAliases.put("ORIGINAL", "org.dspace.app.itemupdate.OriginalBitstreamFilter");
filterAliases.put("ORIGINAL_AND_DERIVATIVES", "org.dspace.app.itemupdate.OriginalWithDerivativesBitstreamFilter");
filterAliases.put("TEXT", "org.dspace.app.itemupdate.DerivativeTextBitstreamFilter");
filterAliases.put("THUMBNAIL", "org.dspace.app.itemupdate.ThumbnailBitstreamFilter");
}
// File listing filter to check for folders
static FilenameFilter directoryFilter = new FilenameFilter()
{
@Override
public boolean accept(File dir, String n)
public boolean accept(File dir, String n)
{
File f = new File(dir.getAbsolutePath() + File.separatorChar + n);
return f.isDirectory();
@@ -99,7 +99,7 @@ public class ItemUpdate {
static FilenameFilter fileFilter = new FilenameFilter()
{
@Override
public boolean accept(File dir, String n)
public boolean accept(File dir, String n)
{
File f = new File(dir.getAbsolutePath() + File.separatorChar + n);
return (f.isFile());
@@ -113,7 +113,7 @@ public class ItemUpdate {
/**
*
* @param argv commandline args
* @param argv the command line arguments given
*/
public static void main(String[] argv)
{
@@ -122,11 +122,11 @@ public class ItemUpdate {
Options options = new Options();
//processing basis for determining items
//processing basis for determining items
//item-specific changes with metadata in source directory with dublin_core.xml files
options.addOption("s", "source", true, "root directory of source dspace archive ");
//actions on items
//actions on items
options.addOption("a", "addmetadata", true, "add metadata specified for each item; multiples separated by semicolon ';'");
options.addOption("d", "deletemetadata", true, "delete metadata specified for each item");
@@ -138,13 +138,13 @@ public class ItemUpdate {
delBitstreamOption.setArgName("BitstreamFilter");
options.addOption(delBitstreamOption);
//other params
//other params
options.addOption("e", "eperson", true, "email of eperson doing the update");
options.addOption("i", "itemfield", true, "optional metadata field that containing item identifier; default is dc.identifier.uri");
options.addOption("F", "filter-properties", true, "filter class name; only for deleting bitstream");
options.addOption("v", "verbose", false, "verbose logging");
//special run states
//special run states
options.addOption("t", "test", false, "test run - do not actually import items");
options.addOption("P", "provenance", false, "suppress altering provenance field for bitstream changes");
options.addOption("h", "help", false, "help");
@@ -156,216 +156,216 @@ public class ItemUpdate {
String metadataIndexName = null;
Context context = null;
ItemUpdate iu = new ItemUpdate();
ItemUpdate iu = new ItemUpdate();
try
{
CommandLine line = parser.parse(options, argv);
if (line.hasOption('h'))
{
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("ItemUpdate", options);
pr("");
pr("Examples:");
pr(" adding metadata: ItemUpdate -e jsmith@mit.edu -s sourcedir -a dc.contributor -a dc.subject ");
pr(" deleting metadata: ItemUpdate -e jsmith@mit.edu -s sourcedir -d dc.description.other");
pr(" adding bitstreams: ItemUpdate -e jsmith@mit.edu -s sourcedir -A -i dc.identifier");
pr(" deleting bitstreams: ItemUpdate -e jsmith@mit.edu -s sourcedir -D ORIGINAL ");
pr("");
System.exit(0);
}
if (line.hasOption('v'))
{
verbose = true;
}
CommandLine line = parser.parse(options, argv);
if (line.hasOption('h'))
{
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("ItemUpdate", options);
pr("");
pr("Examples:");
pr(" adding metadata: ItemUpdate -e jsmith@mit.edu -s sourcedir -a dc.contributor -a dc.subject ");
pr(" deleting metadata: ItemUpdate -e jsmith@mit.edu -s sourcedir -d dc.description.other");
pr(" adding bitstreams: ItemUpdate -e jsmith@mit.edu -s sourcedir -A -i dc.identifier");
pr(" deleting bitstreams: ItemUpdate -e jsmith@mit.edu -s sourcedir -D ORIGINAL ");
pr("");
System.exit(0);
}
if (line.hasOption('v'))
{
verbose = true;
}
if (line.hasOption('P'))
{
alterProvenance = false;
pr("Suppressing changes to Provenance field option");
}
if (line.hasOption('P'))
{
alterProvenance = false;
pr("Suppressing changes to Provenance field option");
}
iu.eperson = line.getOptionValue('e'); // db ID or email
if (!line.hasOption('s')) // item specific changes from archive dir
{
pr("Missing source archive option");
System.exit(1);
}
String sourcedir = line.getOptionValue('s');
if (line.hasOption('t')) //test
{
isTest = true;
pr("**Test Run** - not actually updating items.");
}
if (line.hasOption('i'))
{
itemField = line.getOptionValue('i');
}
iu.eperson = line.getOptionValue('e'); // db ID or email
if (!line.hasOption('s')) // item specific changes from archive dir
{
pr("Missing source archive option");
System.exit(1);
}
String sourcedir = line.getOptionValue('s');
if (line.hasOption('t')) //test
{
isTest = true;
pr("**Test Run** - not actually updating items.");
}
if (line.hasOption('i'))
{
itemField = line.getOptionValue('i');
}
if (line.hasOption('d'))
{
String[] targetFields = line.getOptionValues('d');
DeleteMetadataAction delMetadataAction = (DeleteMetadataAction) iu.actionMgr.getUpdateAction(DeleteMetadataAction.class);
delMetadataAction.addTargetFields(targetFields);
//undo is an add
for (String field : targetFields)
{
iu.undoActionList.add(" -a " + field + " ");
}
pr("Delete metadata for fields: ");
for (String s : targetFields)
{
pr(" " + s);
}
}
if (line.hasOption('a'))
{
String[] targetFields = line.getOptionValues('a');
AddMetadataAction addMetadataAction = (AddMetadataAction) iu.actionMgr.getUpdateAction(AddMetadataAction.class);
addMetadataAction.addTargetFields(targetFields);
//undo is a delete followed by an add of a replace record for target fields
for (String field : targetFields)
{
iu.undoActionList.add(" -d " + field + " ");
}
for (String field : targetFields)
{
iu.undoActionList.add(" -a " + field + " ");
}
pr("Add metadata for fields: ");
for (String s : targetFields)
{
pr(" " + s);
}
}
if (line.hasOption('D')) // undo not supported
{
pr("Delete bitstreams ");
String[] filterNames = line.getOptionValues('D');
if ((filterNames != null) && (filterNames.length > 1))
{
pr("Error: Only one filter can be a used at a time.");
System.exit(1);
}
String filterName = line.getOptionValue('D');
pr("Filter argument: " + filterName);
if (filterName == null) // indicates using delete_contents files
{
DeleteBitstreamsAction delAction = (DeleteBitstreamsAction) iu.actionMgr.getUpdateAction(DeleteBitstreamsAction.class);
delAction.setAlterProvenance(alterProvenance);
}
else
{
// check if param is on ALIAS list
String filterClassname = filterAliases.get(filterName);
if (filterClassname == null)
{
filterClassname = filterName;
}
BitstreamFilter filter = null;
if (line.hasOption('d'))
{
String[] targetFields = line.getOptionValues('d');
DeleteMetadataAction delMetadataAction = (DeleteMetadataAction) iu.actionMgr.getUpdateAction(DeleteMetadataAction.class);
delMetadataAction.addTargetFields(targetFields);
//undo is an add
for (String field : targetFields)
{
iu.undoActionList.add(" -a " + field + " ");
}
pr("Delete metadata for fields: ");
for (String s : targetFields)
{
pr(" " + s);
}
}
if (line.hasOption('a'))
{
String[] targetFields = line.getOptionValues('a');
AddMetadataAction addMetadataAction = (AddMetadataAction) iu.actionMgr.getUpdateAction(AddMetadataAction.class);
addMetadataAction.addTargetFields(targetFields);
//undo is a delete followed by an add of a replace record for target fields
for (String field : targetFields)
{
iu.undoActionList.add(" -d " + field + " ");
}
for (String field : targetFields)
{
iu.undoActionList.add(" -a " + field + " ");
}
pr("Add metadata for fields: ");
for (String s : targetFields)
{
pr(" " + s);
}
}
if (line.hasOption('D')) // undo not supported
{
pr("Delete bitstreams ");
String[] filterNames = line.getOptionValues('D');
if ((filterNames != null) && (filterNames.length > 1))
{
pr("Error: Only one filter can be a used at a time.");
System.exit(1);
}
String filterName = line.getOptionValue('D');
pr("Filter argument: " + filterName);
if (filterName == null) // indicates using delete_contents files
{
DeleteBitstreamsAction delAction = (DeleteBitstreamsAction) iu.actionMgr.getUpdateAction(DeleteBitstreamsAction.class);
delAction.setAlterProvenance(alterProvenance);
}
else
{
// check if param is on ALIAS list
String filterClassname = filterAliases.get(filterName);
if (filterClassname == null)
{
filterClassname = filterName;
}
BitstreamFilter filter = null;
try
{
Class<?> cfilter = Class.forName(filterClassname);
pr("BitstreamFilter class to instantiate: " + cfilter.toString());
filter = (BitstreamFilter) cfilter.newInstance(); //unfortunate cast, an erasure consequence
}
catch(Exception e)
{
pr("Error: Failure instantiating bitstream filter class: " + filterClassname);
System.exit(1);
}
String filterPropertiesName = line.getOptionValue('F');
if (filterPropertiesName != null) //not always required
{
try
{
// TODO try multiple relative locations, e.g. source dir
if (!filterPropertiesName.startsWith("/"))
{
filterPropertiesName = sourcedir + File.separator + filterPropertiesName;
}
filter.initProperties(filterPropertiesName);
}
catch(Exception e)
{
pr("Error: Failure finding properties file for bitstream filter class: " + filterPropertiesName);
System.exit(1);
}
}
DeleteBitstreamsByFilterAction delAction =
(DeleteBitstreamsByFilterAction) iu.actionMgr.getUpdateAction(DeleteBitstreamsByFilterAction.class);
delAction.setAlterProvenance(alterProvenance);
delAction.setBitstreamFilter(filter);
//undo not supported
}
}
try
{
Class<?> cfilter = Class.forName(filterClassname);
pr("BitstreamFilter class to instantiate: " + cfilter.toString());
filter = (BitstreamFilter) cfilter.newInstance(); //unfortunate cast, an erasure consequence
}
catch(Exception e)
{
pr("Error: Failure instantiating bitstream filter class: " + filterClassname);
System.exit(1);
}
String filterPropertiesName = line.getOptionValue('F');
if (filterPropertiesName != null) //not always required
{
try
{
// TODO try multiple relative locations, e.g. source dir
if (!filterPropertiesName.startsWith("/"))
{
filterPropertiesName = sourcedir + File.separator + filterPropertiesName;
}
filter.initProperties(filterPropertiesName);
}
catch(Exception e)
{
pr("Error: Failure finding properties file for bitstream filter class: " + filterPropertiesName);
System.exit(1);
}
}
DeleteBitstreamsByFilterAction delAction =
(DeleteBitstreamsByFilterAction) iu.actionMgr.getUpdateAction(DeleteBitstreamsByFilterAction.class);
delAction.setAlterProvenance(alterProvenance);
delAction.setBitstreamFilter(filter);
//undo not supported
}
}
if (line.hasOption('A'))
{
pr("Add bitstreams ");
AddBitstreamsAction addAction = (AddBitstreamsAction) iu.actionMgr.getUpdateAction(AddBitstreamsAction.class);
addAction.setAlterProvenance(alterProvenance);
iu.undoActionList.add(" -D "); // delete_contents file will be written, no arg required
}
if (!iu.actionMgr.hasActions())
{
if (line.hasOption('A'))
{
pr("Add bitstreams ");
AddBitstreamsAction addAction = (AddBitstreamsAction) iu.actionMgr.getUpdateAction(AddBitstreamsAction.class);
addAction.setAlterProvenance(alterProvenance);
iu.undoActionList.add(" -D "); // delete_contents file will be written, no arg required
}
if (!iu.actionMgr.hasActions())
{
pr("Error - an action must be specified");
System.exit(1);
}
else
{
pr("Actions to be performed: ");
for (UpdateAction ua : iu.actionMgr)
{
pr(" " + ua.getClass().getName());
}
}
pr("ItemUpdate - initializing run on " + (new Date()).toString());
context = new Context();
iu.setEPerson(context, iu.eperson);
context.turnOffAuthorisationSystem();
HANDLE_PREFIX = ConfigurationManager.getProperty("handle.canonical.prefix");
if (HANDLE_PREFIX == null || HANDLE_PREFIX.length() == 0)
{
HANDLE_PREFIX = "http://hdl.handle.net/";
}
iu.processArchive(context, sourcedir, itemField, metadataIndexName, alterProvenance, isTest);
}
else
{
pr("Actions to be performed: ");
for (UpdateAction ua : iu.actionMgr)
{
pr(" " + ua.getClass().getName());
}
}
pr("ItemUpdate - initializing run on " + (new Date()).toString());
context = new Context();
iu.setEPerson(context, iu.eperson);
context.turnOffAuthorisationSystem();
HANDLE_PREFIX = ConfigurationManager.getProperty("handle.canonical.prefix");
if (HANDLE_PREFIX == null || HANDLE_PREFIX.length() == 0)
{
HANDLE_PREFIX = "http://hdl.handle.net/";
}
iu.processArchive(context, sourcedir, itemField, metadataIndexName, alterProvenance, isTest);
context.complete(); // complete all transactions
context.complete(); // complete all transactions
}
catch (Exception e)
{
@@ -378,7 +378,7 @@ public class ItemUpdate {
status = 1;
}
finally {
context.restoreAuthSystemState();
context.restoreAuthSystemState();
}
if (isTest)
@@ -387,14 +387,15 @@ public class ItemUpdate {
}
else
{
pr("End.");
pr("End.");
}
System.exit(status);
}
/**
* process an archive
*
* @param context DSpace Context
* @param sourceDirPath source path
* @param itemField item field
@@ -404,7 +405,7 @@ public class ItemUpdate {
* @throws Exception if error
*/
protected void processArchive(Context context, String sourceDirPath, String itemField,
String metadataIndexName, boolean alterProvenance, boolean isTest)
String metadataIndexName, boolean alterProvenance, boolean isTest)
throws Exception
{
// open and process the source directory
@@ -424,89 +425,89 @@ public class ItemUpdate {
File fSuppressUndo = new File(sourceDir, SUPPRESS_UNDO_FILENAME);
if (fSuppressUndo.exists())
{
suppressUndo = true;
suppressUndo = true;
}
File undoDir = null; //sibling directory of source archive
if (!suppressUndo && !isTest)
{
undoDir = initUndoArchive(sourceDir);
}
if (!suppressUndo && !isTest)
{
undoDir = initUndoArchive(sourceDir);
}
int itemCount = 0;
int successItemCount = 0;
int itemCount = 0;
int successItemCount = 0;
for (String dirname : dircontents)
{
itemCount++;
pr("");
pr("processing item " + dirname);
try
{
ItemArchive itarch = ItemArchive.create(context, new File(sourceDir, dirname), itemField);
for (UpdateAction action : actionMgr)
{
pr("action: " + action.getClass().getName());
action.execute(context, itarch, isTest, suppressUndo);
if (!isTest && !suppressUndo)
itemCount++;
pr("");
pr("processing item " + dirname);
try
{
ItemArchive itarch = ItemArchive.create(context, new File(sourceDir, dirname), itemField);
for (UpdateAction action : actionMgr)
{
pr("action: " + action.getClass().getName());
action.execute(context, itarch, isTest, suppressUndo);
if (!isTest && !suppressUndo)
{
itarch.writeUndo(undoDir);
}
}
if (!isTest)
{
Item item = itarch.getItem();
}
if (!isTest)
{
Item item = itarch.getItem();
itemService.update(context, item); //need to update before commit
}
ItemUpdate.pr("Item " + dirname + " completed");
successItemCount++;
}
catch(Exception e)
{
pr("Exception processing item " + dirname + ": " + e.toString());
}
ItemUpdate.pr("Item " + dirname + " completed");
successItemCount++;
}
catch(Exception e)
{
pr("Exception processing item " + dirname + ": " + e.toString());
e.printStackTrace();
}
}
}
if (!suppressUndo && !isTest)
{
StringBuilder sb = new StringBuilder("dsrun org.dspace.app.itemupdate.ItemUpdate ");
sb.append(" -e ").append(this.eperson);
sb.append(" -s ").append(undoDir);
if (itemField != null)
{
sb.append(" -i ").append(itemField);
}
if (!alterProvenance)
{
sb.append(" -P ");
}
if (isTest)
{
sb.append(" -t ");
}
for (String actionOption : undoActionList)
{
sb.append(actionOption);
}
PrintWriter pw = null;
try
{
File cmdFile = new File (undoDir.getParent(), undoDir.getName() + "_command.sh");
pw = new PrintWriter(new BufferedWriter(new FileWriter(cmdFile)));
pw.println(sb.toString());
}
finally
{
pw.close();
}
{
StringBuilder sb = new StringBuilder("dsrun org.dspace.app.itemupdate.ItemUpdate ");
sb.append(" -e ").append(this.eperson);
sb.append(" -s ").append(undoDir);
if (itemField != null)
{
sb.append(" -i ").append(itemField);
}
if (!alterProvenance)
{
sb.append(" -P ");
}
if (isTest)
{
sb.append(" -t ");
}
for (String actionOption : undoActionList)
{
sb.append(actionOption);
}
PrintWriter pw = null;
try
{
File cmdFile = new File (undoDir.getParent(), undoDir.getName() + "_command.sh");
pw = new PrintWriter(new BufferedWriter(new FileWriter(cmdFile)));
pw.println(sb.toString());
}
finally
{
pw.close();
}
}
pr("");
@@ -516,7 +517,6 @@ public class ItemUpdate {
/**
*
* to avoid overwriting the undo source tree on repeated processing
* sequence numbers are added and checked
*
@@ -526,45 +526,45 @@ public class ItemUpdate {
* @throws IOException if IO error
*/
protected File initUndoArchive(File sourceDir)
throws FileNotFoundException, IOException
{
File parentDir = sourceDir.getCanonicalFile().getParentFile();
if (parentDir == null)
{
throw new FileNotFoundException("Parent directory of archive directory not found; unable to write UndoArchive; no processing performed");
}
String sourceDirName = sourceDir.getName();
int seqNo = 1;
File undoDir = new File(parentDir, "undo_" + sourceDirName + "_" + seqNo);
while (undoDir.exists())
{
undoDir = new File(parentDir, "undo_" + sourceDirName+ "_" + ++seqNo); //increment
}
// create root directory
if (!undoDir.mkdir())
{
pr("ERROR creating Undo Archive directory " + undoDir.getCanonicalPath());
throw new IOException("ERROR creating Undo Archive directory " + undoDir.getCanonicalPath());
}
throws FileNotFoundException, IOException
{
File parentDir = sourceDir.getCanonicalFile().getParentFile();
if (parentDir == null)
{
throw new FileNotFoundException("Parent directory of archive directory not found; unable to write UndoArchive; no processing performed");
}
String sourceDirName = sourceDir.getName();
int seqNo = 1;
File undoDir = new File(parentDir, "undo_" + sourceDirName + "_" + seqNo);
while (undoDir.exists())
{
undoDir = new File(parentDir, "undo_" + sourceDirName+ "_" + ++seqNo); //increment
}
// create root directory
if (!undoDir.mkdir())
{
pr("ERROR creating Undo Archive directory " + undoDir.getCanonicalPath());
throw new IOException("ERROR creating Undo Archive directory " + undoDir.getCanonicalPath());
}
//Undo is suppressed to prevent undo of undo
File fSuppressUndo = new File(undoDir, ItemUpdate.SUPPRESS_UNDO_FILENAME);
try
{
fSuppressUndo.createNewFile();
fSuppressUndo.createNewFile();
}
catch(IOException e)
{
pr("ERROR creating Suppress Undo File " + e.toString());
throw e;
pr("ERROR creating Suppress Undo File " + e.toString());
throw e;
}
return undoDir;
}
//private void write
return undoDir;
}
//private void write
/**
* Set EPerson doing import
@@ -603,14 +603,15 @@ public class ItemUpdate {
}
/**
* poor man's logging
* As with ItemImport, API logging goes through log4j to the DSpace.log files
* whereas the batch logging goes to the console to be captured there.
* poor man's logging
* As with ItemImport, API logging goes through log4j to the DSpace.log files
* whereas the batch logging goes to the console to be captured there.
*
* @param s String
*/
static void pr(String s)
{
System.out.println(s);
System.out.println(s);
}
/**
@@ -619,10 +620,10 @@ public class ItemUpdate {
*/
static void prv(String s)
{
if (verbose)
{
System.out.println(s);
}
if (verbose)
{
System.out.println(s);
}
}
} //end of class

View File

@@ -25,7 +25,7 @@ public class CommandRunner
{
/**
*
* @param args commandline args
* @param args the command line arguments given
* @throws IOException if IO error
* @throws FileNotFoundException if file doesn't exist
*/

View File

@@ -92,8 +92,9 @@ public class ScriptLauncher
/**
* Recognize and execute a single command.
*
* @param doc Document
* @param args arguments
* @param args the command line arguments given
*/
static int runOneCommand(Document commandConfigs, String[] args)
{

View File

@@ -61,7 +61,7 @@ public abstract class MediaFilter implements FormatFilter
* @param generatedBitstream
* the bitstream which was generated by
* this filter.
* @throws java.lang.Exception
* @throws Exception if error
*/
@Override
public void postProcessBitstream(Context c, Item item, Bitstream generatedBitstream)

View File

@@ -24,13 +24,20 @@ public interface RequestItemService {
/**
* Generate a request item representing the request and put it into the DB
* @param context context
* @param bitstream bitstream
* @param item item
* @param reqMessage message
* @param allFiles all files flag
* @param context
* The relevant DSpace Context.
* @param bitstream
* The requested bitstream
* @param item
* The requested item
* @param reqMessage
* Request message text
* @param allFiles
* true indicates that all bitstreams of this item are requested
* @param reqEmail email
* @param reqName name
* Requester email
* @param reqName
* Requester name
* @return the token of the request item
* @throws SQLException if database error
*/
@@ -41,8 +48,11 @@ public interface RequestItemService {
/**
* Save updates to the record. Only accept_request, and decision_date are set-able.
*
* @param context
* The relevant DSpace Context.
* @param requestItem
* requested item
*/
public void update(Context context, RequestItem requestItem);

View File

@@ -212,7 +212,7 @@ public class LogAnalyser
/**
* main method to be run from command line. See usage information for
* details as to how to use the command line flags (-help)
* @param argv arguments
* @param argv the command line arguments given
* @throws Exception if error
* @throws SQLException if database error
*/
@@ -1051,7 +1051,7 @@ public class LogAnalyser
{
// Use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'MM'-'dd'T'hh:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(date);
}
@@ -1187,13 +1187,13 @@ public class LogAnalyser
// that
DiscoverQuery discoverQuery = new DiscoverQuery();
if(StringUtils.isNotBlank(type))
if (StringUtils.isNotBlank(type))
{
discoverQuery.addFilterQueries("dc.type=" + type +"*");
}
StringBuilder accessionedQuery = new StringBuilder();
accessionedQuery.append("dc.date.accessioned_dt:[");
if(startDate != null)
if (startDate != null)
{
accessionedQuery.append(unParseDate(startDate));
}
@@ -1202,7 +1202,7 @@ public class LogAnalyser
accessionedQuery.append("*");
}
accessionedQuery.append(" TO ");
if(endDate != null)
if (endDate != null)
{
accessionedQuery.append(unParseDate(endDate));
}
@@ -1242,44 +1242,44 @@ public class LogAnalyser
public static void usage()
{
String usage = "Usage Information:\n" +
"LogAnalyser [options [parameters]]\n" +
"-log [log directory]\n" +
"\tOptional\n" +
"\tSpecify a directory containing log files\n" +
"\tDefault uses [dspace.dir]/log from dspace.cfg\n" +
"-file [file name regex]\n" +
"\tOptional\n" +
"\tSpecify a regular expression as the file name template.\n" +
"\tCurrently this needs to be correctly escaped for Java string handling (FIXME)\n" +
"\tDefault uses dspace.log*\n" +
"-cfg [config file path]\n" +
"\tOptional\n" +
"\tSpecify a config file to be used\n" +
"\tDefault uses dstat.cfg in dspace config directory\n" +
"-out [output file path]\n" +
"\tOptional\n" +
"\tSpecify an output file to write results into\n" +
"\tDefault uses dstat.dat in dspace log directory\n" +
"-start [YYYY-MM-DD]\n" +
"\tOptional\n" +
"\tSpecify the start date of the analysis\n" +
"\tIf a start date is specified then no attempt to gather \n" +
"\tcurrent database statistics will be made unless -lookup is\n" +
"\talso passed\n" +
"\tDefault is to start from the earliest date records exist for\n" +
"-end [YYYY-MM-DD]\n" +
"\tOptional\n" +
"\tSpecify the end date of the analysis\n" +
"\tIf an end date is specified then no attempt to gather \n" +
"\tcurrent database statistics will be made unless -lookup is\n" +
"\talso passed\n" +
"\tDefault is to work up to the last date records exist for\n" +
"-lookup\n" +
"\tOptional\n" +
"\tForce a lookup of the current database statistics\n" +
"\tOnly needs to be used if date constraints are also in place\n" +
"-help\n" +
"\tdisplay this usage information\n";
"LogAnalyser [options [parameters]]\n" +
"-log [log directory]\n" +
"\tOptional\n" +
"\tSpecify a directory containing log files\n" +
"\tDefault uses [dspace.dir]/log from dspace.cfg\n" +
"-file [file name regex]\n" +
"\tOptional\n" +
"\tSpecify a regular expression as the file name template.\n" +
"\tCurrently this needs to be correctly escaped for Java string handling (FIXME)\n" +
"\tDefault uses dspace.log*\n" +
"-cfg [config file path]\n" +
"\tOptional\n" +
"\tSpecify a config file to be used\n" +
"\tDefault uses dstat.cfg in dspace config directory\n" +
"-out [output file path]\n" +
"\tOptional\n" +
"\tSpecify an output file to write results into\n" +
"\tDefault uses dstat.dat in dspace log directory\n" +
"-start [YYYY-MM-DD]\n" +
"\tOptional\n" +
"\tSpecify the start date of the analysis\n" +
"\tIf a start date is specified then no attempt to gather \n" +
"\tcurrent database statistics will be made unless -lookup is\n" +
"\talso passed\n" +
"\tDefault is to start from the earliest date records exist for\n" +
"-end [YYYY-MM-DD]\n" +
"\tOptional\n" +
"\tSpecify the end date of the analysis\n" +
"\tIf an end date is specified then no attempt to gather \n" +
"\tcurrent database statistics will be made unless -lookup is\n" +
"\talso passed\n" +
"\tDefault is to work up to the last date records exist for\n" +
"-lookup\n" +
"\tOptional\n" +
"\tForce a lookup of the current database statistics\n" +
"\tOnly needs to be used if date constraints are also in place\n" +
"-help\n" +
"\tdisplay this usage information\n";
System.out.println(usage);
}

View File

@@ -125,14 +125,14 @@ public class ReportGenerator
private static Pattern real = Pattern.compile("^(.+)=(.+)");
//////////////////////////
// Miscellaneous variables
//////////////////////////
/** process timing clock */
private static Calendar startTime = null;
/** a map from log file action to human readable action */
private static Map<String, String> actionMap = null;
// Miscellaneous variables
//////////////////////////
/** process timing clock */
private static Calendar startTime = null;
/** a map from log file action to human readable action */
private static Map<String, String> actionMap = null;
/////////////////
// report generator config data
@@ -141,9 +141,9 @@ public class ReportGenerator
/** the input file to build the report from */
private static String input = null;
/** the log file action to human readable action map */
private static String map = ConfigurationManager.getProperty("dspace.dir") +
File.separator + "config" + File.separator + "dstat.map";
/** the log file action to human readable action map */
private static String map = ConfigurationManager.getProperty("dspace.dir") +
File.separator + "config" + File.separator + "dstat.map";
private static final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
private static final HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
@@ -152,9 +152,10 @@ public class ReportGenerator
/**
* main method to be run from command line. See usage information for
* details as to how to use the command line flags
* @param argv
* @throws java.lang.Exception
* @throws java.sql.SQLException
* @param argv the command line arguments given
* @throws Exception on generic exception
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public static void main(String [] argv)
throws Exception, SQLException

View File

@@ -24,14 +24,16 @@ import org.dspace.core.Context;
public class CollectionDropDown {
private static final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
private static final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
/**
* Get full path starting from a top-level community via subcommunities down to a collection.
* The full path will not be truncated.
*
* @param context
* The relevant DSpace Context.
* @param col
* Get full path for this collection
* Get full path for this collection
* @return Full path to the collection
* @throws SQLException if database error
*/
@@ -44,10 +46,12 @@ public class CollectionDropDown {
* Get full path starting from a top-level community via subcommunities down to a collection.
* The full cat will be truncated to the specified number of characters and prepended with an ellipsis.
*
* @param context
* The relevant DSpace Context.
* @param col
* Get full path for this collection
* Get full path for this collection
* @param maxchars
* Truncate the full path to maxchar characters. 0 means do not truncate.
* Truncate the full path to maxchar characters. 0 means do not truncate.
* @return Full path to the collection (truncated)
* @throws SQLException if database error
*/
@@ -82,62 +86,64 @@ public class CollectionDropDown {
return name.toString();
}
/**
* Annotates an array of collections with their respective full paths (@see #collectionPath() method in this class).
* @param collections An array of collections to annotate with their hierarchical paths.
* The array and all its entries must be non-null.
* @return A sorted array of collection path entries (essentially collection/path pairs).
* @throws SQLException In case there are problems annotating a collection with its path.
*/
public static CollectionPathEntry[] annotateWithPaths(Context context, List<Collection> collections) throws SQLException
{
CollectionPathEntry[] result = new CollectionPathEntry[collections.size()];
for (int i = 0; i < collections.size(); i++)
{
Collection collection = collections.get(i);
CollectionPathEntry entry = new CollectionPathEntry(collection, collectionPath(context, collection));
result[i] = entry;
}
Arrays.sort(result);
return result;
}
/**
* Annotates an array of collections with their respective full paths (@see #collectionPath() method in this class).
* @param context
* The relevant DSpace Context.
* @param collections An array of collections to annotate with their hierarchical paths.
* The array and all its entries must be non-null.
* @return A sorted array of collection path entries (essentially collection/path pairs).
* @throws SQLException In case there are problems annotating a collection with its path.
*/
public static CollectionPathEntry[] annotateWithPaths(Context context, List<Collection> collections) throws SQLException
{
CollectionPathEntry[] result = new CollectionPathEntry[collections.size()];
for (int i = 0; i < collections.size(); i++)
{
Collection collection = collections.get(i);
CollectionPathEntry entry = new CollectionPathEntry(collection, collectionPath(context, collection));
result[i] = entry;
}
Arrays.sort(result);
return result;
}
/**
* A helper class to hold (collection, full path) pairs. Instances of the helper class are sortable:
* two instances will be compared first on their full path and if those are equal,
* the comparison will fall back to comparing collection IDs.
*/
public static class CollectionPathEntry implements Comparable<CollectionPathEntry>
{
public Collection collection;
public String path;
/**
* A helper class to hold (collection, full path) pairs. Instances of the helper class are sortable:
* two instances will be compared first on their full path and if those are equal,
* the comparison will fall back to comparing collection IDs.
*/
public static class CollectionPathEntry implements Comparable<CollectionPathEntry>
{
public Collection collection;
public String path;
public CollectionPathEntry(Collection collection, String path)
{
this.collection = collection;
this.path = path;
}
public CollectionPathEntry(Collection collection, String path)
{
this.collection = collection;
this.path = path;
}
@Override
public int compareTo(CollectionPathEntry other)
{
if (!this.path.equals(other.path))
{
return this.path.compareTo(other.path);
}
return this.collection.getID().compareTo(other.collection.getID());
}
@Override
public int compareTo(CollectionPathEntry other)
{
if (!this.path.equals(other.path))
{
return this.path.compareTo(other.path);
}
return this.collection.getID().compareTo(other.collection.getID());
}
@Override
public boolean equals(Object o)
{
return o != null && o instanceof CollectionPathEntry && this.compareTo((CollectionPathEntry) o) == 0;
}
@Override
public boolean equals(Object o)
{
return o != null && o instanceof CollectionPathEntry && this.compareTo((CollectionPathEntry) o) == 0;
}
@Override
public int hashCode()
{
return Objects.hash(path, collection.getID());
}
}
@Override
public int hashCode()
{
return Objects.hash(path, collection.getID());
}
}
}

View File

@@ -36,8 +36,7 @@ public class Configuration
* </ul>
* If the property does not exist, nothing is written.
*
* @param argv
* command-line arguments
* @param argv the command line arguments given
*/
public static void main(String[] argv)
{

View File

@@ -94,8 +94,9 @@ public class DCInput
* a HashMap
*
* @param fieldMap
* ???
*
* @param listMap
* value-pairs map, computed from the forms definition XML file
*/
public DCInput(Map<String, String> fieldMap, Map<String, List<String>> listMap)
{

View File

@@ -20,80 +20,80 @@ import java.util.Map;
public class DCInputSet
{
/** name of the input set */
private String formName = null;
/** the inputs ordered by page and row position */
private DCInput[][] inputPages = null;
/** name of the input set */
private String formName = null;
/** the inputs ordered by page and row position */
private DCInput[][] inputPages = null;
/** constructor
* @param formName form name
* @param pages pages
* @param listMap map
*/
public DCInputSet(String formName, List<List<Map<String, String>>> pages, Map<String, List<String>> listMap)
{
this.formName = formName;
inputPages = new DCInput[pages.size()][];
for ( int i = 0; i < inputPages.length; i++ )
{
List<Map<String, String>> page = pages.get(i);
inputPages[i] = new DCInput[page.size()];
for ( int j = 0; j < inputPages[i].length; j++ )
{
inputPages[i][j] = new DCInput(page.get(j), listMap);
}
}
}
/**
* Return the name of the form that defines this input set
* @return formName the name of the form
*/
public String getFormName()
{
return formName;
}
/**
* Return the number of pages in this input set
* @return number of pages
*/
public int getNumberPages()
{
return inputPages.length;
}
public DCInputSet(String formName, List<List<Map<String, String>>> pages, Map<String, List<String>> listMap)
{
this.formName = formName;
inputPages = new DCInput[pages.size()][];
for ( int i = 0; i < inputPages.length; i++ )
{
List<Map<String, String>> page = pages.get(i);
inputPages[i] = new DCInput[page.size()];
for ( int j = 0; j < inputPages[i].length; j++ )
{
inputPages[i][j] = new DCInput(page.get(j), listMap);
}
}
}
/**
* Return the name of the form that defines this input set
* @return formName the name of the form
*/
public String getFormName()
{
return formName;
}
/**
* Return the number of pages in this input set
* @return number of pages
*/
public int getNumberPages()
{
return inputPages.length;
}
/**
* Get all the rows for a page from the form definition
*
* @param pageNum desired page within set
* @param pageNum desired page within set
* @param addTitleAlternative flag to add the additional title row
* @param addPublishedBefore flag to add the additional published info
*
* @return an array containing the page's displayable rows
*/
public DCInput[] getPageRows(int pageNum, boolean addTitleAlternative,
boolean addPublishedBefore)
{
List<DCInput> filteredInputs = new ArrayList<DCInput>();
if ( pageNum < inputPages.length )
{
for (int i = 0; i < inputPages[pageNum].length; i++ )
{
DCInput input = inputPages[pageNum][i];
if (doField(input, addTitleAlternative, addPublishedBefore))
{
filteredInputs.add(input);
}
}
}
public DCInput[] getPageRows(int pageNum, boolean addTitleAlternative,
boolean addPublishedBefore)
{
List<DCInput> filteredInputs = new ArrayList<DCInput>();
if ( pageNum < inputPages.length )
{
for (int i = 0; i < inputPages[pageNum].length; i++ )
{
DCInput input = inputPages[pageNum][i];
if (doField(input, addTitleAlternative, addPublishedBefore))
{
filteredInputs.add(input);
}
}
}
// Convert list into an array
DCInput[] inputArray = new DCInput[filteredInputs.size()];
return filteredInputs.toArray(inputArray);
}
// Convert list into an array
DCInput[] inputArray = new DCInput[filteredInputs.size()];
return filteredInputs.toArray(inputArray);
}
/**
* Does this set of inputs include an alternate title field?
*
@@ -101,7 +101,7 @@ public class DCInputSet
*/
public boolean isDefinedMultTitles()
{
return isFieldPresent("title.alternative");
return isFieldPresent("title.alternative");
}
/**
@@ -111,9 +111,9 @@ public class DCInputSet
*/
public boolean isDefinedPubBefore()
{
return ( isFieldPresent("date.issued") &&
isFieldPresent("identifier.citation") &&
isFieldPresent("publisher.null") );
return ( isFieldPresent("date.issued") &&
isFieldPresent("identifier.citation") &&
isFieldPresent("publisher.null") );
}
/**
@@ -125,22 +125,22 @@ public class DCInputSet
*/
public boolean isFieldPresent(String fieldName)
{
for (int i = 0; i < inputPages.length; i++)
{
DCInput[] pageInputs = inputPages[i];
for (int row = 0; row < pageInputs.length; row++)
{
String fullName = pageInputs[row].getElement() + "." +
pageInputs[row].getQualifier();
if (fullName.equals(fieldName))
{
return true;
}
}
}
return false;
for (int i = 0; i < inputPages.length; i++)
{
DCInput[] pageInputs = inputPages[i];
for (int row = 0; row < pageInputs.length; row++)
{
String fullName = pageInputs[row].getElement() + "." +
pageInputs[row].getQualifier();
if (fullName.equals(fieldName))
{
return true;
}
}
}
return false;
}
/**
* Does the current input set define the named field?
* and is valid for the specified document type
@@ -152,48 +152,48 @@ public class DCInputSet
*/
public boolean isFieldPresent(String fieldName, String documentType)
{
if(documentType == null){
documentType = "";
}
for (int i = 0; i < inputPages.length; i++)
{
DCInput[] pageInputs = inputPages[i];
for (int row = 0; row < pageInputs.length; row++)
{
String fullName = pageInputs[row].getElement() + "." +
pageInputs[row].getQualifier();
if (fullName.equals(fieldName) )
{
if(pageInputs[row].isAllowedFor(documentType)){
return true;
}
}
}
}
return false;
if (documentType == null) {
documentType = "";
}
for (int i = 0; i < inputPages.length; i++)
{
DCInput[] pageInputs = inputPages[i];
for (int row = 0; row < pageInputs.length; row++)
{
String fullName = pageInputs[row].getElement() + "." +
pageInputs[row].getQualifier();
if (fullName.equals(fieldName) )
{
if (pageInputs[row].isAllowedFor(documentType)) {
return true;
}
}
}
}
return false;
}
protected boolean doField(DCInput dcf, boolean addTitleAlternative,
boolean addPublishedBefore)
boolean addPublishedBefore)
{
String rowName = dcf.getElement() + "." + dcf.getQualifier();
if ( rowName.equals("title.alternative") && ! addTitleAlternative )
{
return false;
}
if (rowName.equals("date.issued") && ! addPublishedBefore )
{
return false;
}
if (rowName.equals("publisher.null") && ! addPublishedBefore )
{
return false;
}
if (rowName.equals("identifier.citation") && ! addPublishedBefore )
{
return false;
}
String rowName = dcf.getElement() + "." + dcf.getQualifier();
if ( rowName.equals("title.alternative") && ! addTitleAlternative )
{
return false;
}
if (rowName.equals("date.issued") && ! addPublishedBefore )
{
return false;
}
if (rowName.equals("publisher.null") && ! addPublishedBefore )
{
return false;
}
if (rowName.equals("identifier.citation") && ! addPublishedBefore )
{
return false;
}
return true;
return true;
}
}

View File

@@ -82,6 +82,7 @@ public class DCInputsReader
* level structures: a map between collections and forms, the definition for
* each page of each form, and lists of pairs of values that populate
* selection boxes.
*
* @throws DCInputsReaderException if input reader error
*/
@@ -90,7 +91,7 @@ public class DCInputsReader
{
// Load from default file
String defsFile = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir")
+ File.separator + "config" + File.separator + FORM_DEF_FILE;
+ File.separator + "config" + File.separator + FORM_DEF_FILE;
buildInputs(defsFile);
}
@@ -114,23 +115,23 @@ public class DCInputsReader
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(uri);
doNodes(doc);
checkValues();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(uri);
doNodes(doc);
checkValues();
}
catch (FactoryConfigurationError fe)
{
throw new DCInputsReaderException("Cannot create Submission form parser",fe);
throw new DCInputsReaderException("Cannot create Submission form parser",fe);
}
catch (Exception e)
{
throw new DCInputsReaderException("Error creating submission forms: "+e);
throw new DCInputsReaderException("Error creating submission forms: "+e);
}
}
@@ -155,27 +156,27 @@ public class DCInputsReader
* if no default set defined
*/
public DCInputSet getInputs(String collectionHandle)
throws DCInputsReaderException
throws DCInputsReaderException
{
String formName = whichForms.get(collectionHandle);
if (formName == null)
{
formName = whichForms.get(DEFAULT_COLLECTION);
formName = whichForms.get(DEFAULT_COLLECTION);
}
if (formName == null)
{
throw new DCInputsReaderException("No form designated as default");
throw new DCInputsReaderException("No form designated as default");
}
// check mini-cache, and return if match
if ( lastInputSet != null && lastInputSet.getFormName().equals( formName ) )
{
return lastInputSet;
return lastInputSet;
}
// cache miss - construct new DCInputSet
List<List<Map<String, String>>> pages = formDefns.get(formName);
if ( pages == null )
{
throw new DCInputsReaderException("Missing the " + formName + " form");
throw new DCInputsReaderException("Missing the " + formName + " form");
}
lastInputSet = new DCInputSet(formName, pages, valuePairs);
return lastInputSet;
@@ -197,13 +198,16 @@ public class DCInputsReader
* Process the top level child nodes in the passed top-level node. These
* should correspond to the collection-form maps, the form definitions, and
* the display/storage word pairs.
*
* @param n
* top-level DOM node
*/
private void doNodes(Node n)
throws SAXException, DCInputsReaderException
throws SAXException, DCInputsReaderException
{
if (n == null)
{
return;
return;
}
Node e = getElement(n);
NodeList nl = e.getChildNodes();
@@ -212,35 +216,35 @@ public class DCInputsReader
boolean foundDefs = false;
for (int i = 0; i < len; i++)
{
Node nd = nl.item(i);
if ((nd == null) || isEmptyTextNode(nd))
{
continue;
}
String tagName = nd.getNodeName();
if (tagName.equals("form-map"))
{
processMap(nd);
foundMap = true;
}
else if (tagName.equals("form-definitions"))
{
processDefinition(nd);
foundDefs = true;
}
else if (tagName.equals("form-value-pairs"))
{
processValuePairs(nd);
}
// Ignore unknown nodes
Node nd = nl.item(i);
if ((nd == null) || isEmptyTextNode(nd))
{
continue;
}
String tagName = nd.getNodeName();
if (tagName.equals("form-map"))
{
processMap(nd);
foundMap = true;
}
else if (tagName.equals("form-definitions"))
{
processDefinition(nd);
foundDefs = true;
}
else if (tagName.equals("form-value-pairs"))
{
processValuePairs(nd);
}
// Ignore unknown nodes
}
if (!foundMap)
{
throw new DCInputsReaderException("No collection to form map found");
throw new DCInputsReaderException("No collection to form map found");
}
if (!foundDefs)
{
throw new DCInputsReaderException("No form definition found");
throw new DCInputsReaderException("No form definition found");
}
}
@@ -258,26 +262,26 @@ public class DCInputsReader
int len = nl.getLength();
for (int i = 0; i < len; i++)
{
Node nd = nl.item(i);
if (nd.getNodeName().equals("name-map"))
Node nd = nl.item(i);
if (nd.getNodeName().equals("name-map"))
{
String id = getAttribute(nd, "collection-handle");
String value = getAttribute(nd, "form-name");
String content = getValue(nd);
if (id == null)
{
String id = getAttribute(nd, "collection-handle");
String value = getAttribute(nd, "form-name");
String content = getValue(nd);
if (id == null)
{
throw new SAXException("name-map element is missing collection-handle attribute");
}
if (value == null)
{
throw new SAXException("name-map element is missing form-name attribute");
}
if (content != null && content.length() > 0)
{
throw new SAXException("name-map element has content, it should be empty.");
}
whichForms.put(id, value);
} // ignore any child node that isn't a "name-map"
throw new SAXException("name-map element is missing collection-handle attribute");
}
if (value == null)
{
throw new SAXException("name-map element is missing form-name attribute");
}
if (content != null && content.length() > 0)
{
throw new SAXException("name-map element has content, it should be empty.");
}
whichForms.put(id, value);
} // ignore any child node that isn't a "name-map"
}
}
@@ -296,62 +300,61 @@ public class DCInputsReader
int len = nl.getLength();
for (int i = 0; i < len; i++)
{
Node nd = nl.item(i);
// process each form definition
if (nd.getNodeName().equals("form"))
Node nd = nl.item(i);
// process each form definition
if (nd.getNodeName().equals("form"))
{
numForms++;
String formName = getAttribute(nd, "name");
if (formName == null)
{
numForms++;
String formName = getAttribute(nd, "name");
if (formName == null)
{
throw new SAXException("form element has no name attribute");
}
List<List<Map<String, String>>> pages = new ArrayList<List<Map<String, String>>>(); // the form contains pages
formDefns.put(formName, pages);
NodeList pl = nd.getChildNodes();
int lenpg = pl.getLength();
for (int j = 0; j < lenpg; j++)
{
Node npg = pl.item(j);
// process each page definition
if (npg.getNodeName().equals("page"))
{
String pgNum = getAttribute(npg, "number");
if (pgNum == null)
{
throw new SAXException("Form " + formName + " has no identified pages");
}
List<Map<String, String>> page = new ArrayList<Map<String, String>>();
pages.add(page);
NodeList flds = npg.getChildNodes();
int lenflds = flds.getLength();
for (int k = 0; k < lenflds; k++)
{
Node nfld = flds.item(k);
if ( nfld.getNodeName().equals("field") )
{
// process each field definition
Map<String, String> field = new HashMap<String, String>();
page.add(field);
processPageParts(formName, pgNum, nfld, field);
// we omit the duplicate validation, allowing multiple fields definition for
// the same metadata and different visibility/type-bind
}
}
} // ignore any child that is not a 'page'
}
// sanity check number of pages
if (pages.size() < 1)
{
throw new DCInputsReaderException("Form " + formName + " has no pages");
}
throw new SAXException("form element has no name attribute");
}
List<List<Map<String, String>>> pages = new ArrayList<List<Map<String, String>>>(); // the form contains pages
formDefns.put(formName, pages);
NodeList pl = nd.getChildNodes();
int lenpg = pl.getLength();
for (int j = 0; j < lenpg; j++)
{
Node npg = pl.item(j);
// process each page definition
if (npg.getNodeName().equals("page"))
{
String pgNum = getAttribute(npg, "number");
if (pgNum == null)
{
throw new SAXException("Form " + formName + " has no identified pages");
}
List<Map<String, String>> page = new ArrayList<Map<String, String>>();
pages.add(page);
NodeList flds = npg.getChildNodes();
int lenflds = flds.getLength();
for (int k = 0; k < lenflds; k++)
{
Node nfld = flds.item(k);
if ( nfld.getNodeName().equals("field") )
{
// process each field definition
Map<String, String> field = new HashMap<String, String>();
page.add(field);
processPageParts(formName, pgNum, nfld, field);
// we omit the duplicate validation, allowing multiple fields definition for
// the same metadata and different visibility/type-bind
}
}
} // ignore any child that is not a 'page'
}
// sanity check number of pages
if (pages.size() < 1)
{
throw new DCInputsReaderException("Form " + formName + " has no pages");
}
}
}
if (numForms == 0)
{
throw new DCInputsReaderException("No form definition found");
throw new DCInputsReaderException("No form definition found");
}
}
@@ -368,86 +371,86 @@ public class DCInputsReader
int len = nl.getLength();
for (int i = 0; i < len; i++)
{
Node nd = nl.item(i);
if ( ! isEmptyTextNode(nd) )
Node nd = nl.item(i);
if ( ! isEmptyTextNode(nd) )
{
String tagName = nd.getNodeName();
String value = getValue(nd);
field.put(tagName, value);
if (tagName.equals("input-type"))
{
String tagName = nd.getNodeName();
String value = getValue(nd);
field.put(tagName, value);
if (tagName.equals("input-type"))
if (value.equals("dropdown")
|| value.equals("qualdrop_value")
|| value.equals("list"))
{
String pairTypeName = getAttribute(nd, PAIR_TYPE_NAME);
if (pairTypeName == null)
{
if (value.equals("dropdown")
|| value.equals("qualdrop_value")
|| value.equals("list"))
{
String pairTypeName = getAttribute(nd, PAIR_TYPE_NAME);
if (pairTypeName == null)
{
throw new SAXException("Form " + formName + ", field " +
field.get("dc-element") +
"." + field.get("dc-qualifier") +
" has no name attribute");
}
else
{
field.put(PAIR_TYPE_NAME, pairTypeName);
}
}
throw new SAXException("Form " + formName + ", field " +
field.get("dc-element") +
"." + field.get("dc-qualifier") +
" has no name attribute");
}
else if (tagName.equals("vocabulary"))
else
{
String closedVocabularyString = getAttribute(nd, "closed");
field.put("closedVocabulary", closedVocabularyString);
}
else if (tagName.equals("language"))
{
if (Boolean.valueOf(value))
{
String pairTypeName = getAttribute(nd, PAIR_TYPE_NAME);
if (pairTypeName == null)
{
throw new SAXException("Form " + formName + ", field " +
field.get("dc-element") +
"." + field.get("dc-qualifier") +
" has no language attribute");
}
else
{
field.put(PAIR_TYPE_NAME, pairTypeName);
}
}
field.put(PAIR_TYPE_NAME, pairTypeName);
}
}
}
else if (tagName.equals("vocabulary"))
{
String closedVocabularyString = getAttribute(nd, "closed");
field.put("closedVocabulary", closedVocabularyString);
}
else if (tagName.equals("language"))
{
if (Boolean.valueOf(value))
{
String pairTypeName = getAttribute(nd, PAIR_TYPE_NAME);
if (pairTypeName == null)
{
throw new SAXException("Form " + formName + ", field " +
field.get("dc-element") +
"." + field.get("dc-qualifier") +
" has no language attribute");
}
else
{
field.put(PAIR_TYPE_NAME, pairTypeName);
}
}
}
}
}
String missing = null;
if (field.get("dc-element") == null)
{
missing = "dc-element";
missing = "dc-element";
}
if (field.get("label") == null)
{
missing = "label";
missing = "label";
}
if (field.get("input-type") == null)
{
missing = "input-type";
missing = "input-type";
}
if ( missing != null )
{
String msg = "Required field " + missing + " missing on page " + page + " of form " + formName;
throw new SAXException(msg);
String msg = "Required field " + missing + " missing on page " + page + " of form " + formName;
throw new SAXException(msg);
}
String type = field.get("input-type");
if (type.equals("twobox") || type.equals("qualdrop_value"))
{
String rpt = field.get("repeatable");
if ((rpt == null) ||
((!rpt.equalsIgnoreCase("yes")) &&
(!rpt.equalsIgnoreCase("true"))))
{
String msg = "The field \'"+field.get("label")+"\' must be repeatable";
throw new SAXException(msg);
}
String rpt = field.get("repeatable");
if ((rpt == null) ||
((!rpt.equalsIgnoreCase("yes")) &&
(!rpt.equalsIgnoreCase("true"))))
{
String msg = "The field \'"+field.get("label")+"\' must be repeatable";
throw new SAXException(msg);
}
}
}
@@ -526,63 +529,62 @@ public class DCInputsReader
* in the passed in hashmap.
*/
private void processValuePairs(Node e)
throws SAXException
throws SAXException
{
NodeList nl = e.getChildNodes();
int len = nl.getLength();
for (int i = 0; i < len; i++)
{
Node nd = nl.item(i);
String tagName = nd.getNodeName();
Node nd = nl.item(i);
String tagName = nd.getNodeName();
// process each value-pairs set
if (tagName.equals("value-pairs"))
// process each value-pairs set
if (tagName.equals("value-pairs"))
{
String pairsName = getAttribute(nd, PAIR_TYPE_NAME);
String dcTerm = getAttribute(nd, "dc-term");
if (pairsName == null)
{
String errString =
"Missing name attribute for value-pairs for DC term " + dcTerm;
throw new SAXException(errString);
}
List<String> pairs = new ArrayList<String>();
valuePairs.put(pairsName, pairs);
NodeList cl = nd.getChildNodes();
int lench = cl.getLength();
for (int j = 0; j < lench; j++)
{
Node nch = cl.item(j);
String display = null;
String storage = null;
if (nch.getNodeName().equals("pair"))
{
String pairsName = getAttribute(nd, PAIR_TYPE_NAME);
String dcTerm = getAttribute(nd, "dc-term");
if (pairsName == null)
NodeList pl = nch.getChildNodes();
int plen = pl.getLength();
for (int k = 0; k < plen; k++)
{
String errString =
"Missing name attribute for value-pairs for DC term " + dcTerm;
throw new SAXException(errString);
}
List<String> pairs = new ArrayList<String>();
valuePairs.put(pairsName, pairs);
NodeList cl = nd.getChildNodes();
int lench = cl.getLength();
for (int j = 0; j < lench; j++)
{
Node nch = cl.item(j);
String display = null;
String storage = null;
if (nch.getNodeName().equals("pair"))
Node vn= pl.item(k);
String vName = vn.getNodeName();
if (vName.equals("displayed-value"))
{
display = getValue(vn);
}
else if (vName.equals("stored-value"))
{
storage = getValue(vn);
if (storage == null)
{
NodeList pl = nch.getChildNodes();
int plen = pl.getLength();
for (int k = 0; k < plen; k++)
{
Node vn= pl.item(k);
String vName = vn.getNodeName();
if (vName.equals("displayed-value"))
{
display = getValue(vn);
}
else if (vName.equals("stored-value"))
{
storage = getValue(vn);
if (storage == null)
{
storage = "";
}
} // ignore any children that aren't 'display' or 'storage'
}
pairs.add(display);
pairs.add(storage);
} // ignore any children that aren't a 'pair'
storage = "";
}
} // ignore any children that aren't 'display' or 'storage'
}
} // ignore any children that aren't a 'value-pair'
pairs.add(display);
pairs.add(storage);
} // ignore any children that aren't a 'pair'
}
} // ignore any children that aren't a 'value-pair'
}
}
@@ -595,40 +597,39 @@ public class DCInputsReader
*/
private void checkValues()
throws DCInputsReaderException
throws DCInputsReaderException
{
// Step through every field of every page of every form
Iterator<String> ki = formDefns.keySet().iterator();
while (ki.hasNext())
{
String idName = ki.next();
List<List<Map<String, String>>> pages = formDefns.get(idName);
for (int i = 0; i < pages.size(); i++)
String idName = ki.next();
List<List<Map<String, String>>> pages = formDefns.get(idName);
for (int i = 0; i < pages.size(); i++)
{
List<Map<String, String>> page = pages.get(i);
for (int j = 0; j < page.size(); j++)
{
List<Map<String, String>> page = pages.get(i);
for (int j = 0; j < page.size(); j++)
{
Map<String, String> fld = page.get(j);
// verify reference in certain input types
String type = fld.get("input-type");
Map<String, String> fld = page.get(j);
// verify reference in certain input types
String type = fld.get("input-type");
if (type.equals("dropdown")
|| type.equals("qualdrop_value")
|| type.equals("list"))
{
String pairsName = fld.get(PAIR_TYPE_NAME);
List<String> v = valuePairs.get(pairsName);
if (v == null)
{
String errString = "Cannot find value pairs for " + pairsName;
throw new DCInputsReaderException(errString);
}
}
// we omit the "required" and "visibility" validation, provided this must be checked in the processing class
// only when it makes sense (if the field isn't visible means that it is not applicable, therefore it can't be required)
|| type.equals("qualdrop_value")
|| type.equals("list"))
{
String pairsName = fld.get(PAIR_TYPE_NAME);
List<String> v = valuePairs.get(pairsName);
if (v == null)
{
String errString = "Cannot find value pairs for " + pairsName;
throw new DCInputsReaderException(errString);
}
}
// we omit the "required" and "visibility" validation, provided this must be checked in the processing class
// only when it makes sense (if the field isn't visible means that it is not applicable, therefore it can't be required)
}
}
}
}
@@ -652,11 +653,11 @@ public class DCInputsReader
boolean isEmpty = false;
if (nd.getNodeType() == Node.TEXT_NODE)
{
String text = nd.getNodeValue().trim();
if (text.length() == 0)
{
isEmpty = true;
}
String text = nd.getNodeValue().trim();
if (text.length() == 0)
{
isEmpty = true;
}
}
return isEmpty;
}
@@ -670,15 +671,15 @@ public class DCInputsReader
int len = attrs.getLength();
if (len > 0)
{
int i;
for (i = 0; i < len; i++)
int i;
for (i = 0; i < len; i++)
{
Node attr = attrs.item(i);
if (name.equals(attr.getNodeName()))
{
Node attr = attrs.item(i);
if (name.equals(attr.getNodeName()))
{
return attr.getNodeValue().trim();
}
return attr.getNodeValue().trim();
}
}
}
//no such attribute
return null;
@@ -694,12 +695,12 @@ public class DCInputsReader
int len = nl.getLength();
for (int i = 0; i < len; i++)
{
Node n = nl.item(i);
short type = n.getNodeType();
if (type == Node.TEXT_NODE)
{
return n.getNodeValue().trim();
}
Node n = nl.item(i);
short type = n.getNodeType();
if (type == Node.TEXT_NODE)
{
return n.getNodeValue().trim();
}
}
// Didn't find a text node
return null;

View File

@@ -30,6 +30,7 @@ public class DSpaceContextListener implements ServletContextListener
/**
* Initialize any resources required by the application.
* @param event
* This is the event class for notifications about changes to the servlet context of a web application.
*/
@Override
public void contextInitialized(ServletContextEvent event)
@@ -63,6 +64,7 @@ public class DSpaceContextListener implements ServletContextListener
* Clean up resources used by the application when stopped
*
* @param event
8 Event class for notifications about changes to the servlet context of a web application.
*/
@Override
public void contextDestroyed(ServletContextEvent event)

View File

@@ -229,6 +229,7 @@ public class GoogleMetadata
* first-encountered instance of the field for this Item.
*
* @param fieldName
* metadata field name
* @return successful?
*/
protected boolean addSingleField(String fieldName)
@@ -262,7 +263,7 @@ public class GoogleMetadata
if (config.equals("$simple-pdf"))
{
String pdf_url = getPDFSimpleUrl(item);
if(pdf_url.length() > 0)
if (pdf_url.length() > 0)
{
metadataMappings.put(fieldName, pdf_url);
return true;
@@ -291,6 +292,7 @@ public class GoogleMetadata
* instead of an aggregate.
*
* @param configFilter
* list of DC metadata fields separated by "|" characters
* @return The first configured match of metadata field for the item.
*/
protected MetadataValue resolveMetadataField(String configFilter)
@@ -309,6 +311,7 @@ public class GoogleMetadata
* A plural version of resolveMetadata for aggregate fields.
*
* @param configFilter
* list of DC metadata fields separated by "|" characters
* @return Aggregate of all matching metadata fields configured in the first
* option field-set to return any number of filter matches.
*/
@@ -328,7 +331,9 @@ public class GoogleMetadata
* configuration filter.
*
* @param configFilter
* list of DC metadata fields separated by "|" characters
* @param returnType
* GoogleMetadata.SINGLE / GoogleMetadata.MULTI / GoogleMetadata.ALL_FIELDS_IN_OPTION
* @return Array of configuration to item-field matches
*/
protected ArrayList<MetadataValue> resolveMetadata(String configFilter,
@@ -350,8 +355,7 @@ public class GoogleMetadata
if (log.isDebugEnabled())
{
log
.debug("Resolved Fields For This Item Per Configuration Filter:");
log.debug("Resolved Fields For This Item Per Configuration Filter:");
for (int i = 0; i < parsedOptions.size(); i++)
{
ArrayList<String> optionFields = parsedOptions.get(i);
@@ -445,6 +449,7 @@ public class GoogleMetadata
* configuration.
*
* @param configFilter
* list of DC metadata fields separated by "|" characters
* @return array of parsed options or null
*/
protected ArrayList<ArrayList<String>> parseOptions(String configFilter)
@@ -720,7 +725,7 @@ public class GoogleMetadata
// Dissertations
if (itemIsDissertation())
{
if(log.isDebugEnabled()) {
if (log.isDebugEnabled()) {
log.debug("ITEM TYPE: DISSERTATION");
}
@@ -731,7 +736,7 @@ public class GoogleMetadata
// Patents
if (itemIsPatent())
{
if(log.isDebugEnabled()) {
if (log.isDebugEnabled()) {
log.debug("ITEM TYPE: PATENT");
}
@@ -750,7 +755,7 @@ public class GoogleMetadata
// Tech Reports
if (itemIsTechReport())
{
if(log.isDebugEnabled()) {
if (log.isDebugEnabled()) {
log.debug("ITEM TYPE: TECH REPORT");
}
addSingleField(TECH_REPORT_NUMBER);
@@ -758,7 +763,7 @@ public class GoogleMetadata
}
if(!itemIsDissertation() && !itemIsTechReport()) {
if (!itemIsDissertation() && !itemIsTechReport()) {
// PUBLISHER
addSingleField(PUBLISHER);
}
@@ -1004,31 +1009,31 @@ public class GoogleMetadata
* is in the default content bundle, and that the item only has one public bitstream
* and it is a PDF.
*
* @param item
* @param item item to get PDF URL from
* @return URL that the PDF can be directly downloaded from
*/
protected String getPDFSimpleUrl(Item item)
{
try {
Bitstream bitstream = findLinkableFulltext(item);
if (bitstream != null) {
StringBuilder path = new StringBuilder();
path.append(ConfigurationManager.getProperty("dspace.url"));
Bitstream bitstream = findLinkableFulltext(item);
if (bitstream != null) {
StringBuilder path = new StringBuilder();
path.append(ConfigurationManager.getProperty("dspace.url"));
if (item.getHandle() != null) {
path.append("/bitstream/");
path.append(item.getHandle());
path.append("/");
path.append(bitstream.getSequenceID());
} else {
path.append("/retrieve/");
path.append(bitstream.getID());
}
if (item.getHandle() != null) {
path.append("/bitstream/");
path.append(item.getHandle());
path.append("/");
path.append(bitstream.getSequenceID());
} else {
path.append("/retrieve/");
path.append(bitstream.getID());
}
path.append("/");
path.append(Util.encodeBitstreamName(bitstream.getName(), Constants.DEFAULT_ENCODING));
return path.toString();
}
path.append("/");
path.append(Util.encodeBitstreamName(bitstream.getName(), Constants.DEFAULT_ENCODING));
return path.toString();
}
} catch (UnsupportedEncodingException ex) {
log.debug(ex.getMessage());
} catch (SQLException ex) {
@@ -1038,22 +1043,24 @@ public class GoogleMetadata
return "";
}
/**
* A bitstream is considered linkable fulltext when it is either
* <ul>
* <li>the item's only bitstream (in the ORIGINAL bundle); or</li>
* <li>the primary bitstream</li>
* </ul>
* Additionally, this bitstream must be publicly viewable.
* @param item
* @return a linkable bitstream or null if none found
* @throws SQLException if database error
*/
protected Bitstream findLinkableFulltext(Item item) throws SQLException {
Bitstream bestSoFar = null;
int bitstreamCount = 0;
List<Bundle> contentBundles = itemService.getBundles(item, "ORIGINAL");
for (Bundle bundle : contentBundles) {
/**
* A bitstream is considered linkable fulltext when it is either
* <ul>
* <li>the item's only bitstream (in the ORIGINAL bundle); or</li>
* <li>the primary bitstream</li>
* </ul>
* Additionally, this bitstream must be publicly viewable.
*
* @param item
* bitstream's parent item
* @return a linkable bitstream or null if none found
* @throws SQLException if database error
*/
protected Bitstream findLinkableFulltext(Item item) throws SQLException {
Bitstream bestSoFar = null;
int bitstreamCount = 0;
List<Bundle> contentBundles = itemService.getBundles(item, "ORIGINAL");
for (Bundle bundle : contentBundles) {
List<Bitstream> bitstreams = bundle.getBitstreams();
for (Bitstream candidate : bitstreams) {
if (candidate.equals(bundle.getPrimaryBitstream())) { // is primary -> use this one
@@ -1068,25 +1075,32 @@ public class GoogleMetadata
}
}
return bestSoFar;
}
return bestSoFar;
}
protected boolean isPublic(Bitstream bitstream) {
if (bitstream == null) {
return false;
}
boolean result = false;
Context context = null;
try {
context = new Context();
result = AuthorizeServiceFactory.getInstance().getAuthorizeService().authorizeActionBoolean(context, bitstream, Constants.READ, true);
} catch (SQLException e) {
log.error("Cannot determine whether bitstream is public, assuming it isn't. bitstream_id=" + bitstream.getID(), e);
}
return result;
}
/**
* Find out whether bitstream is readable by the public.
*
* @param bitstream
* the target bitstream
* @return whether bitstream is readable by the Anonymous group
*/
protected boolean isPublic(Bitstream bitstream) {
if (bitstream == null) {
return false;
}
boolean result = false;
Context context = null;
try {
context = new Context();
result = AuthorizeServiceFactory.getInstance().getAuthorizeService().authorizeActionBoolean(context, bitstream, Constants.READ, true);
} catch (SQLException e) {
log.error("Cannot determine whether bitstream is public, assuming it isn't. bitstream_id=" + bitstream.getID(), e);
}
return result;
}
/**
/**
*
*
* @param field
@@ -1122,6 +1136,7 @@ public class GoogleMetadata
/**
* If metadata field contains multiple values, then add each value to the map separately
* @param FIELD
* metadata field
*/
protected void addMultipleValues(String FIELD)
{
@@ -1201,6 +1216,7 @@ public class GoogleMetadata
* metadata practice.
*
* @param dConfig
* configured fields (from google-metadata.properties)
* @return item matches configuration
*/
protected boolean identifyItemType(String dConfig)
@@ -1223,7 +1239,7 @@ public class GoogleMetadata
if (mdPairs.containsKey(parsedPair[0].trim()))
{
mdPairs.get(parsedPair[0].trim()).add(parsedPair[1]);
if(log.isDebugEnabled()) {
if (log.isDebugEnabled()) {
log.debug("Registering Type Identifier: " + parsedPair[0] + " => " + parsedPair[1]);
}
}

View File

@@ -85,50 +85,50 @@ public class OpenSearchServiceImpl implements OpenSearchService, InitializingBea
public void afterPropertiesSet() throws Exception
{
ConfigurationService config = DSpaceServicesFactory.getInstance().getConfigurationService();
enabled = config.getBooleanProperty("websvc.opensearch.enable");
enabled = config.getBooleanProperty("websvc.opensearch.enable");
svcUrl = config.getProperty("dspace.url") + "/" +
config.getProperty("websvc.opensearch.svccontext");
uiUrl = config.getProperty("dspace.url") + "/" +
config.getProperty("websvc.opensearch.uicontext");
// read rest of config info if enabled
formats = new ArrayList<String>();
if (enabled)
{
String[] fmts = config.getArrayProperty("websvc.opensearch.formats");
// read rest of config info if enabled
formats = new ArrayList<String>();
if (enabled)
{
String[] fmts = config.getArrayProperty("websvc.opensearch.formats");
formats = Arrays.asList(fmts);
}
}
}
@Override
public List<String> getFormats()
{
return formats;
return formats;
}
@Override
public String getContentType(String format)
{
return "html".equals(format) ? "text/html" :
"application/" + format + "+xml; charset=UTF-8";
return "html".equals(format) ? "text/html" :
"application/" + format + "+xml; charset=UTF-8";
}
@Override
public Document getDescriptionDoc(String scope) throws IOException
{
return jDomToW3(getServiceDocument(scope));
return jDomToW3(getServiceDocument(scope));
}
@Override
public String getDescription(String scope)
{
return new XMLOutputter().outputString(getServiceDocument(scope));
return new XMLOutputter().outputString(getServiceDocument(scope));
}
@Override
public String getResultsString(Context context, String format, String query, int totalResults, int start, int pageSize,
DSpaceObject scope, List<DSpaceObject> results,
Map<String, String> labels) throws IOException
DSpaceObject scope, List<DSpaceObject> results,
Map<String, String> labels) throws IOException
{
try
{
@@ -137,13 +137,13 @@ public class OpenSearchServiceImpl implements OpenSearchService, InitializingBea
catch (FeedException e)
{
log.error(e.toString(), e);
throw new IOException("Unable to generate feed", e);
throw new IOException("Unable to generate feed", e);
}
}
@Override
public Document getResultsDoc(Context context, String format, String query, int totalResults, int start, int pageSize,
DSpaceObject scope, List<DSpaceObject> results, Map<String, String> labels)
DSpaceObject scope, List<DSpaceObject> results, Map<String, String> labels)
throws IOException
{
try
@@ -169,13 +169,13 @@ public class OpenSearchServiceImpl implements OpenSearchService, InitializingBea
{
format = "atom_1.0";
}
SyndicationFeed feed = new SyndicationFeed(labels.get(SyndicationFeed.MSG_UITYPE));
feed.populate(null, context, scope, results, labels);
feed.setType(format);
feed.addModule(openSearchMarkup(query, totalResults, start, pageSize));
return feed;
}
return feed;
}
/*
* Generates the OpenSearch elements which are added to the RSS or Atom feeds as foreign markup
@@ -187,17 +187,17 @@ public class OpenSearchServiceImpl implements OpenSearchService, InitializingBea
*/
protected OpenSearchModule openSearchMarkup(String query, int totalResults, int start, int pageSize)
{
OpenSearchModule osMod = new OpenSearchModuleImpl();
osMod.setTotalResults(totalResults);
osMod.setStartIndex(start);
osMod.setItemsPerPage(pageSize);
OSQuery osq = new OSQuery();
osq.setRole("request");
OpenSearchModule osMod = new OpenSearchModuleImpl();
osMod.setTotalResults(totalResults);
osMod.setStartIndex(start);
osMod.setItemsPerPage(pageSize);
OSQuery osq = new OSQuery();
osq.setRole("request");
try
{
osq.setSearchTerms(URLEncoder.encode(query, "UTF-8"));
}
catch(UnsupportedEncodingException e)
catch (UnsupportedEncodingException e)
{
log.error(e);
}
@@ -216,7 +216,7 @@ public class OpenSearchServiceImpl implements OpenSearchService, InitializingBea
{
ConfigurationService config = DSpaceServicesFactory.getInstance().getConfigurationService();
Namespace ns = Namespace.getNamespace(osNs);
Namespace ns = Namespace.getNamespace(osNs);
Element root = new Element("OpenSearchDescription", ns);
root.addContent(new Element("ShortName", ns).setText(config.getProperty("websvc.opensearch.shortname")));
root.addContent(new Element("LongName", ns).setText(config.getProperty("websvc.opensearch.longname")));
@@ -227,61 +227,63 @@ public class OpenSearchServiceImpl implements OpenSearchService, InitializingBea
String sample = config.getProperty("websvc.opensearch.samplequery");
if (sample != null && sample.length() > 0)
{
Element sq = new Element("Query", ns).setAttribute("role", "example");
root.addContent(sq.setAttribute("searchTerms", sample));
Element sq = new Element("Query", ns).setAttribute("role", "example");
root.addContent(sq.setAttribute("searchTerms", sample));
}
String tags = config.getProperty("websvc.opensearch.tags");
if (tags != null && tags.length() > 0)
{
root.addContent(new Element("Tags", ns).setText(tags));
root.addContent(new Element("Tags", ns).setText(tags));
}
String contact = config.getProperty("mail.admin");
if (contact != null && contact.length() > 0)
{
root.addContent(new Element("Contact", ns).setText(contact));
root.addContent(new Element("Contact", ns).setText(contact));
}
String faviconUrl = config.getProperty("websvc.opensearch.faviconurl");
if (faviconUrl != null && faviconUrl.length() > 0)
{
String dim = String.valueOf(16);
String type = faviconUrl.endsWith("ico") ? "image/vnd.microsoft.icon" : "image/png";
Element fav = new Element("Image", ns).setAttribute("height", dim).setAttribute("width", dim).
setAttribute("type", type).setText(faviconUrl);
root.addContent(fav);
String dim = String.valueOf(16);
String type = faviconUrl.endsWith("ico") ? "image/vnd.microsoft.icon" : "image/png";
Element fav = new Element("Image", ns).setAttribute("height", dim).setAttribute("width", dim).
setAttribute("type", type).setText(faviconUrl);
root.addContent(fav);
}
// service URLs
for (String format : formats)
{
Element url = new Element("Url", ns).setAttribute("type", getContentType(format));
StringBuilder template = new StringBuilder();
if ("html".equals(format))
{
template.append(uiUrl);
}
else
{
template.append(svcUrl);
}
Element url = new Element("Url", ns).setAttribute("type", getContentType(format));
StringBuilder template = new StringBuilder();
if ("html".equals(format))
{
template.append(uiUrl);
}
else
{
template.append(svcUrl);
}
template.append("?query={searchTerms}");
if(! "html".equals(format))
{
template.append("&start={startIndex?}&rpp={count?}&format=");
template.append(format);
}
if (scope != null)
{
template.append("&scope=");
template.append(scope);
}
url.setAttribute("template", template.toString());
root.addContent(url);
if(! "html".equals(format))
{
template.append("&start={startIndex?}&rpp={count?}&format=");
template.append(format);
}
if (scope != null)
{
template.append("&scope=");
template.append(scope);
}
url.setAttribute("template", template.toString());
root.addContent(url);
}
return new org.jdom.Document(root);
}
/**
* Converts a JDOM document to a W3C one
*
* @param jdomDoc
* jDOM document to convert
* @return W3C Document object
* @throws IOException if IO error
*/
@@ -290,11 +292,11 @@ public class OpenSearchServiceImpl implements OpenSearchService, InitializingBea
DOMOutputter domOut = new DOMOutputter();
try
{
return domOut.output(jdomDoc);
return domOut.output(jdomDoc);
}
catch(JDOMException jde)
catch (JDOMException jde)
{
throw new IOException("JDOM output exception", jde);
throw new IOException("JDOM output exception", jde);
}
}

View File

@@ -39,7 +39,7 @@ public class SubmissionStepConfig implements Serializable
/**
* the id for this step ('id' only exists if this step is defined in the
* <step-definitions> section)
* &lt;step-definitions&gt; section)
*/
private String id = null;

View File

@@ -13,13 +13,15 @@ import java.net.Inet6Address;
import java.net.UnknownHostException;
/**
* <p>
* Quickly tests whether a given IP address matches an IP range. An
* {@code IPMatcher} is initialized with a particular IP range specification.
* Calls to {@link IPMatcher#match(String) match} method will then quickly
* determine whether a given IP falls within that range.
* </p>
* <p>
* Supported range specifications are:
* <p>
* </p>
* <ul>
* <li>Full IPv4 address, e.g. {@code 12.34.56.78}</li>
* <li>Full IPv6 address, e.g. {@code 2001:18e8:3:171:218:8bff:fe2a:56a4}</li>
@@ -32,7 +34,7 @@ import java.net.UnknownHostException;
*
* @version $Revision$
* @author Robert Tansley
* @author Ben Bosman
* @author Ben Bosman
* @author Roeland Dillen
*/
public class IPMatcher

View File

@@ -37,6 +37,7 @@ public class AuthorizeException extends Exception
* create an exception with only a message
*
* @param message
* Exception message
*/
public AuthorizeException(String message)
{

View File

@@ -92,7 +92,7 @@ public class AuthorizeServiceImpl implements AuthorizeService
@Override
public void authorizeAction(Context c, DSpaceObject o, int action, boolean useInheritance) throws AuthorizeException, SQLException
{
authorizeAction(c, c.getCurrentUser(), o, action, useInheritance);
authorizeAction(c, c.getCurrentUser(), o, action, useInheritance);
}
@Override
@@ -538,12 +538,12 @@ public class AuthorizeServiceImpl implements AuthorizeService
@Override
public void switchPoliciesAction(Context context, DSpaceObject dso, int fromAction, int toAction) throws SQLException, AuthorizeException {
List<ResourcePolicy> rps = getPoliciesActionFilter(context, dso, fromAction);
List<ResourcePolicy> rps = getPoliciesActionFilter(context, dso, fromAction);
for (ResourcePolicy rp : rps) {
rp.setAction(toAction);
rp.setAction(toAction);
}
resourcePolicyService.update(context, rps);
}
}
@Override
public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest)
@@ -624,7 +624,7 @@ public class AuthorizeServiceImpl implements AuthorizeService
List<Group> groups = new ArrayList<Group>();
for (ResourcePolicy resourcePolicy : policies) {
if(resourcePolicy.getGroup() != null)
if (resourcePolicy.getGroup() != null)
{
groups.add(resourcePolicy.getGroup());
}
@@ -653,7 +653,7 @@ public class AuthorizeServiceImpl implements AuthorizeService
if (CollectionUtils.isNotEmpty(policies))
{
return policies.iterator().next();
}else{
} else {
return null;
}
}
@@ -664,16 +664,22 @@ public class AuthorizeServiceImpl implements AuthorizeService
* have right on the collection. E.g., if the anonymous can access the collection policies are assigned to anonymous.
*
* @param context
* The relevant DSpace Context.
* @param embargoDate
* embargo end date
* @param reason
* embargo reason
* @param dso
* DSpace object
* @param owningCollection
* collection to get group policies from
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
*/
@Override
public void generateAutomaticPolicies(Context context, Date embargoDate,
String reason, DSpaceObject dso, Collection owningCollection) throws SQLException, AuthorizeException
String reason, DSpaceObject dso, Collection owningCollection)
throws SQLException, AuthorizeException
{
if (embargoDate != null || (embargoDate == null && dso instanceof Bitstream))
@@ -714,7 +720,7 @@ public class AuthorizeServiceImpl implements AuthorizeService
@Override
public ResourcePolicy createResourcePolicy(Context context, DSpaceObject dso, Group group, EPerson eperson, int type, String rpType) throws SQLException, AuthorizeException {
if(group == null && eperson == null)
if (group == null && eperson == null)
{
throw new IllegalArgumentException("We need at least an eperson or a group in order to create a resource policy.");
}

View File

@@ -34,7 +34,8 @@ public class FixDefaultPolicies
{
/**
* Command line interface to setPolicies - run to see arguments
* @param argv arguments
*
* @param argv the command line arguments given
* @throws Exception if error
*/
public static void main(String[] argv) throws Exception

View File

@@ -43,7 +43,8 @@ public class PolicySet
/**
* Command line interface to setPolicies - run to see arguments
* @param argv arguments
*
* @param argv the command line arguments given
* @throws Exception if error
*/
public static void main(String[] argv) throws Exception
@@ -130,17 +131,30 @@ public class PolicySet
/**
*
* @param c
* current context
* @param containerType
* type, Constants.ITEM or Constants.COLLECTION
* @param containerID
* ID of container (DB primary key)
* @param contentType
* ID of container (DB primary key)
* @param actionID
* action ID (e.g. Constants.READ)
* @param groupID
* group ID (database key)
* @param isReplace
* if <code>true</code>, existing policies are removed first,
* otherwise add to existing policies
* @param clearOnly
* if non-null, only process bitstreams whose names contain filter
* @param name
* policy name
* @param description
* policy descrption
* @param startDate
* policy start date
* @param endDate
* policy end date
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
*/
@@ -166,7 +180,7 @@ public class PolicySet
* @param contentType
* type (BUNDLE, ITEM, or BITSTREAM)
* @param actionID
* action ID
* action ID (e.g. Constants.READ)
* @param groupID
* group ID (database key)
* @param isReplace
@@ -214,9 +228,13 @@ public class PolicySet
* @param filter
* if non-null, only process bitstreams whose names contain filter
* @param name
* policy name
* @param description
* policy description
* @param startDate
* policy start date
* @param endDate
* policy end date
* @throws SQLException if database error
* if database problem
* @throws AuthorizeException if authorization error
@@ -250,7 +268,7 @@ public class PolicySet
{
// before create a new policy check if an identical policy is already in place
if(!authorizeService.isAnIdenticalPolicyAlreadyInPlace(c, myitem, group, actionID, -1)){
if (!authorizeService.isAnIdenticalPolicyAlreadyInPlace(c, myitem, group, actionID, -1)) {
// now add the policy
ResourcePolicy rp = resourcePolicyService.create(c);

View File

@@ -96,6 +96,7 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
* Return true if this object equals obj, false otherwise.
*
* @param obj
* object to compare (eperson, group, start date, end date, ...)
* @return true if ResourcePolicy objects are equal
*/
@Override
@@ -144,23 +145,22 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
{
int hash = 7;
hash = 19 * hash + this.getAction();
if(this.getGroup() != null)
if (this.getGroup() != null)
{
hash = 19 * hash + this.getGroup().hashCode();
}else{
} else {
hash = 19 * hash + -1;
}
if(this.getEPerson() != null)
if (this.getEPerson() != null)
{
hash = 19 * hash + this.getEPerson().hashCode();
}else{
} else {
hash = 19 * hash + -1;
}
hash = 19 * hash + (this.getStartDate() != null? this.getStartDate().hashCode():0);
hash = 19 * hash + (this.getEndDate() != null? this.getEndDate().hashCode():0);
hash = 19 * hash + (this.getStartDate() != null ? this.getStartDate().hashCode() : 0);
hash = 19 * hash + (this.getEndDate() != null ? this.getEndDate().hashCode() : 0);
return hash;
}
@@ -185,7 +185,7 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
/**
* set the action this policy authorizes
*
* @param myid action ID from <code>org.dspace.core.Constants</code>
* @param myid action ID from {@link org.dspace.core.Constants#Constants Constants}
*/
public void setAction(int myid)
{
@@ -279,24 +279,24 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
this.endDate = d;
}
public String getRpName(){
public String getRpName() {
return rpname;
}
public void setRpName(String name){
public void setRpName(String name) {
this.rpname = name;
}
public String getRpType(){
public String getRpType() {
return rptype;
}
public void setRpType(String type){
public void setRpType(String type) {
this.rptype = type;
}
public String getRpDescription(){
public String getRpDescription() {
return rpdescription;
}
public void setRpDescription(String description){
public void setRpDescription(String description) {
this.rpdescription = description;
}
}

View File

@@ -44,10 +44,11 @@ public interface AuthorizeService {
* @param c context with the current user
* @param o DSpace object user is attempting to perform action on
* @param actions array of action IDs from
* <code>org.dspace.core.Constants</code>
* <code>org.dspace.core.Constants</code>
* @throws AuthorizeException if any one of the specified actions cannot be
* performed by the current user on the given object.
* @throws SQLException if database error
* performed by the current user on the given object.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public void authorizeAnyOf(Context c, DSpaceObject o, int[] actions) throws AuthorizeException, SQLException;
@@ -59,8 +60,11 @@ public interface AuthorizeService {
* @param c context
* @param o a DSpaceObject
* @param action action to perform from <code>org.dspace.core.Constants</code>
* @throws AuthorizeException if the user is denied
* @throws SQLException if database error
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public void authorizeAction(Context c, DSpaceObject o, int action) throws AuthorizeException, SQLException;
@@ -75,8 +79,11 @@ public interface AuthorizeService {
* flag to say if ADMIN action on the current object or parent
* object can be used
* @param action action to perform from <code>org.dspace.core.Constants</code>
* @throws AuthorizeException if the user is denied
* @throws SQLException if database error
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public void authorizeAction(Context c, DSpaceObject o, int action, boolean useInheritance)
throws AuthorizeException, SQLException;
@@ -93,8 +100,11 @@ public interface AuthorizeService {
* flag to say if ADMIN action on the current object or parent
* object can be used
* @param action action to perform from <code>org.dspace.core.Constants</code>
* @throws AuthorizeException if the user is denied
* @throws SQLException if database error
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public void authorizeAction(Context c, EPerson e, DSpaceObject o, int action, boolean useInheritance)
throws AuthorizeException, SQLException;
@@ -109,7 +119,8 @@ public interface AuthorizeService {
* <code>org.dspace.core.Constants</code>
* @return {@code true} if the current user in the context is
* authorized to perform the given action on the given object
* @throws SQLException if database error
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public boolean authorizeActionBoolean(Context c, DSpaceObject o, int a) throws SQLException;
@@ -126,7 +137,8 @@ public interface AuthorizeService {
* object can be used
* @return {@code true} if the current user in the context is
* authorized to perform the given action on the given object
* @throws SQLException if database error
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public boolean authorizeActionBoolean(Context c, DSpaceObject o, int a, boolean useInheritance) throws SQLException;
@@ -144,7 +156,8 @@ public interface AuthorizeService {
* object can be used
* @return {@code true} if the requested user is
* authorized to perform the given action on the given object
* @throws SQLException if database error
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public boolean authorizeActionBoolean(Context c, EPerson e, DSpaceObject o, int a, boolean useInheritance) throws SQLException;
@@ -163,7 +176,8 @@ public interface AuthorizeService {
* method
* @return {@code true} if user has administrative privileges on the
* given DSpace object
* @throws SQLException if database error
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public boolean isAdmin(Context c, DSpaceObject o) throws SQLException;
@@ -176,7 +190,8 @@ public interface AuthorizeService {
* @param c current context
* @return {@code true} if user is an admin or ignore authorization
* flag set
* @throws SQLException if database error
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public boolean isAdmin(Context c) throws SQLException;
@@ -432,21 +447,25 @@ public interface AuthorizeService {
public ResourcePolicy createOrModifyPolicy(ResourcePolicy policy, Context context, String name, Group group, EPerson ePerson, Date embargoDate, int action, String reason, DSpaceObject dso) throws AuthorizeException, SQLException;
/**
* Change all the policies related to the action (fromPolicy) of the
* specified object to the new action (toPolicy)
*
* @param context
* @param dso
* the dspace object
* @param fromAction
* the action to change
* @param toAction
* the new action to set
* @throws SQLException
* @throws AuthorizeException
*/
void switchPoliciesAction(Context context, DSpaceObject dso, int fromAction, int toAction)
throws SQLException, AuthorizeException;
/**
* Change all the policies related to the action (fromPolicy) of the
* specified object to the new action (toPolicy)
*
* @param context
* The relevant DSpace Context.
* @param dso
* the dspace object
* @param fromAction
* the action to change
* @param toAction
* the new action to set
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
void switchPoliciesAction(Context context, DSpaceObject dso, int fromAction, int toAction)
throws SQLException, AuthorizeException;
}

View File

@@ -155,6 +155,7 @@ public interface BrowseDAO
* to only items or values within items that appear in the given container.
*
* @param containerID
* community/collection internal ID (UUID)
*/
public void setContainerID(UUID containerID);
@@ -234,7 +235,7 @@ public interface BrowseDAO
* normal browse operations can be completed without it. The default is -1, which
* means do not offset.
*
* @return the offset
* @return paging offset
*/
public int getOffset();
@@ -245,6 +246,7 @@ public interface BrowseDAO
* means do not offset.
*
* @param offset
* paging offset
*/
public void setOffset(int offset);

File diff suppressed because it is too large Load Diff

View File

@@ -67,7 +67,7 @@ public class DailyReportEmailer
public void sendReport(File attachment, int numberOfBitstreams)
throws IOException, javax.mail.MessagingException
{
if(numberOfBitstreams > 0)
if (numberOfBitstreams > 0)
{
String hostname = ConfigurationManager.getProperty("dspace.hostname");
Email email = new Email();
@@ -83,22 +83,22 @@ public class DailyReportEmailer
* Allows users to have email sent to them. The default is to send all
* reports in one email
*
* @param args
* <dl>
* <dt>-h</dt>
* <dd>help</dd>
* <dt>-d</dt>
* <dd>Select deleted bitstreams</dd>
* <dt>-m</dt>
* <dd>Bitstreams missing from assetstore</dd>
* <dt>-c</dt>
* <dd>Bitstreams whose checksums were changed</dd>
* <dt>-n</dt>
* <dd>Bitstreams whose checksums were changed</dd>
* <dt>-a</dt>
* <dd>Send all reports in one email</dd>
* </dl>
* <dl>
* <dt>-h</dt>
* <dd>help</dd>
* <dt>-d</dt>
* <dd>Select deleted bitstreams</dd>
* <dt>-m</dt>
* <dd>Bitstreams missing from assetstore</dd>
* <dt>-c</dt>
* <dd>Bitstreams whose checksums were changed</dd>
* <dt>-n</dt>
* <dd>Bitstreams whose checksums were changed</dd>
* <dt>-a</dt>
* <dd>Send all reports in one email</dd>
* </dl>
*
* @param args the command line arguments given
*/
public static void main(String[] args)
{
@@ -110,26 +110,18 @@ public class DailyReportEmailer
Options options = new Options();
options.addOption("h", "help", false, "Help");
options
.addOption("d", "Deleted", false,
"Send E-mail report for all bitstreams set as deleted for today");
options
.addOption("m", "Missing", false,
"Send E-mail report for all bitstreams not found in assetstore for today");
options
.addOption(
"c",
"Changed",
false,
"Send E-mail report for all bitstreams where checksum has been changed for today");
options.addOption("a", "All", false, "Send all E-mail reports");
options.addOption("d", "Deleted", false,
"Send E-mail report for all bitstreams set as deleted for today");
options.addOption("m", "Missing", false,
"Send E-mail report for all bitstreams not found in assetstore for today");
options.addOption("c", "Changed", false,
"Send E-mail report for all bitstreams where checksum has been changed for today");
options.addOption("a", "All", false,
"Send all E-mail reports");
options.addOption("u", "Unchecked", false,
"Send the Unchecked bitstream report");
options
.addOption("n", "Not Processed", false,
"Send E-mail report for all bitstreams set to longer be processed for today");
"Send the Unchecked bitstream report");
options.addOption("n", "Not Processed", false,
"Send E-mail report for all bitstreams set to longer be processed for today");
try
{
@@ -147,19 +139,11 @@ public class DailyReportEmailer
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("Checksum Reporter\n", options);
System.out
.println("\nSend Deleted bitstream email report: DailyReportEmailer -d");
System.out
.println("\nSend Missing bitstreams email report: DailyReportEmailer -m");
System.out
.println("\nSend Checksum Changed email report: DailyReportEmailer -c");
System.out
.println("\nSend bitstream not to be processed email report: DailyReportEmailer -n");
System.out
.println("\nSend Un-checked bitstream report: DailyReportEmailer -u");
System.out.println("\nSend Deleted bitstream email report: DailyReportEmailer -d");
System.out.println("\nSend Missing bitstreams email report: DailyReportEmailer -m");
System.out.println("\nSend Checksum Changed email report: DailyReportEmailer -c");
System.out.println("\nSend bitstream not to be processed email report: DailyReportEmailer -n");
System.out.println("\nSend Un-checked bitstream report: DailyReportEmailer -u");
System.out.println("\nSend All email reports: DailyReportEmailer");
System.exit(0);
}
@@ -201,34 +185,24 @@ public class DailyReportEmailer
else
{
throw new IllegalStateException("directory :" + dirLocation
+ " does not exist");
+ " does not exist");
}
writer = new FileWriter(report);
if ((line.hasOption("a")) || (line.getOptions().length == 0))
{
writer
.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
numBitstreams += reporter.getDeletedBitstreamReport(context, yesterday,
tomorrow, writer);
writer
.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
numBitstreams += reporter.getChangedChecksumReport(context, yesterday,
tomorrow, writer);
writer
.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
numBitstreams += reporter.getBitstreamNotFoundReport(context, yesterday,
tomorrow, writer);
writer
.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
numBitstreams += reporter.getNotToBeProcessedReport(context, yesterday,
tomorrow, writer);
writer
.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
writer.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
numBitstreams += reporter.getDeletedBitstreamReport(context, yesterday, tomorrow, writer);
writer.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
numBitstreams += reporter.getChangedChecksumReport(context, yesterday, tomorrow, writer);
writer.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
numBitstreams += reporter.getBitstreamNotFoundReport(context, yesterday, tomorrow, writer);
writer.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
numBitstreams += reporter.getNotToBeProcessedReport(context, yesterday, tomorrow, writer);
writer.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
numBitstreams += reporter.getUncheckedBitstreamsReport(context, writer);
writer
.write("\n--------------------------------- End Report ---------------------------\n\n");
writer.write("\n--------------------------------- End Report ---------------------------\n\n");
writer.flush();
writer.close();
emailer.sendReport(report, numBitstreams);
@@ -237,10 +211,9 @@ public class DailyReportEmailer
{
if (line.hasOption("d"))
{
writer
.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
writer.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
numBitstreams += reporter.getDeletedBitstreamReport(context,
yesterday, tomorrow, writer);
yesterday, tomorrow, writer);
writer.flush();
writer.close();
emailer.sendReport(report, numBitstreams);
@@ -248,10 +221,9 @@ public class DailyReportEmailer
if (line.hasOption("m"))
{
writer
.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
writer.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
numBitstreams += reporter.getBitstreamNotFoundReport(context,
yesterday, tomorrow, writer);
yesterday, tomorrow, writer);
writer.flush();
writer.close();
emailer.sendReport(report, numBitstreams);
@@ -259,10 +231,9 @@ public class DailyReportEmailer
if (line.hasOption("c"))
{
writer
.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
writer.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
numBitstreams += reporter.getChangedChecksumReport(context,
yesterday, tomorrow, writer);
yesterday, tomorrow, writer);
writer.flush();
writer.close();
emailer.sendReport(report, numBitstreams);
@@ -270,10 +241,9 @@ public class DailyReportEmailer
if (line.hasOption("n"))
{
writer
.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
writer.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
numBitstreams += reporter.getNotToBeProcessedReport(context,
yesterday, tomorrow, writer);
yesterday, tomorrow, writer);
writer.flush();
writer.close();
emailer.sendReport(report, numBitstreams);
@@ -281,10 +251,9 @@ public class DailyReportEmailer
if (line.hasOption("u"))
{
writer
.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
writer.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
numBitstreams += reporter
.getUncheckedBitstreamsReport(context, writer);
.getUncheckedBitstreamsReport(context, writer);
writer.flush();
writer.close();
emailer.sendReport(report, numBitstreams);
@@ -294,9 +263,10 @@ public class DailyReportEmailer
catch (MessagingException | SQLException | IOException e)
{
log.fatal(e);
} finally
}
finally
{
if(context != null && context.isValid())
if (context != null && context.isValid())
{
context.abort();
}

View File

@@ -30,8 +30,11 @@ public interface ChecksumHistoryDAO extends GenericDAO<ChecksumHistory> {
* the specified result code.
*
* @param context
* @param retentionDate row must be older than this to be deleted.
* @param checksumResultCode row must have this result to be deleted.
* The relevant DSpace Context.
* @param retentionDate
* row must be older than this to be deleted.
* @param checksumResultCode
* row must have this result to be deleted.
* @return number of rows deleted.
* @throws SQLException if database error
*/
@@ -41,7 +44,9 @@ public interface ChecksumHistoryDAO extends GenericDAO<ChecksumHistory> {
* Delete all ChecksumHistory rows for the given Bitstream.
*
* @param context
* The relevant DSpace Context.
* @param bitstream
* which bitstream's checksums to delete
* @throws SQLException if database error
*/
public void deleteByBitstream(Context context, Bitstream bitstream) throws SQLException;

View File

@@ -345,8 +345,9 @@ public class Bitstream extends DSpaceObject implements DSpaceObjectLegacySupport
* bitstream is uncertain, and the format is set to "unknown."
*
* @param context
* The relevant DSpace Context.
* @param desc
* the user's description of the format
* the user's description of the format
* @throws SQLException if database error
*/
public void setUserFormatDescription(Context context, String desc) throws SQLException
@@ -436,4 +437,4 @@ public class Bitstream extends DSpaceObject implements DSpaceObjectLegacySupport
return hash;
}
}
}

View File

@@ -379,12 +379,13 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl<Collection> i
* Get the value of a metadata field
*
* @param collection
* which collection to operate on
* @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
*
* @exception IllegalArgumentException
* @throws IllegalArgumentException
* if the requested metadata field doesn't exist
*/
@Override

View File

@@ -516,7 +516,7 @@ public class DCDate
public String displayUTCDate(boolean showTime, Locale locale)
{
// forcibly truncate month name to 3 chars -- XXX FIXME?
// forcibly truncate month name to 3 chars -- XXX FIXME?
String monthName = getMonthName(getMonthUTC(), locale);
if (monthName.length() > 2)
monthName = monthName.substring(0, 3);
@@ -540,7 +540,7 @@ public class DCDate
}
}
/**
/**
* Test if the requested level of granularity is within that of the date.
*
* @param dg
@@ -594,23 +594,21 @@ public class DCDate
* Get a date representing the current instant in time.
*
* @return a DSpaceDate object representing the current instant.
*/
public static DCDate getCurrent()
{
return (new DCDate(new Date()));
}
/**
/**
* Get a month's name for a month between 1 and 12. Any invalid month value
* (e.g. 0 or -1) will return a value of "Unspecified".
*
* @param m
* the month number
*
* the month number
* @param locale
*
* @return the month name.
* which locale to render the month name in
* @return the month name.
*/
public static String getMonthName(int m, Locale locale)
{

View File

@@ -149,8 +149,8 @@ public class ItemComparator implements Comparator, Serializable
}
/**
* @param first
* @param second
* @param first first operand
* @param second second operand
* @return true if the first string is equal to the second. Either or both
* may be null.
*/
@@ -224,7 +224,8 @@ public class ItemComparator implements Comparator, Serializable
/**
* Normalize the title of a Metadatum.
* @param value
*
* @param value metadata value
* @return normalized title
*/
protected String normalizeTitle(MetadataValue value)

View File

@@ -534,10 +534,10 @@ public class ItemServiceImpl extends DSpaceObjectServiceImpl<Item> implements It
// switch all READ authorization policies to WITHDRAWN_READ
authorizeService.switchPoliciesAction(context, item, Constants.READ, Constants.WITHDRAWN_READ);
for (Bundle bnd : item.getBundles()) {
authorizeService.switchPoliciesAction(context, bnd, Constants.READ, Constants.WITHDRAWN_READ);
for (Bitstream bs : bnd.getBitstreams()) {
authorizeService.switchPoliciesAction(context, bs, Constants.READ, Constants.WITHDRAWN_READ);
}
authorizeService.switchPoliciesAction(context, bnd, Constants.READ, Constants.WITHDRAWN_READ);
for (Bitstream bs : bnd.getBitstreams()) {
authorizeService.switchPoliciesAction(context, bs, Constants.READ, Constants.WITHDRAWN_READ);
}
}
// Write log
@@ -586,26 +586,26 @@ public class ItemServiceImpl extends DSpaceObjectServiceImpl<Item> implements It
context.addEvent(new Event(Event.MODIFY, Constants.ITEM, item.getID(),
"REINSTATE", getIdentifiers(context, item)));
// restore all WITHDRAWN_READ authorization policies back to READ
for (Bundle bnd : item.getBundles()) {
authorizeService.switchPoliciesAction(context, bnd, Constants.WITHDRAWN_READ, Constants.READ);
for (Bitstream bs : bnd.getBitstreams()) {
authorizeService.switchPoliciesAction(context, bs, Constants.WITHDRAWN_READ, Constants.READ);
}
}
// restore all WITHDRAWN_READ authorization policies back to READ
for (Bundle bnd : item.getBundles()) {
authorizeService.switchPoliciesAction(context, bnd, Constants.WITHDRAWN_READ, Constants.READ);
for (Bitstream bs : bnd.getBitstreams()) {
authorizeService.switchPoliciesAction(context, bs, Constants.WITHDRAWN_READ, Constants.READ);
}
}
// check if the item was withdrawn before the fix DS-3097
if (authorizeService.getPoliciesActionFilter(context, item, Constants.WITHDRAWN_READ).size() != 0) {
authorizeService.switchPoliciesAction(context, item, Constants.WITHDRAWN_READ, Constants.READ);
authorizeService.switchPoliciesAction(context, item, Constants.WITHDRAWN_READ, Constants.READ);
}
else {
// authorization policies
if (colls.size() > 0)
{
// remove the item's policies and replace them with
// the defaults from the collection
adjustItemPolicies(context, item, item.getOwningCollection());
}
// authorization policies
if (colls.size() > 0)
{
// remove the item's policies and replace them with
// the defaults from the collection
adjustItemPolicies(context, item, item.getOwningCollection());
}
}
// Write log
@@ -919,12 +919,12 @@ public class ItemServiceImpl extends DSpaceObjectServiceImpl<Item> implements It
// is this collection not yet created, and an item template is created
if (item.getOwningCollection() == null)
{
if (!isInProgressSubmission(context, item)) {
return true;
}
else {
return false;
}
if (!isInProgressSubmission(context, item)) {
return true;
}
else {
return false;
}
}
return collectionService.canEditBoolean(context, item.getOwningCollection(), false);
@@ -932,18 +932,21 @@ public class ItemServiceImpl extends DSpaceObjectServiceImpl<Item> implements It
/**
* Check if the item is an inprogress submission
*
* @param context
* @param item
* The relevant DSpace Context.
* @param item item to check
* @return <code>true</code> if the item is an inprogress submission, i.e. a WorkspaceItem or WorkflowItem
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public boolean isInProgressSubmission(Context context, Item item) throws SQLException {
return workspaceItemService.findByItem(context, item) != null
|| workflowItemService.findByItem(context, item) != null;
return workspaceItemService.findByItem(context, item) != null
|| workflowItemService.findByItem(context, item) != null;
}
/*
With every finished submission a bunch of resource policy entries with have null value for the dspace_object column are generated in the database.
With every finished submission a bunch of resource policy entries which have null value for the dspace_object column are generated in the database.
prevent the generation of resource policy entry values with null dspace_object as value
*/
@@ -952,10 +955,16 @@ prevent the generation of resource policy entry values with null dspace_object a
* Add the default policies, which have not been already added to the given DSpace object
*
* @param context
* The relevant DSpace Context.
* @param dso
* The DSpace Object to add policies to
* @param defaultCollectionPolicies
* list of policies
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
protected void addDefaultPoliciesNotInPlace(Context context, DSpaceObject dso, List<ResourcePolicy> defaultCollectionPolicies) throws SQLException, AuthorizeException
{
@@ -983,8 +992,12 @@ prevent the generation of resource policy entry values with null dspace_object a
* @param value field value or Item.ANY to match any value
* @return an iterator over the items matching that authority value
* @throws SQLException if database error
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException if authorization error
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
* @throws IOException if IO error
* A general class of exceptions produced by failed or interrupted I/O operations.
*
*/
@Override

View File

@@ -57,10 +57,15 @@ public class LicenseUtils
* LicenseArgumentFormatter based on his type (map key)
*
* @param locale
* Formatter locale
* @param collection
* collection to get license from
* @param item
* the item object of the license
* @param eperson
* EPerson to get firstname, lastname and email from
* @param additionalInfo
* additional template arguments beyond 0-6
* @return the license text obtained substituting the provided argument in
* the license template
*/
@@ -104,9 +109,13 @@ public class LicenseUtils
* supplying {@code null} for the additionalInfo argument)
*
* @param locale
* Formatter locale
* @param collection
* collection to get license from
* @param item
* the item object of the license
* @param eperson
* EPerson to get firstname, lastname and email from
* @return the license text, with no custom substitutions.
*/
public static String getLicenseText(Locale locale, Collection collection,

View File

@@ -27,6 +27,7 @@ public class NonUniqueMetadataException extends Exception
* Create an exception with only a message
*
* @param message
* message string
*/
public NonUniqueMetadataException(String message)
{

View File

@@ -57,9 +57,24 @@ public class CrosswalkMetadataValidator {
/**
* Scans metadata for elements not defined in this DSpace instance. It then takes action based
* on a configurable parameter (fail, ignore, add).
*
* @param context
* The relevant DSpace Context.
* @param schema metadata field schema
* @param element metadata field element
* @param qualifier metadata field qualifier
* @param forceCreate if true, force addinga schema or metadata field
* @return metadata field
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
* @throws CrosswalkException
* Superclass for more-specific crosswalk exceptions.
*/
public MetadataField checkMetadata(Context context, String schema, String element, String qualifier, boolean forceCreate) throws SQLException, AuthorizeException, CrosswalkException {
if(!validatedBefore(schema, element, qualifier)) {
if (!validatedBefore(schema, element, qualifier)) {
// Verify that the schema exists
MetadataSchema mdSchema = metadataSchemaService.find(context, schema);
MetadataField mdField = null;

View File

@@ -402,9 +402,13 @@ public class METSRightsCrosswalk
* Ingest a whole XML document, starting at specified root.
*
* @param context
* The relevant DSpace Context.
* @param dso
* DSpace object to ingest
* @param root
* root element
* @param createMissingMetadataFields
* whether to create missing fields
* @throws CrosswalkException if crosswalk error
* @throws IOException if IO error
* @throws SQLException if database error

View File

@@ -311,7 +311,7 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
/**
* Returns object's metadata in MODS format, as List of XML structure nodes.
* @param context context
* @throws org.dspace.content.crosswalk.CrosswalkException
* @throws CrosswalkException if crosswalk error
* @throws IOException if IO error
* @throws SQLException if database error
* @throws AuthorizeException if authorization error

View File

@@ -32,6 +32,7 @@ public interface ParameterizedDisseminationCrosswalk
* <p>
*
* @param context
* The relevant DSpace Context.
* @param dso the DSpace Object whose metadata to export.
* @param parameters
* names and values of parameters to be passed into the transform.

View File

@@ -50,7 +50,7 @@ import org.slf4j.LoggerFactory;
* Configurable XSLT-driven dissemination Crosswalk
* <p>
* See the XSLTCrosswalk superclass for details on configuration.
* <p>
* </p>
* <h3>Additional Configuration of Dissemination crosswalk:</h3>
* The disseminator also needs to be configured with an XML Namespace
* (including prefix and URI) and an XML Schema for output format. This
@@ -524,7 +524,8 @@ public class XSLTDisseminationCrosswalk
/**
* Simple command-line rig for testing the DIM output of a stylesheet.
* Usage: {@code java XSLTDisseminationCrosswalk <crosswalk-name> <handle> [output-file]}
* @param argv arguments
*
* @param argv the command line arguments given
* @throws Exception if error
*/
public static void main(String[] argv) throws Exception

View File

@@ -293,7 +293,8 @@ public class XSLTIngestionCrosswalk
/**
* Simple command-line rig for testing the DIM output of a stylesheet.
* Usage: {@code java XSLTIngestionCrosswalk <crosswalk-name> <input-file>}
* @param argv arguments
*
* @param argv the command line arguments given
* @throws Exception if error
*/
public static void main(String[] argv) throws Exception

View File

@@ -106,6 +106,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
protected final WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
/**
* <p>
* An instance of ZipMdrefManager holds the state needed to retrieve the
* contents of an external metadata stream referenced by an
* <code>mdRef</code> element in a Zipped up METS manifest.
@@ -244,7 +245,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
license);
//if ingestion was successful
if(dso!=null)
if (dso!=null)
{
// Log whether we finished an ingest (create new obj) or a restore
// (restore previously existing obj)
@@ -338,7 +339,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
// Retrieve the manifest file entry (named mets.xml)
ZipEntry manifestEntry = zip.getEntry(METSManifest.MANIFEST_FILE);
if(manifestEntry!=null)
if (manifestEntry!=null)
{
// parse the manifest and sanity-check it.
manifest = METSManifest.create(zip.getInputStream(manifestEntry),
@@ -404,7 +405,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
catch(UnsupportedOperationException e)
{
//If user specified to skip item ingest if any "missing parent" error message occur
if(params.getBooleanProperty("skipIfParentMissing", false))
if (params.getBooleanProperty("skipIfParentMissing", false))
{
//log a warning instead of throwing an error
log.warn(LogManager.getHeader(context, "package_ingest",
@@ -518,7 +519,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
// Finally, if item is still in the workspace, then we actually need
// to install it into the archive & assign its handle.
if(wsi!=null)
if (wsi!=null)
{
// Finish creating the item. This actually assigns the handle,
// and will either install item immediately or start a workflow, based on params
@@ -531,7 +532,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
// Add logo if one is referenced from manifest
addContainerLogo(context, dso, manifest, pkgFile, params);
if(type==Constants.COLLECTION)
if (type==Constants.COLLECTION)
{
//Add template item if one is referenced from manifest (only for Collections)
addTemplateItem(context, dso, manifest, pkgFile, params, callback);
@@ -670,11 +671,11 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
// have subclass manage license since it may be extra package file.
Collection owningCollection = (Collection) ContentServiceFactory.getInstance().getDSpaceObjectService(dso).getParentObject(context, dso);
if(owningCollection == null)
if (owningCollection == null)
{
//We are probably dealing with an item that isn't archived yet
InProgressSubmission inProgressSubmission = workspaceItemService.findByItem(context, item);
if(inProgressSubmission == null)
if (inProgressSubmission == null)
{
inProgressSubmission = WorkflowServiceFactory.getInstance().getWorkflowItemService().findByItem(context, item);
}
@@ -817,7 +818,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
// Set bitstream sequence id, if known
String seqID = mfile.getAttributeValue("SEQ");
if(seqID!=null && !seqID.isEmpty())
if (seqID!=null && !seqID.isEmpty())
bitstream.setSequenceID(Integer.parseInt(seqID));
// crosswalk this bitstream's administrative metadata located in
@@ -878,18 +879,18 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
bundle = bundleService.create(context, item, bundleName);
}
String mfileGrp = mfile.getAttributeValue("ADMID");
if (mfileGrp != null)
{
manifest.crosswalkBundle(context, params, bundle, mfileGrp,mdRefCallback);
}
else
{
if (log.isDebugEnabled())
{
log.debug("Ingesting bundle with no ADMID, not crosswalking bundle metadata");
}
}
String mfileGrp = mfile.getAttributeValue("ADMID");
if (mfileGrp != null)
{
manifest.crosswalkBundle(context, params, bundle, mfileGrp,mdRefCallback);
}
else
{
if (log.isDebugEnabled())
{
log.debug("Ingesting bundle with no ADMID, not crosswalking bundle metadata");
}
}
bundleService.update(context, bundle);
}// end for each manifest file
@@ -1044,7 +1045,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
CrosswalkException, PackageValidationException
{
//Template items only valid for collections
if(dso.getType()!=Constants.COLLECTION)
if (dso.getType()!=Constants.COLLECTION)
return;
Collection collection = (Collection) dso;
@@ -1052,18 +1053,18 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
//retrieve list of all <div>s representing child objects from manifest
List childObjList = manifest.getChildObjDivs();
if(childObjList!=null && !childObjList.isEmpty())
if (childObjList!=null && !childObjList.isEmpty())
{
Element templateItemDiv = null;
Iterator childIterator = childObjList.iterator();
//Search for the child with a type of "DSpace ITEM Template"
while(childIterator.hasNext())
while (childIterator.hasNext())
{
Element childDiv = (Element) childIterator.next();
String childType = childDiv.getAttributeValue("TYPE");
//should be the only child of type "ITEM" with "Template" for a suffix
if(childType.contains(Constants.typeText[Constants.ITEM]) &&
if (childType.contains(Constants.typeText[Constants.ITEM]) &&
childType.endsWith(AbstractMETSDisseminator.TEMPLATE_TYPE_SUFFIX))
{
templateItemDiv = childDiv;
@@ -1072,11 +1073,11 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
}
//If an Template Item was found, create it with the specified metadata
if(templateItemDiv!=null)
if (templateItemDiv!=null)
{
//make sure this templateItemDiv is associated with one or more dmdSecs
String templateDmdIds = templateItemDiv.getAttributeValue("DMDID");
if(templateDmdIds!=null)
if (templateDmdIds!=null)
{
//create our template item & get a reference to it
itemService.createTemplateItem(context, collection);
@@ -1193,7 +1194,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
null);
//if ingestion was successful
if(dso!=null)
if (dso!=null)
{
// Log that we created an object
log.info(LogManager.getHeader(context, "package_replace",
@@ -1222,7 +1223,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
}
//if ingest/restore/replace successful
if(dso!=null)
if (dso!=null)
{
// Check if the Packager is currently running recursively.
// If so, this means the Packager will attempt to recursively
@@ -1547,14 +1548,16 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
*
* @param context the DSpace context
* @param dso DSpace Object
* @param manifest the METSManifest
* @param manifest
* the METSManifest
* @param callback
* the MdrefManager (manages all external metadata files
* referenced by METS <code>mdref</code> elements)
* the MdrefManager (manages all external metadata files
* referenced by METS <code>mdref</code> elements)
* @param dmds
* array of Elements, each a METS <code>dmdSec</code> that
* applies to the Item as a whole.
* array of Elements, each a METS <code>dmdSec</code> that
* applies to the Item as a whole.
* @param params
* Packager Parameters
* @throws CrosswalkException if crosswalk error
* @throws PackageValidationException if package validation error
* @throws IOException if IO error
@@ -1586,10 +1589,11 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester
* the DSpace context
* @param item Item
* @param collection
* DSpace Collection to which the item is being submitted.
* DSpace Collection to which the item is being submitted.
* @param license
* optional user-supplied Deposit License text (may be null)
* optional user-supplied Deposit License text (may be null)
* @param params
* Packager Parameters
* @throws PackageValidationException if package validation error
* @throws IOException if IO error
* @throws SQLException if database error

View File

@@ -454,6 +454,7 @@ public class DSpaceAIPDisseminator extends AbstractMETSDisseminator
* @throws IOException if IO error
* @throws AuthorizeException if authorization error
* @throws MetsException
* METS Java toolkit exception class.
*/
@Override
public void addStructMap(Context context, DSpaceObject dso,

View File

@@ -95,6 +95,21 @@ public class DSpaceAIPIngester
* 3. If (1) or (2) succeeds, crosswalk it and ignore all other DMDs with
* same GROUPID<br>
* 4. Crosswalk remaining DMDs not eliminated already.
*
* @param context
* The relevant DSpace Context.
* @param dso
* DSpace object
* @param manifest
* the METSManifest
* @param callback
* the MdrefManager (manages all external metadata files
* referenced by METS <code>mdref</code> elements)
* @param dmds
* array of Elements, each a METS <code>dmdSec</code> that
* applies to the Item as a whole.
* @param params
* Packager Parameters
* @throws PackageValidationException validation error
* @throws CrosswalkException if crosswalk error
* @throws IOException if IO error
@@ -198,6 +213,15 @@ public class DSpaceAIPIngester
* license supplied by explicit argument next, else use collection's
* default deposit license.
* Normally the rightsMD crosswalks should provide a license.
*
* @param context
* The relevant DSpace Context.
* @param item
* item to add license to
* @param collection
* collection to get the default license from
* @param params
* Packager Parameters
* @throws PackageValidationException validation error
* @throws IOException if IO error
* @throws SQLException if database error
@@ -211,7 +235,7 @@ public class DSpaceAIPIngester
{
boolean newLicense = false;
if(!params.restoreModeEnabled())
if (!params.restoreModeEnabled())
{
//AIP is not being restored/replaced, so treat it like a SIP -- every new SIP needs a new license
newLicense = true;
@@ -225,7 +249,7 @@ public class DSpaceAIPIngester
newLicense = true;
}
if(newLicense)
if (newLicense)
{
PackageUtils.addDepositLicense(context, license, item, collection);
}
@@ -233,19 +257,30 @@ public class DSpaceAIPIngester
/**
* Last change to fix up a DSpace Object.
* <P>
* <p>
* For AIPs, if the object is an Item, we may want to make sure all of its
* metadata fields already exist in the database (otherwise, the database
* will throw errors when we attempt to save/update the Item)
* </p>
*
* @param context DSpace Context
* @param dso DSpace object
* @param params Packager Parameters
* @throws org.dspace.content.packager.PackageValidationException
* @throws java.sql.SQLException
* @throws org.dspace.content.crosswalk.CrosswalkException
* @throws java.io.IOException
* @throws org.dspace.authorize.AuthorizeException
* @param context
* The relevant DSpace Context.
* @param dso
* DSpace object
* @param params
* Packager Parameters
* @throws PackageValidationException
* Failure when importing or exporting a package
* caused by invalid unacceptable package format or contents
* @throws CrosswalkException
* Superclass for more-specific crosswalk exceptions.
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
@Override
public void finishObject(Context context, DSpaceObject dso, PackageParameters params)
@@ -253,7 +288,7 @@ public class DSpaceAIPIngester
AuthorizeException, SQLException, IOException
{
//Metadata fields are now required before adding, so this logic isn't needed anymore
/*if(dso.getType()==Constants.ITEM)
/*if (dso.getType()==Constants.ITEM)
{
// Check if 'createMetadataFields' option is enabled (default=true)
// This defaults to true as by default we should attempt to restore as much metadata as we can.

View File

@@ -8,15 +8,18 @@
package org.dspace.content.packager;
/**
* <p>
* This represents a failure when importing or exporting a package
* caused by invalid unacceptable package format or contents; for
* example, missing files that were mentioned in the manifest, or
* extra files not in manifest, or lack of a manifest.
* </p>
* <p>
* When throwing a PackageValidationException, be sure the message
* includes enough specific information to let the end user diagnose
* the problem, i.e. what files appear to be missing from the manifest
* or package, or the details of a checksum error on a file.
* </p>
*
* @author Larry Stone
* @version $Revision$

View File

@@ -430,6 +430,7 @@ public class RoleIngester implements PackageIngester
* @param context DSpace Context
* @param parent the Parent DSpaceObject
* @param params package params
* @param stream input stream with the roles
* @throws PackageException if packaging error
* @throws SQLException if database error
* @throws AuthorizeException if authorization error

View File

@@ -77,8 +77,11 @@ public interface CollectionService extends DSpaceObjectService<Collection>, DSpa
/**
* Get all collections in the system. Adds support for limit and offset.
* @param context
* The relevant DSpace Context.
* @param limit
* paging limit
* @param offset
* paging offset
* @return List of Collections
* @throws SQLException if database error
*/

View File

@@ -104,7 +104,7 @@ public interface CommunityService extends DSpaceObjectService<Community>, DSpace
*
* @return the value of the metadata field
*
* @exception IllegalArgumentException
* @throws IllegalArgumentException
* if the requested metadata field doesn't exist
* @deprecated
*/
@@ -123,9 +123,9 @@ public interface CommunityService extends DSpaceObjectService<Community>, DSpace
* @param value
* value to set the field to
*
* @exception IllegalArgumentException
* @throws IllegalArgumentException
* if the requested metadata field doesn't exist
* @exception java.util.MissingResourceException
* @throws MissingResourceException if resource missing
* @throws SQLException if database error
* @deprecated
*/
@@ -192,7 +192,12 @@ public interface CommunityService extends DSpaceObjectService<Community>, DSpace
/**
* Return an array of parent communities of this collection.
*
* @param context
* The relevant DSpace Context.
* @param collection
* collection to check
* @return an array of parent communities
* @throws SQLException if database error
*/
public List<Community> getAllParents(Context context, Collection collection) throws SQLException;

View File

@@ -181,7 +181,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
*
* @return the value of the metadata field (or null if the column is an SQL NULL)
*
* @exception IllegalArgumentException
* @throws IllegalArgumentException
* if the requested metadata field doesn't exist
*/
public String getMetadata(T dSpaceObject, String value);

View File

@@ -53,7 +53,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
*
* @param context DSpace context object
* @param collection Collection (parent)
* @return Item
* @return empty template item for this collection
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
*/
@@ -96,8 +96,10 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
/**
* Retrieve the list of items submitted by eperson, ordered by recently submitted, optionally limitable
* @param context context
* @param eperson eperson
*
* @param context DSpace context object
* @param eperson
* the submitter
* @param limit a positive integer to limit, -1 or null for unlimited
* @return an iterator over the items submitted by eperson
* @throws SQLException if database error
@@ -128,7 +130,8 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
/**
* Get all Items installed or withdrawn, discoverable, and modified since a Date.
* @param context context
*
* @param context DSpace context object
* @param since earliest interesting last-modified date, or null for no date test.
* @return an iterator over the items in the collection.
* @throws SQLException if database error
@@ -148,7 +151,8 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
/**
* See whether this Item is contained by a given Collection.
* @param item Item
*
* @param item item to check
* @param collection Collection (parent
* @return true if {@code collection} contains this Item.
* @throws SQLException if database error
@@ -161,7 +165,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* communities of the owning collections.
*
* @param context DSpace context object
* @param item Item
* @param item item to check
* @return the communities this item is in.
* @throws SQLException if database error
*/
@@ -171,7 +175,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
/**
* Get the bundles matching a bundle name (name corresponds roughly to type)
*
* @param item Item
* @param item item to check
* @param name
* name of bundle (ORIGINAL/TEXT/THUMBNAIL)
* @throws SQLException if database error
@@ -184,7 +188,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Add an existing bundle to this item. This has immediate effect.
*
* @param context DSpace context object
* @param item Item
* @param item item to add the bundle to
* @param bundle
* the bundle to add
* @throws SQLException if database error
@@ -210,9 +214,10 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
/**
* Remove all bundles linked to this item. This may result in the bundle being deleted, if the
* bundle is orphaned.
*
* @param context DSpace context object
* @param item
* the item from which to remove our bundles
* the item from which to remove all bundles
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
* @throws IOException if IO error
@@ -224,7 +229,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* method for the most common use.
*
* @param context DSpace context object
* @param item Item
* @param item item to create bitstream on
* @param is
* the stream to create the new bitstream from
* @param name
@@ -241,7 +246,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Convenience method, calls createSingleBitstream() with name "ORIGINAL"
*
* @param context DSpace context object
* @param item Item
* @param item item to create bitstream on
* @param is
* InputStream
* @return created bitstream
@@ -256,8 +261,9 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Get all non-internal bitstreams in the item. This is mainly used for
* auditing for provenance messages and adding format.* DC values. The order
* is indeterminate.
*
* @param context DSpace context object
* @param item Item
* @param item item to check
* @return non-internal bitstreams.
* @throws SQLException if database error
*/
@@ -271,7 +277,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* This method is used by the org.dspace.submit.step.LicenseStep class
*
* @param context DSpace context object
* @param item Item
* @param item item to remove DSpace license from
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
* @throws IOException if IO error
@@ -283,7 +289,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Remove all licenses from an item - it was rejected
*
* @param context DSpace context object
* @param item Item
* @param item item to remove all licenses from
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
* @throws IOException if IO error
@@ -295,7 +301,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* and metadata are not deleted, but it is not publicly accessible.
*
* @param context DSpace context object
* @param item Item
* @param item item to withdraw
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
*/
@@ -306,7 +312,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Reinstate a withdrawn item
*
* @param context DSpace context object
* @param item Item
* @param item withdrawn item to reinstate
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
*/
@@ -315,7 +321,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
/**
* Return true if this Collection 'owns' this item
*
* @param item Item
* @param item item to check
* @param collection
* Collection
* @return true if this Collection owns this item
@@ -327,7 +333,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* policies
*
* @param context DSpace context object
* @param item Item
* @param item item to replace policies on
* @param newpolicies -
* this will be all of the new policies for the item and its
* contents
@@ -342,7 +348,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* them with a new list of policies
*
* @param context DSpace context object
* @param item Item
* @param item item to replace policies on
* @param newpolicies -
* this will be all of the new policies for the bundle and
* bitstream contents
@@ -358,7 +364,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* to a given Group
*
* @param context DSpace context object
* @param item Item
* @param item item to remove group policies from
* @param group
* Group referenced by policies that needs to be removed
* @throws SQLException if database error
@@ -372,7 +378,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* the collection.
*
* @param context DSpace context object
* @param item Item
* @param item item to reset policies on
* @param collection
* Collection
* @throws SQLException if database error
@@ -392,7 +398,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Moves the item from one collection to another one
*
* @param context DSpace context object
* @param item Item
* @param item item to move
* @param from Collection to move from
* @param to Collection to move to
* @throws SQLException if database error
@@ -405,7 +411,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Moves the item from one collection to another one
*
* @param context DSpace context object
* @param item Item
* @param item item to move
* @param from Collection to move from
* @param to Collection to move to
* @param inheritDefaultPolicies whether to inherit policies from new collection
@@ -413,12 +419,12 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* @throws AuthorizeException if authorization error
* @throws IOException if IO error
*/
public void move (Context context, Item item, Collection from, Collection to, boolean inheritDefaultPolicies) throws SQLException, AuthorizeException, IOException;
public void move(Context context, Item item, Collection from, Collection to, boolean inheritDefaultPolicies) throws SQLException, AuthorizeException, IOException;
/**
* Check the bundle ORIGINAL to see if there are any uploaded files
*
* @param item Item
* @param item item to check
* @return true if there is a bundle named ORIGINAL with one or more
* bitstreams inside
* @throws SQLException if database error
@@ -429,7 +435,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Get the collections this item is not in.
*
* @param context DSpace context object
* @param item Item
* @param item item to check
* @return the collections this item is not in, if any.
* @throws SQLException if database error
*/
@@ -439,7 +445,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* return TRUE if context's user can edit item, false otherwise
*
* @param context DSpace context object
* @param item Item
* @param item item to check
* @return boolean true = current user can edit item
* @throws SQLException if database error
*/
@@ -448,8 +454,10 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
/**
* return TRUE if context's user can create new version of the item, false
* otherwise.
* @param context DSpace context object
* @param item item to check
* @return boolean true = current user can create new version of the item
* @throws SQLException
* @throws SQLException if database error
*/
public boolean canCreateNewVersion(Context context, Item item) throws SQLException;
@@ -500,7 +508,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
* Service method for knowing if this Item should be visible in the item list.
* Items only show up in the "item list" if the user has READ permission
* and if the Item isn't flagged as unlisted.
* @param context context
* @param context DSpace context object
* @param item item
* @return true or false
*/
@@ -519,7 +527,7 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
/**
* Find all Items modified since a Date.
*
* @param context context
* @param context DSpace context object
* @param last Earliest interesting last-modified date.
* @return iterator over items
* @throws SQLException if database error
@@ -564,11 +572,12 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
*/
int countWithdrawnItems(Context context) throws SQLException;
/**
* Check if the supplied item is an inprogress submission
* @param context
* @param item
* @return <code>true</code> if the item is linked to a workspaceitem or workflowitem
*/
/**
* Check if the supplied item is an inprogress submission
* @param context DSpace context object
* @param item item to check
* @return <code>true</code> if the item is linked to a workspaceitem or workflowitem
* @throws SQLException if database error
*/
boolean isInProgressSubmission(Context context, Item item) throws SQLException;
}

View File

@@ -37,7 +37,7 @@ public interface MetadataFieldService {
* @return new MetadataField
* @throws AuthorizeException if authorization error
* @throws SQLException if database error
* @throws NonUniqueMetadataException
* @throws NonUniqueMetadataException if an existing field with an identical element and qualifier is already present
*/
public MetadataField create(Context context, MetadataSchema metadataSchema, String element, String qualifier, String scopeNote)
throws AuthorizeException, SQLException, NonUniqueMetadataException;
@@ -102,7 +102,7 @@ public interface MetadataFieldService {
* @param metadataField metadata field
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
* @throws NonUniqueMetadataException
* @throws NonUniqueMetadataException if an existing field with an identical element and qualifier is already present
* @throws IOException if IO error
*/
public void update(Context context, MetadataField metadataField)

View File

@@ -33,7 +33,7 @@ public interface MetadataSchemaService {
* @return new MetadataSchema
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
* @throws NonUniqueMetadataException
* @throws NonUniqueMetadataException if an existing field with an identical element and qualifier is already present
*/
public MetadataSchema create(Context context, String name, String namespace) throws SQLException, AuthorizeException, NonUniqueMetadataException;
@@ -54,7 +54,7 @@ public interface MetadataSchemaService {
* @param metadataSchema metadata schema
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
* @throws NonUniqueMetadataException
* @throws NonUniqueMetadataException if an existing field with an identical element and qualifier is already present
*/
public void update(Context context, MetadataSchema metadataSchema) throws SQLException, AuthorizeException, NonUniqueMetadataException;

View File

@@ -43,7 +43,7 @@ public interface MetadataValueService {
* @param context dspace context
* @param valueId database key id of value
* @return recalled metadata value
* @throws java.io.IOException
* @throws IOException if IO error
* @throws SQLException if database error
*/
public MetadataValue find(Context context, int valueId)
@@ -89,7 +89,7 @@ public interface MetadataValueService {
/**
* Get the minimum value of a given metadata field across all objects.
*
* @param context
* @param context dspace context
* @param metadataFieldId unique identifier of the interesting field.
* @return the minimum value of the metadata field
* @throws SQLException if database error

View File

@@ -143,6 +143,7 @@ public interface WorkspaceItemService extends InProgressSubmissionService<Worksp
/**
* The map entry returned contains stage reached as the key and count of items in that stage as a value
* @param context
* The relevant DSpace Context.
* @return the map
* @throws SQLException if database error
*/

View File

@@ -94,7 +94,9 @@ public abstract class AbstractHibernateDAO<T> implements GenericDAO<T> {
* Execute a JPA Criteria query and return a collection of results.
*
* @param context
* @param query JPQL query string
* The relevant DSpace Context.
* @param query
* JPQL query string
* @return list of DAOs specified by the query string
* @throws SQLException if database error
*/
@@ -134,7 +136,7 @@ public abstract class AbstractHibernateDAO<T> implements GenericDAO<T> {
* Retrieve a unique result from the query. If multiple results CAN be
* retrieved an exception will be thrown,
* so only use when the criteria state uniqueness in the database.
* @param criteria
* @param criteria JPA criteria
* @return a DAO specified by the criteria
*/
public T uniqueResult(Criteria criteria)
@@ -147,7 +149,7 @@ public abstract class AbstractHibernateDAO<T> implements GenericDAO<T> {
/**
* Retrieve a single result from the query. Best used if you expect a
* single result, but this isn't enforced on the database.
* @param criteria
* @param criteria JPA criteria
* @return a DAO specified by the criteria
*/
public T singleResult(Criteria criteria)

View File

@@ -40,8 +40,11 @@ public abstract class AbstractHibernateDSODAO<T extends DSpaceObject> extends Ab
* The identifier of the join will be the toString() representation of the metadata field.
* The joineded metadata fields can then be used to query or sort.
* @param query
* partial SQL query (to be appended)
* @param tableIdentifier
* DB table to join with
* @param metadataFields
* a collection of metadata fields
*/
protected void addMetadataLeftJoin(StringBuilder query, String tableIdentifier, Collection<MetadataField> metadataFields)
{
@@ -63,26 +66,26 @@ public abstract class AbstractHibernateDSODAO<T extends DSpaceObject> extends Ab
*/
protected void addMetadataValueWhereQuery(StringBuilder query, List<MetadataField> metadataFields, String operator, String additionalWhere)
{
if(CollectionUtils.isNotEmpty(metadataFields) || StringUtils.isNotBlank(additionalWhere)){
if (CollectionUtils.isNotEmpty(metadataFields) || StringUtils.isNotBlank(additionalWhere)) {
//Add the where query on metadata
query.append(" WHERE ");
for (int i = 0; i < metadataFields.size(); i++) {
MetadataField metadataField = metadataFields.get(i);
if(StringUtils.isNotBlank(operator))
if (StringUtils.isNotBlank(operator))
{
query.append(" (");
query.append("lower(STR(" + metadataField.toString()).append(".value)) ").append(operator).append(" lower(:queryParam)");
query.append(")");
if(i < metadataFields.size() - 1)
if (i < metadataFields.size() - 1)
{
query.append(" OR ");
}
}
}
if(StringUtils.isNotBlank(additionalWhere))
if (StringUtils.isNotBlank(additionalWhere))
{
if(CollectionUtils.isNotEmpty(metadataFields))
if (CollectionUtils.isNotEmpty(metadataFields))
{
query.append(" OR ");
}
@@ -95,23 +98,23 @@ public abstract class AbstractHibernateDSODAO<T extends DSpaceObject> extends Ab
protected void addMetadataSortQuery(StringBuilder query, List<MetadataField> metadataSortFields, List<String> columnSortFields)
{
if(CollectionUtils.isNotEmpty(metadataSortFields)){
if (CollectionUtils.isNotEmpty(metadataSortFields)) {
query.append(" ORDER BY ");
for (int i = 0; i < metadataSortFields.size(); i++) {
MetadataField metadataField = metadataSortFields.get(i);
query.append("STR(").append(metadataField.toString()).append(".value)");
if(i != metadataSortFields.size() -1)
if (i != metadataSortFields.size() -1)
{
query.append(",");
}
}
}else if(CollectionUtils.isNotEmpty(columnSortFields))
} else if (CollectionUtils.isNotEmpty(columnSortFields))
{
query.append(" ORDER BY ");
for (int i = 0; i < columnSortFields.size(); i++) {
String sortField = columnSortFields.get(i);
query.append(sortField);
if(i != columnSortFields.size() -1)
if (i != columnSortFields.size() -1)
{
query.append(",");
}

View File

@@ -130,7 +130,7 @@ public class Context
/**
* Initializes a new context object.
*
* @exception SQLException
* @throws SQLException
* if there was an error obtaining a database connection
*/
private void init()
@@ -337,7 +337,7 @@ public class Context
* Calling complete() on a Context which is no longer valid (isValid()==false),
* is a no-op.
*
* @exception SQLException
* @throws SQLException
* if there was an error completing the database transaction
* or closing the connection
*/
@@ -448,6 +448,7 @@ public class Context
* Add an event to be dispatched when this context is committed.
*
* @param event
* event to be dispatched
*/
public void addEvent(Event event)
{
@@ -634,6 +635,7 @@ public class Context
* means that more memory is consumed by the cache. This also has a negative impact on the query performance. In
* that case you should consider clearing the cache (see {@link Context#clearCache() clearCache}).
*
* @return connection cache size
* @throws SQLException When connecting to the active cache fails.
*/
public long getCacheSize() throws SQLException {

View File

@@ -49,12 +49,17 @@ public interface DBConnection<T> {
/**
* Reload a DSpace object from the database. This will make sure the object is valid and stored in the cache.
* @param entity The DSpace object to reload
* @return
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public <E extends ReloadableEntity> E reloadEntity(E entity) throws SQLException;
/**
* Remove a DSpace object from the cache when batch processing a large number of objects.
* @param entity The DSpace object to reload
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public <E extends ReloadableEntity> void uncacheEntity(E entity) throws SQLException ;
}
}

View File

@@ -42,25 +42,28 @@ import org.dspace.services.factory.DSpaceServicesFactory;
/**
* Class representing an e-mail message, also used to send e-mails.
* <P>
* <p>
* Typical use:
* <P>
* </p>
* <p>
* <code>Email email = new Email();</code><br>
* <code>email.addRecipient("foo@bar.com");</code><br>
* <code>email.addArgument("John");</code><br>
* <code>email.addArgument("On the Testing of DSpace");</code><br>
* <code>email.send();</code><br>
* <P>
* </p>
* <p>
* <code>name</code> is the name of an email template in
* <code>dspace-dir/config/emails/</code> (which also includes the subject.)
* <code>arg0</code> and <code>arg1</code> are arguments to fill out the
* message with.
* <P>
* </p>
* <p>
* Emails are formatted using <code>java.text.MessageFormat.</code>
* Additionally, comment lines (starting with '#') are stripped, and if a line
* starts with "Subject:" the text on the right of the colon is used for the
* subject line. For example:
* <P>
* </p>
*
* <pre>
*
@@ -77,10 +80,10 @@ import org.dspace.services.factory.DSpaceServicesFactory;
*
* </pre>
*
* <P>
* <p>
* 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:
* <P>
* </p>
*
* <pre>
*
@@ -91,9 +94,10 @@ import org.dspace.services.factory.DSpaceServicesFactory;
*
* </pre>
*
* <P>
* <p>
* Note that parameters like <code>{0}</code> cannot be placed in the subject
* of the e-mail; they won't get filled out.
* </p>
*
*
* @author Robert Tansley
@@ -295,37 +299,44 @@ public class Email
message.setText(fullMessage);
}
}
else{
Multipart multipart = new MimeMultipart();
// create the first part of the email
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(fullMessage);
multipart.addBodyPart(messageBodyPart);
if(!attachments.isEmpty()){
for (Iterator<FileAttachment> iter = attachments.iterator(); iter.hasNext();)
{
FileAttachment f = iter.next();
// add the file
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(
new FileDataSource(f.file)));
messageBodyPart.setFileName(f.name);
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
}
if(!moreAttachments.isEmpty()){
for (Iterator<InputStreamAttachment> iter = moreAttachments.iterator(); iter.hasNext();)
{
InputStreamAttachment isa = iter.next();
// add the stream
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(new InputStreamDataSource(isa.name,isa.mimetype,isa.is)));
messageBodyPart.setFileName(isa.name);
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
}
else
{
Multipart multipart = new MimeMultipart();
// create the first part of the email
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(fullMessage);
multipart.addBodyPart(messageBodyPart);
if (!attachments.isEmpty()) {
for (Iterator<FileAttachment> iter = attachments.iterator(); iter.hasNext();)
{
FileAttachment f = iter.next();
// add the file
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(
new FileDataSource(f.file)));
messageBodyPart.setFileName(f.name);
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
}
if (!moreAttachments.isEmpty()) {
for (Iterator<InputStreamAttachment> iter = moreAttachments.iterator(); iter.hasNext();)
{
InputStreamAttachment isa = iter.next();
// add the stream
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(
new DataHandler(new InputStreamDataSource(
isa.name,
isa.mimetype,
isa.is)
)
);
messageBodyPart.setFileName(isa.name);
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
}
}
if (replyTo != null)
@@ -338,7 +349,7 @@ public class Email
if (disabled)
{
StringBuffer text = new StringBuffer(
"Message not sent due to mail.server.disabled:\n");
"Message not sent due to mail.server.disabled:\n");
Enumeration<String> headers = message.getAllHeaderLines();
while (headers.hasMoreElements())
@@ -375,7 +386,7 @@ public class Email
* error reading the template
*/
public static Email getEmail(String emailFile)
throws IOException
throws IOException
{
String charset = null;
String subject = "";
@@ -459,7 +470,7 @@ public class Email
/**
* Test method to send an email to check email server settings
*
* @param args Command line options
* @param args the command line arguments given
*/
public static void main(String[] args)
{
@@ -479,7 +490,7 @@ public class Email
boolean disabled = config.getBooleanProperty("mail.server.disabled", false);
try
{
if( disabled)
if (disabled)
{
System.err.println("\nError sending email:");
System.err.println(" - Error: cannot test email because mail.server.disabled is set to true");
@@ -497,8 +508,10 @@ public class Email
System.err.println("\nPlease see the DSpace documentation for assistance.\n");
System.err.println("\n");
System.exit(1);
}catch (IOException e1) {
System.err.println("\nError sending email:");
}
catch (IOException e1)
{
System.err.println("\nError sending email:");
System.err.println(" - Error: " + e1);
System.err.println("\nPlease see the DSpace documentation for assistance.\n");
System.err.println("\n");

View File

@@ -33,6 +33,7 @@ public interface GenericDAO<T>
* Fetch all persisted instances of a given object type.
*
* @param context
* The relevant DSpace Context.
* @param clazz the desired type.
* @return list of DAOs of the same type as clazz
* @throws SQLException if database error
@@ -43,6 +44,7 @@ public interface GenericDAO<T>
* Execute a JPQL query returning a unique result.
*
* @param context
* The relevant DSpace Context.
* @param query JPQL query string
* @return a DAO specified by the query string
* @throws SQLException if database error
@@ -57,6 +59,7 @@ public interface GenericDAO<T>
* Execute a JPQL query and return a collection of results.
*
* @param context
* The relevant DSpace Context.
* @param query JPQL query string
* @return list of DAOs specified by the query string
* @throws SQLException if database error

View File

@@ -23,38 +23,43 @@ import org.dspace.services.ConfigurationService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* <p>
* The Legacy Plugin Service is a very simple component container (based on the
* legacy PluginManager class from 5.x or below). It reads defined "plugins" (interfaces)
* from config file(s) and makes them available to the API. (TODO: Someday, this
* entire "plugin" framework needs to be replaced by Spring Beans.)
* </p>
* <p>
* It creates and organizes components (plugins), and helps select a plugin in
* the cases where there are many possible choices. It also gives some limited
* control over the lifecycle of a plugin. It manages three different types
* (usage patterns) of plugins:
* <p>
* <ol><li> Singleton Plugin
* <br> There is only one implementation class for the plugin. It is indicated
* </p>
* <ol>
* <li>Singleton Plugin<br>
* There is only one implementation class for the plugin. It is indicated
* in the configuration. This type of plugin chooses an implementations of
* a service, for the entire system, at configuration time. Your
* application just fetches the plugin for that interface and gets the
* configured-in choice.
* configured-in choice.</li>
*
* <p><li> Sequence Plugins
* <br> You need a sequence or series of plugins, to implement a mechanism like
* <li>Sequence Plugins<br>
* You need a sequence or series of plugins, to implement a mechanism like
* StackableAuthenticationMethods or a pipeline, where each plugin is
* called in order to contribute its implementation of a process to the
* whole.
* <p><li> Named Plugins
* <br> Use a named plugin when the application has to choose one plugin
* whole.</li>
* <li>Named Plugins<br>
* Use a named plugin when the application has to choose one plugin
* implementation out of many available ones. Each implementation is bound
* to one or more names (symbolic identifiers) in the configuration.
* </ol><p>
* to one or more names (symbolic identifiers) in the configuration.</li>
* </ol>
* <p>
* The name is just a <code>String</code> to be associated with the
* combination of implementation class and interface. It may contain
* any characters except for comma (,) and equals (=). It may contain
* embedded spaces. Comma is a special character used to separate
* names in the configuration entry.
* </p>
*
* @author Larry Stone
* @author Tim Donohue (turned old PluginManager into a PluginService)
@@ -209,7 +214,7 @@ public class LegacyPluginServiceImpl implements PluginService
catch (ClassNotFoundException e)
{
throw new PluginInstantiationException("Cannot load plugin class: " +
e.toString(), e);
e.toString(), e);
}
catch (InstantiationException|IllegalAccessException e)
{
@@ -257,7 +262,7 @@ public class LegacyPluginServiceImpl implements PluginService
// If there's no "=" separator in this value, assume it's
// just a "name" that belongs with previous class.
// (This may occur if there's an unescaped comma between names)
if(prevClassName!=null && valSplit.length==1)
if (prevClassName!=null && valSplit.length==1)
{
className = prevClassName;
name = valSplit[0];
@@ -383,7 +388,7 @@ public class LegacyPluginServiceImpl implements PluginService
catch (ClassNotFoundException e)
{
throw new PluginInstantiationException("Cannot load plugin class: " +
e.toString(), e);
e.toString(), e);
}
catch (InstantiationException|IllegalAccessException e)
{
@@ -416,7 +421,7 @@ public class LegacyPluginServiceImpl implements PluginService
catch (ClassNotFoundException e)
{
throw new PluginInstantiationException("Cannot load plugin class: " +
e.toString(), e);
e.toString(), e);
}
}
@@ -713,7 +718,8 @@ public class LegacyPluginServiceImpl implements PluginService
* Invoking this class from the command line just runs
* <code>checkConfiguration</code> and shows the results.
* There are no command-line options.
* @param argv arguments
*
* @param argv the command line arguments given
* @throws Exception if error
*/
public void main(String[] argv) throws Exception

View File

@@ -35,27 +35,27 @@ public class NewsServiceImpl implements NewsService
{
private final Logger log = LoggerFactory.getLogger(NewsServiceImpl.class);
private List<String> acceptableFilenames;
private List<String> acceptableFilenames;
@Autowired(required = true)
private ConfigurationService configurationService;
public void setAcceptableFilenames(List<String> acceptableFilenames) {
public void setAcceptableFilenames(List<String> acceptableFilenames) {
this.acceptableFilenames = addLocalesToAcceptableFilenames(acceptableFilenames);
}
protected List<String> addLocalesToAcceptableFilenames(List<String> acceptableFilenames){
protected List<String> addLocalesToAcceptableFilenames(List<String> acceptableFilenames) {
String [] locales = configurationService.getArrayProperty("webui.supported.locales");
List<String> newAcceptableFilenames = new ArrayList<>();
newAcceptableFilenames.addAll(acceptableFilenames);
for(String local : locales){
for(String acceptableFilename : acceptableFilenames){
for (String local : locales) {
for (String acceptableFilename : acceptableFilenames) {
int lastPoint = acceptableFilename.lastIndexOf(".");
newAcceptableFilenames.add(
acceptableFilename.substring(0, lastPoint)
+ "_"
+ local
+ acceptableFilename.substring(lastPoint));
acceptableFilename.substring(0, lastPoint)
+ "_"
+ local
+ acceptableFilename.substring(lastPoint));
}
}
return newAcceptableFilenames;
@@ -68,9 +68,9 @@ public class NewsServiceImpl implements NewsService
@Override
public String readNewsFile(String newsFile)
{
if (!validate(newsFile)) {
throw new IllegalArgumentException("The file "+ newsFile + " is not a valid news file");
}
if (!validate(newsFile)) {
throw new IllegalArgumentException("The file " + newsFile + " is not a valid news file");
}
String fileName = getNewsFilePath();
fileName += newsFile;
@@ -106,9 +106,9 @@ public class NewsServiceImpl implements NewsService
@Override
public String writeNewsFile(String newsFile, String news)
{
if (!validate(newsFile)) {
throw new IllegalArgumentException("The file "+ newsFile + " is not a valid news file");
}
if (!validate(newsFile)) {
throw new IllegalArgumentException("The file "+ newsFile + " is not a valid news file");
}
String fileName = getNewsFilePath();
fileName += newsFile;
@@ -138,11 +138,11 @@ public class NewsServiceImpl implements NewsService
return filePath;
}
@Override
public boolean validate(String newsName) {
if (acceptableFilenames != null) {
return acceptableFilenames.contains(newsName);
}
return false;
}
@Override
public boolean validate(String newsName) {
if (acceptableFilenames != null) {
return acceptableFilenames.contains(newsName);
}
return false;
}
}

View File

@@ -42,11 +42,12 @@ public interface NewsService {
public String getNewsFilePath();
/**
* Check if the newsName is a valid one
* Check if the newsName is an acceptable file name
*
* @param newsName
* news name
* @return true
* if the newsName is valid
* if the newsName is valid
*/
public boolean validate(String newsName);
}

View File

@@ -113,7 +113,10 @@ public class BasicLinkChecker extends AbstractCurationTask
/**
* Check the URL and perform appropriate reporting
*
* @param url The URL to check
* @param url
* The URL to check
* @param results
* Result string with HTTP status codes
* @return If the URL was OK or not
*/
protected boolean checkURL(String url, StringBuilder results)

View File

@@ -113,6 +113,8 @@ public class BitstreamsIntoMetadata extends AbstractCurationTask
* @param item The item
* @param bitstream The bitstream
* @param type The type of bitstream
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
protected void addMetadata(Item item, Bitstream bitstream, String type) throws SQLException {
String value = bitstream.getFormat(Curator.curationContext()).getMIMEType() + "##";

View File

@@ -156,6 +156,9 @@ public class ClamScan extends AbstractCurationTask
/** openSession
*
* This method opens a session.
*
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
*/
protected void openSession() throws IOException

View File

@@ -86,7 +86,7 @@ public class Curator
*/
public Curator addTask(String taskName)
{
ResolvedTask task = resolver.resolveTask(taskName);
ResolvedTask task = resolver.resolveTask(taskName);
if (task != null)
{
try
@@ -149,7 +149,7 @@ public class Curator
*
* @param reporter name of reporting stream. The name '-'
* causes reporting to standard out.
* @return the Curator instance
* @return return self (Curator instance) with reporter set
*/
public Curator setReporter(String reporter)
{
@@ -166,11 +166,14 @@ public class Curator
* entire performance is complete, and a scope of 'object'
* will commit for each object (e.g. item) encountered in
* a given execution.
*
* @param scope transactional scope
* @return return self (Curator instance) with given scope set
*/
public Curator setTransactionScope(TxScope scope)
{
txScope = scope;
return this;
txScope = scope;
return this;
}
/**
@@ -207,11 +210,11 @@ public class Curator
}
// if curation scoped, commit transaction
if (txScope.equals(TxScope.CURATION)) {
Context ctx = curationCtx.get();
if (ctx != null)
{
ctx.complete();
}
Context ctx = curationCtx.get();
if (ctx != null)
{
ctx.complete();
}
}
}
catch (SQLException sqlE)
@@ -358,18 +361,20 @@ public class Curator
/**
* Returns the context object used in the current curation thread.
* This is primarily a utility method to allow tasks access to the context when necessary.
* <P>
* <p>
* If the context is null or not set, then this just returns
* a brand new Context object representing an Anonymous User.
*
* @return curation thread's Context object (or a new, anonymous Context if no curation Context exists)
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public static Context curationContext() throws SQLException
{
// Return curation context or new context if undefined/invalid
Context curCtx = curationCtx.get();
// Return curation context or new context if undefined/invalid
Context curCtx = curationCtx.get();
if(curCtx==null || !curCtx.isValid())
if (curCtx==null || !curCtx.isValid())
{
//Create a new context (represents an Anonymous User)
curCtx = new Context();
@@ -407,7 +412,7 @@ public class Curator
// Site-wide Tasks really should have an EPerson performer associated with them,
// otherwise they are run as an "anonymous" user with limited access rights.
if(ctx.getCurrentUser()==null && !ctx.ignoreAuthorization())
if (ctx.getCurrentUser()==null && !ctx.ignoreAuthorization())
{
log.warn("You are running one or more Site-Wide curation tasks in ANONYMOUS USER mode," +
" as there is no EPerson 'performer' associated with this task. To associate an EPerson 'performer' " +
@@ -502,17 +507,20 @@ public class Curator
/**
* Record a 'visit' to a DSpace object and enforce any policies set
* on this curator.
* @param dso the DSpace object
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
*/
protected void visit(DSpaceObject dso) throws IOException
{
Context curCtx = curationCtx.get();
if (curCtx != null)
{
Context curCtx = curationCtx.get();
if (curCtx != null)
{
if (txScope.equals(TxScope.OBJECT))
{
curCtx.dispatchEvents();
}
}
}
}
protected class TaskRunner
@@ -540,7 +548,7 @@ public class Curator
visit(dso);
return ! suspend(statusCode);
}
catch(IOException ioe)
catch (IOException ioe)
{
//log error & pass exception upwards
log.error("Error executing curation task '" + task.getName() + "'", ioe);
@@ -561,7 +569,7 @@ public class Curator
visit(null);
return ! suspend(statusCode);
}
catch(IOException ioe)
catch (IOException ioe)
{
//log error & pass exception upwards
log.error("Error executing curation task '" + task.getName() + "'", ioe);
@@ -576,7 +584,7 @@ public class Curator
protected boolean suspend(int code)
{
Invoked mode = task.getMode();
Invoked mode = task.getMode();
if (mode != null && (mode.equals(Invoked.ANY) || mode.equals(iMode)))
{
for (int i : task.getCodes())

View File

@@ -114,6 +114,7 @@ public class ResolvedTask
/**
* Returns whether task should be distributed through containers
*
* @return whether task should be distributed through containers
*/
public boolean isDistributive()
{
@@ -123,6 +124,7 @@ public class ResolvedTask
/**
* Returns whether task alters (mutates) it's target objects
*
* @return whether task alters (mutates) it's target objects
*/
public boolean isMutative()
{
@@ -139,6 +141,11 @@ public class ResolvedTask
return codes;
}
/**
* Returns whether task is not scripted (curation task)
*
* @return true if this task is not scripted
*/
private boolean unscripted()
{
return sTask == null;

View File

@@ -27,9 +27,13 @@ public final class TaskQueueEntry
* TaskQueueEntry constructor with enumerated field values.
*
* @param epersonId
* task owner
* @param submitTime
* time the task was submitted (System.currentTimeMillis())
* @param taskNames
* list of task names
* @param objId
* usually a handle or workflow id
*/
public TaskQueueEntry(String epersonId, long submitTime,
List<String> taskNames, String objId)

View File

@@ -120,8 +120,8 @@ public class Utils
/**
* Performs a buffered copy from one file into another.
*
* @param inFile
* @param outFile
* @param inFile input file
* @param outFile output file
* @throws IOException if IO error
*/
public static void copy(File inFile, File outFile) throws IOException

View File

@@ -54,7 +54,7 @@ import static javax.xml.stream.XMLStreamConstants.*;
public class WorkflowCuratorServiceImpl implements WorkflowCuratorService
{
/** log4j logger */
/** log4j logger */
private Logger log = Logger.getLogger(WorkflowCuratorServiceImpl.class);
protected Map<String, TaskSet> tsMap = new HashMap<String, TaskSet>();
@@ -79,6 +79,7 @@ public class WorkflowCuratorServiceImpl implements WorkflowCuratorService
* Ensures the configurationService is injected, so that we can read the
* settings from configuration
* Called by "init-method" in Spring config.
* @throws Exception ...
*/
public void init() throws Exception {
File cfgFile = new File(configurationService.getProperty("dspace.dir") +
@@ -87,7 +88,7 @@ public class WorkflowCuratorServiceImpl implements WorkflowCuratorService
try
{
loadTaskConfig(cfgFile);
if(workflowServiceFactory.getWorkflowService() instanceof BasicWorkflowItemService)
if (workflowServiceFactory.getWorkflowService() instanceof BasicWorkflowItemService)
{
basicWorkflowService = (BasicWorkflowService) workflowServiceFactory.getWorkflowService();
basicWorkflowItemService = (BasicWorkflowItemService) workflowServiceFactory.getWorkflowItemService();

View File

@@ -46,8 +46,12 @@ public interface WorkflowCuratorService {
/**
* Determines and executes curation of a Workflow item.
*
* @param curator the Curator object
* @param c the user context
* @param wfId the workflow id
* @return true if curation was completed or not required,
* false if no workflow item found for id
* or item was rejected
* @throws AuthorizeException if authorization error
* @throws IOException if IO error
* @throws SQLException if database error
@@ -55,6 +59,18 @@ public interface WorkflowCuratorService {
public boolean curate(Curator curator, Context c, String wfId)
throws AuthorizeException, IOException, SQLException;
/**
* Determines and executes curation of a Workflow item.
*
* @param curator the Curator object
* @param c the user context
* @param wfi the workflow item
* @return true if curation was completed or not required,
* false if item was rejected
* @throws AuthorizeException if authorization error
* @throws IOException if IO error
* @throws SQLException if database error
*/
public boolean curate(Curator curator, Context c, BasicWorkflowItem wfi)
throws AuthorizeException, IOException, SQLException;
}

View File

@@ -40,12 +40,17 @@ public class DiscoverHitHighlightingField {
* field containing a matching hit. e.g. If maxChars = 200
* and a hit is found in the full-text the 200 chars
* surrounding the hit will be shown
*
* @return max number of characters shown for a hit
*/
public int getMaxChars()
{
return maxChars;
}
/**
* @return max number of result snippets
*/
public int getMaxSnippets()
{
return maxSnippets;

View File

@@ -41,12 +41,15 @@ public class IndexClient {
* from the whole index
*
* @param args the command-line arguments, none used
* @throws java.io.IOException
* @throws SQLException if database error
*
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws SearchServiceException if something went wrong with querying the solr server
*/
public static void main(String[] args) throws SQLException, IOException, SearchServiceException {
public static void main(String[] args)
throws SQLException, IOException, SearchServiceException
{
Context context = new Context();
context.turnOffAuthorisationSystem();
@@ -55,46 +58,49 @@ public class IndexClient {
HelpFormatter formatter = new HelpFormatter();
CommandLine line = null;
options
.addOption(OptionBuilder
.withArgName("handle to remove")
.hasArg(true)
.withDescription(
"remove an Item, Collection or Community from index based on its handle")
.create("r"));
options.addOption(OptionBuilder
.withArgName("handle to remove")
.hasArg(true)
.withDescription(
"remove an Item, Collection or Community from index based on its handle")
.create("r"));
options
.addOption(OptionBuilder
.withArgName("handle to add or update")
.hasArg(true)
.withDescription(
"add or update an Item, Collection or Community based on its handle")
.create("i"));
options.addOption(OptionBuilder
.withArgName("handle to add or update")
.hasArg(true)
.withDescription(
"add or update an Item, Collection or Community based on its handle")
.create("i"));
options
.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"clean existing index removing any documents that no longer exist in the db")
.create("c"));
options.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"clean existing index removing any documents that no longer exist in the db")
.create("c"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"(re)build index, wiping out current one if it exists").create(
"b"));
options.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"(re)build index, wiping out current one if it exists")
.create("b"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"Rebuild the spellchecker, can be combined with -b and -f.").create(
"s"));
options.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"Rebuild the spellchecker, can be combined with -b and -f.")
.create("s"));
options
.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"if updating existing index, force each handle to be reindexed even if uptodate")
.create("f"));
options.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"if updating existing index, force each handle to be reindexed even if uptodate")
.create("f"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"print this help message").create("h"));
options.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"print this help message")
.create("h"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"optimize search core").create("o"));
@@ -118,7 +124,10 @@ public class IndexClient {
* new DSpace.getServiceManager().getServiceByName("org.dspace.discovery.SolrIndexer");
*/
IndexingService indexer = DSpaceServicesFactory.getInstance().getServiceManager().getServiceByName(IndexingService.class.getName(),IndexingService.class);
IndexingService indexer = DSpaceServicesFactory.getInstance().getServiceManager().getServiceByName(
IndexingService.class.getName(),
IndexingService.class
);
if (line.hasOption("r")) {
log.info("Removing " + line.getOptionValue("r") + " from Index");
@@ -133,9 +142,9 @@ public class IndexClient {
} else if (line.hasOption("o")) {
log.info("Optimizing search core.");
indexer.optimize();
} else if(line.hasOption('s')) {
} else if (line.hasOption('s')) {
checkRebuildSpellCheck(line, indexer);
} else if(line.hasOption('i')) {
} else if (line.hasOption('i')) {
final String handle = line.getOptionValue('i');
final DSpaceObject dso = HandleServiceFactory.getInstance().getHandleService().resolveToObject(context, handle);
if (dso == null) {
@@ -156,15 +165,31 @@ public class IndexClient {
}
log.info("Done with indexing");
}
}
/**
* Indexes the given object and all children, if applicable.
*
* @param indexingService
*
* @param itemService
*
* @param context
* The relevant DSpace Context.
* @param dso
* DSpace object to index recursively
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws SearchServiceException in case of a solr exception
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
private static long indexAll(final IndexingService indexingService,
final ItemService itemService,
final Context context,
final DSpaceObject dso) throws IOException, SearchServiceException, SQLException {
final DSpaceObject dso)
throws IOException, SearchServiceException, SQLException
{
long count = 0;
indexingService.indexContent(context, dso, true, true);
@@ -194,11 +219,27 @@ public class IndexClient {
/**
* Indexes all items in the given collection.
*
* @param indexingService
*
* @param itemService
*
* @param context
* The relevant DSpace Context.
* @param collection
* collection to index
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws SearchServiceException in case of a solr exception
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
private static long indexItems(final IndexingService indexingService,
final ItemService itemService,
final Context context,
final Collection collection) throws IOException, SearchServiceException, SQLException {
final Collection collection)
throws IOException, SearchServiceException, SQLException
{
long count = 0;
final Iterator<Item> itemIterator = itemService.findByCollection(context, collection);
@@ -220,10 +261,12 @@ public class IndexClient {
* @param indexer the solr indexer
* @throws SearchServiceException in case of a solr exception
*/
protected static void checkRebuildSpellCheck(CommandLine line, IndexingService indexer) throws SearchServiceException {
protected static void checkRebuildSpellCheck(CommandLine line, IndexingService indexer)
throws SearchServiceException
{
if (line.hasOption("s")) {
log.info("Rebuilding spell checker.");
indexer.buildSpellCheck();
}
}
}
}

View File

@@ -34,6 +34,7 @@ public interface SearchService {
* DSpace Context object.
* @param query
* the discovery query object.
* @return discovery search result object
* @throws SearchServiceException if search error
*/
DiscoverResult search(Context context, DiscoverQuery query)
@@ -50,6 +51,7 @@ public interface SearchService {
* within this object)
* @param query
* the discovery query object
* @return discovery search result object
* @throws SearchServiceException if search error
*/
DiscoverResult search(Context context, DSpaceObject dso, DiscoverQuery query)
@@ -64,6 +66,7 @@ public interface SearchService {
* @param includeWithdrawn
* use <code>true</code> to include in the results also withdrawn
* items that match the query.
* @return discovery search result object
* @throws SearchServiceException if search error
*/
DiscoverResult search(Context context, DiscoverQuery query,
@@ -81,7 +84,7 @@ public interface SearchService {
* @param includeWithdrawn
* use <code>true</code> to include in the results also withdrawn
* items that match the query
*
* @return discovery search result object
* @throws SearchServiceException if search error
*/
DiscoverResult search(Context context, DSpaceObject dso, DiscoverQuery query, boolean includeWithdrawn) throws SearchServiceException;
@@ -97,11 +100,14 @@ public interface SearchService {
/**
* Transforms the given string field and value into a filter query
* @param context the DSpace context
* @param context
* The relevant DSpace Context.
* @param field the field of the filter query
* @param operator equals/notequals/notcontains/authority/notauthority
* @param value the filter query value
* @return a filter query
* @throws SQLException if database error
* An exception that provides information on a database access error or other errors.
*/
DiscoverFilterQuery toFilterQuery(Context context, String field, String operator, String value) throws SQLException;
@@ -118,21 +124,27 @@ public interface SearchService {
* communities/collections only.
*
* @param context
* @return
* The relevant DSpace Context.
* @return query string specific to the user's rights
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
String createLocationQueryForAdministrableItems(Context context) throws SQLException;
/**
* Transforms the metadata field of the given sort configuration into the indexed field which we can then use in our solr queries
*
* @param metadataField the metadata field
* @param type @see org.dspace.discovery.configuration.DiscoveryConfigurationParameters
* @return the indexed field
*/
String toSortFieldIndex(String metadataField, String type);
/**
* Utility method to escape any special characters in a user's query
*
* @param query
* User's query to escape.
* @return query with any special characters escaped
*/
String escapeQueryChars(String query);

View File

@@ -31,28 +31,28 @@ public class SearchUtils {
public static SearchService getSearchService()
{
if(searchService == null){
if (searchService == null) {
org.dspace.kernel.ServiceManager manager = DSpaceServicesFactory.getInstance().getServiceManager();
searchService = manager.getServiceByName(SearchService.class.getName(),SearchService.class);
}
return searchService;
}
public static DiscoveryConfiguration getDiscoveryConfiguration(){
public static DiscoveryConfiguration getDiscoveryConfiguration() {
return getDiscoveryConfiguration(null);
}
public static DiscoveryConfiguration getDiscoveryConfiguration(DSpaceObject dso){
public static DiscoveryConfiguration getDiscoveryConfiguration(DSpaceObject dso) {
DiscoveryConfigurationService configurationService = getConfigurationService();
DiscoveryConfiguration result = null;
if(dso == null){
if (dso == null) {
result = configurationService.getMap().get("site");
}else{
result = configurationService.getMap().get(dso.getHandle());
}
if(result == null){
if (result == null) {
//No specific configuration, get the default one
result = configurationService.getMap().get("default");
}
@@ -73,8 +73,11 @@ public class SearchUtils {
/**
* Method that retrieves a list of all the configuration objects from the given item
* A configuration object can be returned for each parent community/collection
*
* @param item the DSpace item
* @return a list of configuration objects
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public static List<DiscoveryConfiguration> getAllDiscoveryConfigurations(Item item) throws SQLException {
Map<String, DiscoveryConfiguration> result = new HashMap<String, DiscoveryConfiguration>();
@@ -82,14 +85,14 @@ public class SearchUtils {
List<Collection> collections = item.getCollections();
for (Collection collection : collections) {
DiscoveryConfiguration configuration = getDiscoveryConfiguration(collection);
if(!result.containsKey(configuration.getId())){
if (!result.containsKey(configuration.getId())) {
result.put(configuration.getId(), configuration);
}
}
//Also add one for the default
DiscoveryConfiguration configuration = getDiscoveryConfiguration(null);
if(!result.containsKey(configuration.getId())){
if (!result.containsKey(configuration.getId())) {
result.put(configuration.getId(), configuration);
}

View File

@@ -55,6 +55,8 @@ public class DiscoveryHitHighlightFieldConfiguration
/**
* Get the maximum number of highlighted snippets to generate per field
*
* @return maximum number of highlighted snippets to generate per field
*/
public int getSnippets()
{

View File

@@ -62,10 +62,11 @@ public class EmbargoCLITool {
* <dt>-q,--quiet</dt>
* <dd> No output except upon error.</dd>
* </dl>
*
* @param argv the command line arguments given
*/
public static void main(String argv[])
{
int status = 0;
Options options = new Options();
@@ -197,7 +198,7 @@ public class EmbargoCLITool {
if (line.hasOption('a')){
embargoService.setEmbargo(context, item);
}
else{
else {
log.debug("Testing embargo on item="+item.getHandle()+", date="+liftDate.toString());
if (liftDate.toDate().before(now))
{
@@ -229,8 +230,8 @@ public class EmbargoCLITool {
}
catch (Exception e)
{
log.error("Failed attempting to lift embargo, item="+item.getHandle()+": ", e);
System.err.println("Failed attempting to lift embargo, item="+item.getHandle()+": "+ e);
log.error("Failed attempting to lift embargo, item=" + item.getHandle() + ": ", e);
System.err.println("Failed attempting to lift embargo, item=" + item.getHandle() + ": " + e);
status = true;
}
}

View File

@@ -28,8 +28,17 @@ public interface EmbargoLifter
* (access control) by (for example) turning on default read access to all
* Bitstreams.
*
* @param context the DSpace context
* @param item the Item on which to lift the embargo
* @param context
* The relevant DSpace Context.
* @param item
* the Item on which to lift the embargo
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public void liftEmbargo(Context context, Item item)
throws SQLException, AuthorizeException, IOException;

View File

@@ -171,6 +171,8 @@ public class EmbargoServiceImpl implements EmbargoService
* Ensures the configurationService is injected, so that we can
* get plugins and MD field settings from config.
* Called by "init-method" in Spring config.
*
* @throws Exception on generic exception
*/
public void init() throws Exception
{

View File

@@ -42,6 +42,11 @@ public interface EmbargoSetter
* @param item the item to embargo
* @param terms value of the metadata field configured as embargo terms, if any.
* @return absolute date on which the embargo is to be lifted, or null if none
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public DCDate parseTerms(Context context, Item item, String terms)
throws SQLException, AuthorizeException;
@@ -52,6 +57,11 @@ public interface EmbargoSetter
*
* @param context the DSpace context
* @param item the item to embargo
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public void setEmbargo(Context context, Item item)
throws SQLException, AuthorizeException;
@@ -68,6 +78,13 @@ public interface EmbargoSetter
*
* @param context the DSpace context
* @param item the item to embargo
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public void checkEmbargo(Context context, Item item)
throws SQLException, AuthorizeException, IOException;

View File

@@ -51,6 +51,11 @@ public interface EmbargoService {
*
* @param context the DSpace context
* @param item the item to embargo
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public void setEmbargo(Context context, Item item)
throws SQLException, AuthorizeException;
@@ -69,6 +74,11 @@ public interface EmbargoService {
* @param context the DSpace context
* @param item the item to embargo
* @return lift date on which the embargo is to be lifted, or null if none
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public DCDate getEmbargoTermsAsDate(Context context, Item item)
throws SQLException, AuthorizeException;
@@ -80,6 +90,13 @@ public interface EmbargoService {
*
* @param context the DSpace context
* @param item the item on which to lift the embargo
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public void liftEmbargo(Context context, Item item)
throws SQLException, AuthorizeException, IOException;

View File

@@ -107,7 +107,7 @@ public class AccountServiceImpl implements AccountService
* @param token
* Account token
* @return The EPerson corresponding to token, or null.
* @exception SQLException
* @throws SQLException
* If the token or eperson cannot be retrieved from the
* database.
*/
@@ -161,7 +161,7 @@ public class AccountServiceImpl implements AccountService
* DSpace context
* @param token
* The token to delete
* @exception SQLException
* @throws SQLException
* If a database error occurs
*/
@Override
@@ -171,7 +171,7 @@ public class AccountServiceImpl implements AccountService
registrationDataService.deleteByToken(context, token);
}
/*
/**
* THIS IS AN INTERNAL METHOD. THE SEND PARAMETER ALLOWS IT TO BE USED FOR
* TESTING PURPOSES.
*
@@ -179,15 +179,18 @@ public class AccountServiceImpl implements AccountService
* is TRUE, this is registration email; otherwise, it is forgot-password
* email. If send is TRUE, the email is sent; otherwise it is skipped.
*
* Potential error conditions: No EPerson with that email (returns null)
* Cannot create registration data in database (throws SQLException) Error
* sending email (throws MessagingException) Error reading email template
* (throws IOException) Authorization error (throws AuthorizeException)
* Potential error conditions:
* @return null if no EPerson with that email found
* @throws SQLException Cannot create registration data in database
* @throws MessagingException Error sending email
* @throws IOException Error reading email template
* @throws AuthorizeException Authorization error
*
* @param context DSpace context @param email Email address to send the
* forgot-password email to @param isRegister If true, this is for
* registration; otherwise, it is for forgot-password @param send If true,
* send email; otherwise do not send any email
* @param context DSpace context
* @param email Email address to send the forgot-password email to
* @param isRegister If true, this is for registration; otherwise, it is
* for forgot-password
* @param send If true, send email; otherwise do not send any email
*/
protected RegistrationData sendInfo(Context context, String email,
boolean isRegister, boolean send) throws SQLException, IOException,
@@ -234,17 +237,21 @@ public class AccountServiceImpl implements AccountService
* If isRegister is <code>true</code>, this is registration email;
* otherwise, it is a forgot-password email.
*
* @param context
* The relevant DSpace Context.
* @param email
* The email address to mail to
* The email address to mail to
* @param isRegister
* If true, this is registration email; otherwise it is
* forgot-password email.
* If true, this is registration email; otherwise it is
* forgot-password email.
* @param rd
* The RDBMS row representing the registration data.
* @exception MessagingException
* If an error occurs while sending email
* @exception IOException
* If an error occurs while reading the email template.
* The RDBMS row representing the registration data.
* @throws MessagingException
* If an error occurs while sending email
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
protected void sendEmail(Context context, String email, boolean isRegister, RegistrationData rd)
throws MessagingException, IOException, SQLException
@@ -271,4 +278,4 @@ public class AccountServiceImpl implements AccountService
+ " information to " + email);
}
}
}
}

View File

@@ -165,8 +165,12 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
* Locale specification of the form {language} or {language}_{territory},
* e.g. "en", "en_US", "pt_BR" (the latter is Brazilian Portugese).
*
* @param context
* The relevant DSpace Context.
* @param language
* language code
* language code
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public void setLanguage(Context context, String language) throws SQLException {
getePersonService().setMetadataSingleValue(context, this, "eperson", "language", null, null, language);
@@ -186,7 +190,7 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
* Set the EPerson's email
*
* @param s
* the new email
* the new email
*/
public void setEmail(String s)
{
@@ -208,7 +212,7 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
* Set the EPerson's netid
*
* @param netid
* the new netid
* the new netid
*/
public void setNetid(String netid) {
this.netid = netid;
@@ -253,8 +257,12 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
/**
* Set the eperson's first name
*
* @param context
* The relevant DSpace Context.
* @param firstname
* the person's first name
* the person's first name
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public void setFirstName(Context context, String firstname) throws SQLException {
getePersonService().setMetadataSingleValue(context, this, "eperson", "firstname", null, null, firstname);
@@ -274,8 +282,12 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
/**
* Set the eperson's last name
*
* @param context
* The relevant DSpace Context.
* @param lastname
* the person's last name
* the person's last name
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public void setLastName(Context context, String lastname) throws SQLException {
getePersonService().setMetadataSingleValue(context, this, "eperson", "lastname", null, null, lastname);
@@ -286,7 +298,7 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
* Indicate whether the user can log in
*
* @param login
* boolean yes/no
* boolean yes/no
*/
public void setCanLogIn(boolean login)
{
@@ -308,7 +320,7 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
* Set require cert yes/no
*
* @param isrequired
* boolean yes/no
* boolean yes/no
*/
public void setRequireCertificate(boolean isrequired)
{
@@ -330,7 +342,7 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
* Indicate whether the user self-registered
*
* @param sr
* boolean yes/no
* boolean yes/no
*/
public void setSelfRegistered(boolean sr)
{
@@ -369,7 +381,7 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport
}
/**
* return type found in Constants
* @return type found in Constants, see {@link org.dspace.core.Constants#Constants Constants}
*/
@Override
public int getType()

View File

@@ -45,6 +45,15 @@ public class EPersonCLITool {
/**
* Tool for manipulating user accounts.
*
* @param argv the command line arguments given
* @throws ParseException
* Base for Exceptions thrown during parsing of a command-line. {@see org.apache.commons.cli.ParseException}
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public static void main(String argv[])
throws ParseException, SQLException, AuthorizeException {

View File

@@ -50,7 +50,9 @@ public class EPersonConsumer implements Consumer
* Consume the event
*
* @param context
* The relevant DSpace Context.
* @param event
* Which Event to consume
* @throws Exception if error
*/
@Override
@@ -116,6 +118,7 @@ public class EPersonConsumer implements Consumer
* Handle the end of the event
*
* @param ctx
* The relevant DSpace Context.
* @throws Exception if error
*/
@Override
@@ -129,6 +132,7 @@ public class EPersonConsumer implements Consumer
* Finish the event
*
* @param ctx
* The relevant DSpace Context.
*/
@Override
public void finish(Context ctx)

View File

@@ -39,6 +39,10 @@ public class Groomer
private static final EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
/**
* Command line tool for "grooming" the EPerson collection.
*
* @param argv the command line arguments given
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
static public void main(String[] argv)
throws SQLException

View File

@@ -40,7 +40,7 @@ public class Group extends DSpaceObject implements DSpaceObjectLegacySupport
public static final String ADMIN = "Administrator";
/**
* Initial value is set to 2 since 0 & 1 are reserved for anonymous & administrative uses
* Initial value is set to 2 since 0 and 1 are reserved for anonymous and administrative uses, respectively
*/
@Column(name="eperson_group_id", insertable = false, updatable = false)
private Integer legacyId;
@@ -95,6 +95,8 @@ public class Group extends DSpaceObject implements DSpaceObjectLegacySupport
/**
* Return EPerson members of a Group
*
* @return list of EPersons
*/
public List<EPerson> getMembers()
{
@@ -146,6 +148,8 @@ public class Group extends DSpaceObject implements DSpaceObjectLegacySupport
/**
* Return Group members of a Group.
*
* @return list of groups
*/
public List<Group> getMemberGroups()
{

View File

@@ -167,16 +167,16 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
if (StringUtils.equals(groupName, Group.ANONYMOUS))
{
return true;
} else if(context.getCurrentUser() != null) {
} else if (context.getCurrentUser() != null) {
EPerson currentUser = context.getCurrentUser();
//First check the special groups
List<Group> specialGroups = context.getSpecialGroups();
if(CollectionUtils.isNotEmpty(specialGroups)) {
if (CollectionUtils.isNotEmpty(specialGroups)) {
for (Group specialGroup : specialGroups)
{
//Check if the current special group is the one we are looking for OR retrieve all groups & make a check here.
if(StringUtils.equals(specialGroup.getName(), groupName) || allMemberGroups(context, currentUser).contains(findByName(context, groupName)))
if (StringUtils.equals(specialGroup.getName(), groupName) || allMemberGroups(context, currentUser).contains(findByName(context, groupName)))
{
return true;
}
@@ -251,7 +251,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
@Override
public Group find(Context context, UUID id) throws SQLException {
if(id == null) {
if (id == null) {
return null;
} else {
return groupDAO.findByID(context, Group.class, id);
@@ -260,7 +260,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
@Override
public Group findByName(Context context, String name) throws SQLException {
if(name == null)
if (name == null)
{
return null;
}
@@ -272,7 +272,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
@Override
@Deprecated
public List<Group> findAll(Context context, int sortField) throws SQLException {
if(sortField == GroupService.NAME) {
if (sortField == GroupService.NAME) {
return findAll(context, null);
} else {
throw new UnsupportedOperationException("You can only find all groups sorted by name with this method");
@@ -282,7 +282,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
@Override
public List<Group> findAll(Context context, List<MetadataField> metadataSortFields) throws SQLException
{
if(CollectionUtils.isEmpty(metadataSortFields)) {
if (CollectionUtils.isEmpty(metadataSortFields)) {
return groupDAO.findAll(context);
} else {
return groupDAO.findAll(context, metadataSortFields);
@@ -299,13 +299,13 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
{
List<Group> groups = new ArrayList<>();
UUID uuid = UUIDUtils.fromString(groupIdentifier);
if(uuid == null) {
if (uuid == null) {
//Search by group name
groups = groupDAO.findByNameLike(context, groupIdentifier, offset, limit);
} else {
//Search by group id
Group group = find(context, uuid);
if(group != null)
if (group != null)
{
groups.add(group);
}
@@ -318,13 +318,13 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
public int searchResultCount(Context context, String groupIdentifier) throws SQLException {
int result = 0;
UUID uuid = UUIDUtils.fromString(groupIdentifier);
if(uuid == null && StringUtils.isNotBlank(groupIdentifier)) {
if (uuid == null && StringUtils.isNotBlank(groupIdentifier)) {
//Search by group name
result = groupDAO.countByNameLike(context, groupIdentifier);
} else {
//Search by group id
Group group = find(context, uuid);
if(group != null)
if (group != null)
{
result = 1;
}
@@ -407,7 +407,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
// Check for Anonymous group. If not found, create it
Group anonymousGroup = groupService.findByName(context, Group.ANONYMOUS);
if(anonymousGroup==null)
if (anonymousGroup==null)
{
anonymousGroup = groupService.create(context);
anonymousGroup.setName(Group.ANONYMOUS);
@@ -418,7 +418,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
// Check for Administrator group. If not found, create it
Group adminGroup = groupService.findByName(context, Group.ADMIN);
if(adminGroup == null)
if (adminGroup == null)
{
adminGroup = groupService.create(context);
adminGroup.setName(Group.ADMIN);
@@ -427,6 +427,15 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
}
}
/**
* Get a list of groups with no members.
*
* @param context
* The relevant DSpace Context.
* @return list of groups with no members
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
@Override
public List<Group> getEmptyGroups(Context context) throws SQLException {
return groupDAO.getEmptyGroups(context);
@@ -434,6 +443,16 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
/**
* Update the group - writing out group object and EPerson list if necessary
*
* @param context
* The relevant DSpace Context.
* @param group
* Group to update
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
@Override
public void update(Context context, Group group) throws SQLException, AuthorizeException
@@ -449,7 +468,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
group.clearDetails();
}
if(group.isGroupsChanged())
if (group.isGroupsChanged())
{
rethinkGroupCache(context, true);
group.clearGroupsChanged();
@@ -473,6 +492,12 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
* Regenerate the group cache AKA the group2groupcache table in the database -
* meant to be called when a group is added or removed from another group
*
* @param context
* The relevant DSpace Context.
* @param flushQueries
* flushQueries Flush all pending queries
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
protected void rethinkGroupCache(Context context, boolean flushQueries) throws SQLException {
@@ -521,7 +546,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
Group childGroup = find(context, child);
if(parentGroup != null && childGroup != null && group2GroupCacheDAO.find(context, parentGroup, childGroup) == null)
if (parentGroup != null && childGroup != null && group2GroupCacheDAO.find(context, parentGroup, childGroup) == null)
{
Group2GroupCache group2GroupCache = group2GroupCacheDAO.create(context, new Group2GroupCache());
group2GroupCache.setParent(parentGroup);
@@ -535,7 +560,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
@Override
public DSpaceObject getParentObject(Context context, Group group) throws SQLException
{
if(group == null)
if (group == null)
{
return null;
}
@@ -647,7 +672,7 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl<Group> implements
@Override
public Group findByIdOrLegacyId(Context context, String id) throws SQLException {
if(org.apache.commons.lang.StringUtils.isNumeric(id))
if (org.apache.commons.lang.StringUtils.isNumeric(id))
{
return findByLegacyId(context, Integer.parseInt(id));
}

View File

@@ -57,8 +57,14 @@ public class SubscribeCLITool {
* For example, if today's date is 2002-10-10 (in UTC) items made available
* during 2002-10-09 (UTC) will be included.
*
* @param context DSpace context object
* @param context
* The relevant DSpace Context.
* @param test
* If true, do a "dry run", i.e. don't actually send email, just log the attempt
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
*/
public static void processDaily(Context context, boolean test) throws SQLException,
IOException {
@@ -115,6 +121,13 @@ public class SubscribeCLITool {
* @param eperson eperson to send to
* @param collections List of collection IDs (Integers)
* @param test
* If true, do a "dry run", i.e. don't actually send email, just log the attempt
* @throws IOException
* A general class of exceptions produced by failed or interrupted I/O operations.
* @throws MessagingException
* A general class of exceptions for sending email.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public static void sendEmail(Context context, EPerson eperson,
List<Collection> collections, boolean test) throws IOException, MessagingException,
@@ -245,7 +258,7 @@ public class SubscribeCLITool {
/**
* Method for invoking subscriptions via the command line
*
* @param argv command-line arguments, none used yet
* @param argv the command line arguments given
*/
public static void main(String[] argv) {
String usage = "org.dspace.eperson.Subscribe [-t] or nothing to send out subscriptions.";

View File

@@ -45,7 +45,13 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
/**
* Find the eperson by their email address.
*
* @param context
* The relevant DSpace Context.
* @param email
* EPerson's email to search by
* @return EPerson, or {@code null} if none such exists.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public EPerson findByEmail(Context context, String email)
throws SQLException;
@@ -54,11 +60,13 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
* Find the eperson by their netid.
*
* @param context
* DSpace context
* The relevant DSpace Context.
* @param netId
* Network ID
* Network ID
*
* @return corresponding EPerson, or <code>null</code>
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public EPerson findByNetid(Context context, String netId)
throws SQLException;
@@ -67,11 +75,13 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
* Find the epeople that match the search query across firstname, lastname or email.
*
* @param context
* DSpace context
* The relevant DSpace Context.
* @param query
* The search string
* The search string
*
* @return array of EPerson objects
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public List<EPerson> search(Context context, String query)
throws SQLException;
@@ -82,15 +92,17 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
* This method also allows offsets and limits for pagination purposes.
*
* @param context
* DSpace context
* The relevant DSpace Context.
* @param query
* The search string
* The search string
* @param offset
* Inclusive offset
* Inclusive offset
* @param limit
* Maximum number of matches returned
* Maximum number of matches returned
*
* @return array of EPerson objects
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public List<EPerson> search(Context context, String query, int offset, int limit)
throws SQLException;
@@ -100,11 +112,13 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
* of creating the EPerson objects to store the results.
*
* @param context
* DSpace context
* The relevant DSpace Context.
* @param query
* The search string
* The search string
*
* @return the number of epeople matching the query
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public int searchResultCount(Context context, String query)
throws SQLException;
@@ -118,7 +132,13 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
* <li><code>NETID</code></li>
* </ul>
*
* @param context
* The relevant DSpace Context.
* @param sortField
* which field to sort EPersons by
* @return array of EPerson objects
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public List<EPerson> findAll(Context context, int sortField)
throws SQLException;
@@ -127,7 +147,13 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
* Create a new eperson
*
* @param context
* DSpace context object
* The relevant DSpace Context.
* @return the created EPerson
* @throws SQLException
* An exception that provides information on a database access error or other errors.
* @throws AuthorizeException
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*/
public EPerson create(Context context) throws SQLException,
AuthorizeException;
@@ -135,22 +161,28 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
/**
* Set the EPerson's password.
*
* @param ePerson
* EPerson whose password we want to set.
* @param password
* the new password.
* the new password.
*/
public void setPassword(EPerson ePerson, String password);
/**
* Set the EPerson's password hash.
*
* @param ePerson
* EPerson whose password hash we want to set.
* @param password
* hashed password, or null to set row data to NULL.
* hashed password, or null to set row data to NULL.
*/
public void setPasswordHash(EPerson ePerson, PasswordHash password);
/**
* Return the EPerson's password hash.
*
* @param ePerson
* EPerson whose password hash we want to get.
* @return hash of the password, or null on failure (such as no password).
*/
public PasswordHash getPasswordHash(EPerson ePerson);
@@ -159,33 +191,56 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
* Check EPerson's password. Side effect: original unsalted MD5 hashes are
* converted using the current algorithm.
*
* @param context
* The relevant DSpace Context.
* @param ePerson
* EPerson whose password we want to check
* @param attempt
* the password attempt
* the password attempt
* @return boolean successful/unsuccessful
*/
public boolean checkPassword(Context context, EPerson ePerson, String attempt);
/**
* Set a metadata value
* Set a metadata value (in the metadatavalue table) of the metadata field
* specified by 'field'.
*
* @param context
* The relevant DSpace Context.
* @param ePerson
* EPerson whose metadata we want to set.
* @param field
* the name of the metadata field to set
* Metadata field we want to set (e.g. "phone").
* @param value
* value to set the field to
*
* @exception IllegalArgumentException
* if the requested metadata field doesn't exist
* Metadata value we want to set
* @throws SQLException
* if the requested metadata field doesn't exist
*/
@Deprecated
public void setMetadata(Context context, EPerson ePerson, String field, String value) throws SQLException;
/**
* Retrieve all accounts which have a password but do not have a digest algorithm
* @param context the dspace context
*
* @param context
* The relevant DSpace Context.
* @return a list of epeople
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public List<EPerson> findUnsalted(Context context) throws SQLException;
/**
* Retrieve all accounts which have not logged in since the specified date
*
* @param context
* The relevant DSpace Context.
* @param date
* from which date
* @return a list of epeople
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public List<EPerson> findNotActiveSince(Context context, Date date) throws SQLException;
/**
@@ -196,13 +251,48 @@ public interface EPersonService extends DSpaceObjectService<EPerson>, DSpaceObje
* An EPerson cannot be deleted if it exists in the item, workflowitem, or
* tasklistitem tables.
*
* @param context
* The relevant DSpace Context.
* @param ePerson
* EPerson to find
* @return List of tables that contain a reference to the eperson.
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public List<String> getDeleteConstraints(Context context, EPerson ePerson) throws SQLException;
/**
* Retrieve all accounts which belong to at least one of the specified groups.
*
* @param c
* The relevant DSpace Context.
* @param groups
* set of eperson groups
* @return a list of epeople
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
public List<EPerson> findByGroups(Context c, Set<Group> groups) throws SQLException;
/**
* Retrieve all accounts which are subscribed to receive information about new items.
*
* @param context
* The relevant DSpace Context.
* @return a list of epeople
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
List<EPerson> findEPeopleWithSubscription(Context context) throws SQLException;
/**
* Count all accounts.
*
* @param context
* The relevant DSpace Context.
* @return the total number of epeople
* @throws SQLException
* An exception that provides information on a database access error or other errors.
*/
int countTotal(Context context) throws SQLException;
}

Some files were not shown because too many files have changed in this diff Show More